commit b38c0270ff519bc44b7e4cb3dc37c4a971e282d6 Author: gac-bernina Date: Wed Apr 28 09:14:56 2021 +0200 Initial Commit diff --git a/config/config.properties b/config/config.properties new file mode 100755 index 0000000..f93e499 --- /dev/null +++ b/config/config.properties @@ -0,0 +1,45 @@ +#Tue Apr 27 16:22:56 CEST 2021 +autoSaveScanData=true +simulation=false +commandExecutionEvents=false +logDaysToLive=50 +dataScanSaveOutput=false +userAuthenticator= +logLevelConsole=Off +scanStreamerPort=-1 +dataScanSaveScript=false +dataScanSaveSetpoints=false +notifiedTasks=null +parallelInitialization=false +dataTransferPath=null +saveConsoleSessionFiles=false +versionTrackingManual=true +dataTransferMode=null +hostName=null +userManagement=false +instanceName=BE +disableEmbeddedAttributes=false +dataServerPort=-1 +hideServerMessages=false +serverPort=8080 +versionTrackingEnabled=true +dataPath={data}/{year}_{month}/{date}/{date}_{time}_{name} +serverEnabled=false +dataScanReleaseRecords=false +depthDimension=0 +dataScanPreserveTypes=false +logLevel=Info +dataScanFlushRecords=false +logPath={logs}/{date}_{time} +dataLayout=default +disableDataFileLogs=false +sessionHandling=null +terminalEnabled=false +notificationLevel=Off +terminalPort=3579 +dataTransferUser=null +createSessionFiles=false +versionTrackingLogin= +versionTrackingRemote= +dataProvider=h5 +saveCommandStatistics=false diff --git a/config/devices.properties b/config/devices.properties new file mode 100755 index 0000000..8fcd56a --- /dev/null +++ b/config/devices.properties @@ -0,0 +1,16 @@ +dispatcher=ch.psi.pshell.bs.Dispatcher|https://dispatcher-api.psi.ch/sf||| +cam_server=ch.psi.pshell.bs.PipelineServer|sf-daqsync-01:8889||| +cam_n=ch.psi.pshell.imaging.MjpegSource|http://bernina-cam-n/axis-cgi/mjpg/video.cgi reopen||-200|false +cam_s=ch.psi.pshell.imaging.MjpegSource|http://bernina-cam-s/axis-cgi/mjpg/video.cgi reopen||-200| +cam_w=ch.psi.pshell.imaging.MjpegSource|http://bernina-cam-w/axis-cgi/mjpg/video.cgi reopen||-200| +cam_mobile=ch.psi.pshell.imaging.MjpegSource|http://bernina-cam-mobile/axis-cgi/mjpg/video.cgi reopen||-200| +energy_machine=ch.psi.pshell.epics.ChannelDouble|SARFE10-PBPG050:ENERGY|||true +psss_energy=ch.psi.pshell.epics.ChannelDouble|SARFE10-PSSS059:ENERGY|||true +psss_spectrum_x=ch.psi.pshell.epics.ChannelDoubleArray|SARFE10-PSSS059:SPECTRUM_X -1 -3|||true +psss_spectrum_y=ch.psi.pshell.epics.ChannelDoubleArray|SARFE10-PSSS059:SPECTRUM_Y -1 -3|||true +psss_center=ch.psi.pshell.epics.ChannelDouble|SARFE10-PSSS059:SPECTRUM_CENTER|||true +psss_fwhm=ch.psi.pshell.epics.ChannelDouble|SARFE10-PSSS059:SPECTRUM_FWHM|||true +psss_roi_min=ch.psi.pshell.epics.ChannelInteger|SARFE10-PSSS059:SPC_ROI_YMIN|||true +psss_roi_max=ch.psi.pshell.epics.ChannelInteger|SARFE10-PSSS059:SPC_ROI_YMAX|||true +histo_center=ch.psi.pshell.device.HistogramGenerator|psss_center|||true +histo_fwhm=ch.psi.pshell.device.HistogramGenerator|psss_fwhm|||true diff --git a/config/jcae.properties b/config/jcae.properties new file mode 100755 index 0000000..0e02d88 --- /dev/null +++ b/config/jcae.properties @@ -0,0 +1,12 @@ +#Mon Feb 22 20:35:07 CET 2021 +ch.psi.jcae.ContextFactory.addressList= +ch.psi.jcae.ContextFactory.serverPort= +ch.psi.jcae.ContextFactory.maxArrayBytes=50000000 +ch.psi.jcae.ChannelFactory.retries=1 +ch.psi.jcae.ChannelFactory.timeout=1250 +ch.psi.jcae.impl.DefaultChannelService.retries=4 +ch.psi.jcae.impl.DefaultChannelService.timeout=1000 +ch.psi.jcae.ContextFactory.autoAddressList=true +ch.psi.jcae.ContextFactory.useShellVariables=true +ch.psi.jcae.ContextFactory.addLocalBroadcastInterfaces=false +ch.psi.jcae.ContextFactory.maxSendArrayBytes=1000000 diff --git a/config/mail.properties b/config/mail.properties new file mode 100755 index 0000000..852ac26 --- /dev/null +++ b/config/mail.properties @@ -0,0 +1,9 @@ +#Mon Nov 27 17:25:22 CET 2017 +auth=None +from= +host= +port=0 +pwd= +smsSuffix=@sms.switch.ch +to= +usr= diff --git a/config/plugins.properties b/config/plugins.properties new file mode 100755 index 0000000..4886f34 --- /dev/null +++ b/config/plugins.properties @@ -0,0 +1,13 @@ +Correlation.java=disabled +ScreenPanel2.java=disabled +ScreenPanel3.java=disabled +ScreenPanel4.java=disabled +ScreenPanel5.java=disabled +ScreenPanel6.java=disabled +PSSS.java=enabled +MonitoringCameras.java=disabled +Chris.java=disabled +SfCamera.java=enabled +ScreenPanel.java=disabled +CameraCalibrationDialog.java=disabled +Inventory.java=disabled diff --git a/config/setup.properties b/config/setup.properties new file mode 100755 index 0000000..d5a5f27 --- /dev/null +++ b/config/setup.properties @@ -0,0 +1,23 @@ +#Thu Feb 25 14:38:29 CET 2021 +sessionsPath={outp}/sessions +scriptPath={home}/script +pluginsPath={home}/plugins +configFileDevices={config}/devices.properties +consoleSessionsPath={sessions}/console +libraryPath={script}; {script}/Lib +configFilePlugins={config}/plugins.properties +contextPath={outp}/context +extensionsPath={home}/extensions +configPath={home}/config +configFileSessions={config}/sessions.properties +userSessionsPath={sessions}/user +dataPath={outp}/data +devicesPath={home}/devices +configFileVariables={config}/variables.properties +configFileSettings={config}/settings.properties +logPath={outp}/log +wwwPath={home}/www +imagesPath={outp}/images +configFile={config}/config.properties +scriptType=py +configFileTasks={config}/tasks.properties diff --git a/config/variables.properties b/config/variables.properties new file mode 100755 index 0000000..21b6b8e --- /dev/null +++ b/config/variables.properties @@ -0,0 +1,4 @@ +#Tue Apr 27 16:17:59 CEST 2021 +LastRunDate=210415 +FileSequentialNumber=81 +DaySequentialNumber=0 diff --git a/devices/CamServer.properties b/devices/CamServer.properties new file mode 100755 index 0000000..5513403 --- /dev/null +++ b/devices/CamServer.properties @@ -0,0 +1,25 @@ +#Sat Jun 08 12:02:12 CEST 2019 +colormap=Grayscale +colormapAutomatic=false +colormapLogarithmic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/devices/Camera Server.properties b/devices/Camera Server.properties new file mode 100755 index 0000000..ad6bc3e --- /dev/null +++ b/devices/Camera Server.properties @@ -0,0 +1,25 @@ +#Tue Jun 25 21:48:15 CEST 2019 +colormap=Grayscale +colormapAutomatic=false +colormapLogarithmic=false +colormapMax=NaN +colormapMin=NaN +flipHorizontally=false +flipVertically=false +grayscale=false +invert=false +rescaleFactor=1.0 +rescaleOffset=0.0 +roiHeight=-1 +roiWidth=-1 +roiX=0 +roiY=0 +rotation=0.0 +rotationCrop=false +scale=1.0 +spatialCalOffsetX=NaN +spatialCalOffsetY=NaN +spatialCalScaleX=NaN +spatialCalScaleY=NaN +spatialCalUnits=mm +transpose=false diff --git a/devices/Center Histogram.properties b/devices/Center Histogram.properties new file mode 100755 index 0000000..d64e661 --- /dev/null +++ b/devices/Center Histogram.properties @@ -0,0 +1,6 @@ +#Fri Feb 26 13:59:45 CET 2021 +bins=0 +min=NaN +max=NaN +precision=-1 +numberOfSamples=0 diff --git a/devices/CurrentCamera.properties b/devices/CurrentCamera.properties new file mode 100755 index 0000000..7f74a53 --- /dev/null +++ b/devices/CurrentCamera.properties @@ -0,0 +1,32 @@ +#Mon Apr 26 11:55:34 CEST 2021 +\u0000\u0000\u0000\u0000= +=0 +spatialCalOffsetY=-211.42799182512672 +spatialCalOffsetX=-274.41641995560866 +colormapLogarithmic=false +scale=1.0 +grayscale=false +spatialCalScaleX=-2.0325203289739266 +spatialCalScaleY=-2.024291558875032 +colormapMax=220.0 +Y=0 +rescaleOffset=0.0 +roiWidth=-1 +colormap=Temperature +imageWidth=1280 +invert=false +colormapMin=6.0 +rotation=0.0 +rotationCrop=false +rescaleFactor=1.0 +imageHeight=1024 +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +flipHorizontally=false +colormapAutomatic=true +roiY=0 +roiX=0 +transpose=false +regionStartX=1 +regionStartY=1 diff --git a/devices/Image Averager.properties b/devices/Image Averager.properties new file mode 100755 index 0000000..852062c --- /dev/null +++ b/devices/Image Averager.properties @@ -0,0 +1,25 @@ +#Thu Oct 03 04:51:06 CEST 2019 +spatialCalOffsetY=-301.6105501758777 +spatialCalOffsetX=-234.3556284010104 +colormapLogarithmic=false +scale=1.0 +grayscale=false +spatialCalScaleX=-0.5345394633098939 +spatialCalScaleY=-0.6305263124663254 +colormapMax=5000.0 +rescaleOffset=0.0 +roiWidth=-1 +colormap=Grayscale +invert=false +colormapMin=10.0 +rotation=0.0 +rotationCrop=false +rescaleFactor=1.0 +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +flipHorizontally=false +colormapAutomatic=false +roiY=0 +roiX=0 +transpose=false diff --git a/devices/Time.properties b/devices/Time.properties new file mode 100755 index 0000000..b1a9d76 --- /dev/null +++ b/devices/Time.properties @@ -0,0 +1,10 @@ +#Wed Feb 26 11:49:58 CET 2020 +minValue=NaN +unit=null +offset=0.0 +maxValue=NaN +rotation=false +precision=-1 +sign_bit=0 +scale=1.0 +resolution=NaN diff --git a/devices/cam_mobile.properties b/devices/cam_mobile.properties new file mode 100755 index 0000000..804bb36 --- /dev/null +++ b/devices/cam_mobile.properties @@ -0,0 +1,20 @@ +#Fri Feb 19 09:52:28 CET 2021 +spatialCalOffsetY=NaN +invert=false +spatialCalOffsetX=NaN +rotation=0.0 +rotationCrop=false +scale=1.0 +rescaleFactor=1.0 +grayscale=false +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +spatialCalScaleX=NaN +spatialCalScaleY=NaN +flipHorizontally=false +roiY=0 +roiX=0 +rescaleOffset=0.0 +transpose=false +roiWidth=-1 diff --git a/devices/cam_n.properties b/devices/cam_n.properties new file mode 100755 index 0000000..2eb9cb7 --- /dev/null +++ b/devices/cam_n.properties @@ -0,0 +1,20 @@ +#Fri Feb 19 09:50:36 CET 2021 +spatialCalOffsetY=NaN +invert=false +spatialCalOffsetX=NaN +rotation=0.0 +rotationCrop=false +scale=1.0 +rescaleFactor=1.0 +grayscale=false +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +spatialCalScaleX=NaN +spatialCalScaleY=NaN +flipHorizontally=false +roiY=0 +roiX=0 +rescaleOffset=0.0 +transpose=false +roiWidth=-1 diff --git a/devices/cam_s.properties b/devices/cam_s.properties new file mode 100755 index 0000000..804bb36 --- /dev/null +++ b/devices/cam_s.properties @@ -0,0 +1,20 @@ +#Fri Feb 19 09:52:28 CET 2021 +spatialCalOffsetY=NaN +invert=false +spatialCalOffsetX=NaN +rotation=0.0 +rotationCrop=false +scale=1.0 +rescaleFactor=1.0 +grayscale=false +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +spatialCalScaleX=NaN +spatialCalScaleY=NaN +flipHorizontally=false +roiY=0 +roiX=0 +rescaleOffset=0.0 +transpose=false +roiWidth=-1 diff --git a/devices/cam_server.properties b/devices/cam_server.properties new file mode 100755 index 0000000..8773076 --- /dev/null +++ b/devices/cam_server.properties @@ -0,0 +1,25 @@ +#Thu Feb 25 15:32:21 CET 2021 +colormapLogarithmic=false +spatialCalScaleX=-1.0 +spatialCalScaleY=-1.0 +rescaleOffset=0.0 +roiWidth=-1 +colormap=Grayscale +invert=false +colormapMin=0.0 +rotationCrop=false +roiHeight=-1 +colormapAutomatic=false +roiY=0 +roiX=0 +spatialCalOffsetY=-50.02315886984715 +spatialCalOffsetX=-50.01953888237593 +scale=1.0 +grayscale=false +colormapMax=255.0 +rotation=0.0 +rescaleFactor=1.0 +spatialCalUnits=mm +flipVertically=false +flipHorizontally=false +transpose=false diff --git a/devices/cam_w.properties b/devices/cam_w.properties new file mode 100755 index 0000000..804bb36 --- /dev/null +++ b/devices/cam_w.properties @@ -0,0 +1,20 @@ +#Fri Feb 19 09:52:28 CET 2021 +spatialCalOffsetY=NaN +invert=false +spatialCalOffsetX=NaN +rotation=0.0 +rotationCrop=false +scale=1.0 +rescaleFactor=1.0 +grayscale=false +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +spatialCalScaleX=NaN +spatialCalScaleY=NaN +flipHorizontally=false +roiY=0 +roiX=0 +rescaleOffset=0.0 +transpose=false +roiWidth=-1 diff --git a/devices/dispatcher.properties b/devices/dispatcher.properties new file mode 100755 index 0000000..9891517 --- /dev/null +++ b/devices/dispatcher.properties @@ -0,0 +1,13 @@ +#Wed Jun 03 18:45:57 CEST 2020 +sendStrategy=complete_all +dropIncomplete=false +keepListeningOnStop=false +disableCompression=false +parallelHandlerProcessing=true +sendBuildChannelConfig=at_startup +sendAwaitFirstMessage=false +socketType=DEFAULT +validationInconsistency=keep_as_is +byteBufferAllocator=false +mappingIncomplete=fill_null +sendSyncTimeout=0 diff --git a/devices/dp1.properties b/devices/dp1.properties new file mode 100755 index 0000000..5e9124f --- /dev/null +++ b/devices/dp1.properties @@ -0,0 +1,11 @@ +#Fri Jan 29 16:28:42 CET 2021 +motor7=null +motor8=null +motor5=null +motor6=null +precision=-1 +positions=Park|Ready|Out|Clear +motor3=null +motor4=null +motor1=0.0|4.0|8.0|0.0 +motor2=0.0|5.0|3.0|NaN diff --git a/devices/histo_center.properties b/devices/histo_center.properties new file mode 100755 index 0000000..99d6128 --- /dev/null +++ b/devices/histo_center.properties @@ -0,0 +1,6 @@ +#Tue Apr 27 16:40:07 CEST 2021 +bins=100 +min=11340.0 +max=11260.0 +precision=-1 +numberOfSamples=100 diff --git a/devices/histo_fwhm.properties b/devices/histo_fwhm.properties new file mode 100755 index 0000000..54c238d --- /dev/null +++ b/devices/histo_fwhm.properties @@ -0,0 +1,6 @@ +#Fri Feb 26 14:09:58 CET 2021 +bins=100 +min=0.0 +max=200.0 +precision=-1 +numberOfSamples=100 diff --git a/devices/m1.properties b/devices/m1.properties new file mode 100755 index 0000000..21f7399 --- /dev/null +++ b/devices/m1.properties @@ -0,0 +1,16 @@ +#Fri Jan 29 16:28:42 CET 2021 +offset=0.0 +maxValue=10.0 +rotation=false +precision=2 +scale=1.0 +estbilizationDelay=0 +maxSpeed=10.0 +resolution=NaN +startRetries=1 +minValue=-10.0 +unit=mm +defaultSpeed=1.0 +sign_bit=0 +monitorByPosition=false +minSpeed=0.1 diff --git a/devices/m2.properties b/devices/m2.properties new file mode 100755 index 0000000..21f7399 --- /dev/null +++ b/devices/m2.properties @@ -0,0 +1,16 @@ +#Fri Jan 29 16:28:42 CET 2021 +offset=0.0 +maxValue=10.0 +rotation=false +precision=2 +scale=1.0 +estbilizationDelay=0 +maxSpeed=10.0 +resolution=NaN +startRetries=1 +minValue=-10.0 +unit=mm +defaultSpeed=1.0 +sign_bit=0 +monitorByPosition=false +minSpeed=0.1 diff --git a/devices/p1.properties b/devices/p1.properties new file mode 100755 index 0000000..f144d8f --- /dev/null +++ b/devices/p1.properties @@ -0,0 +1,10 @@ +#Fri Jan 29 16:28:42 CET 2021 +minValue=0.0 +unit=mm +offset=0.0 +maxValue=1000.0 +rotation=false +precision=-1 +sign_bit=0 +scale=1.0 +resolution=NaN diff --git a/devices/ps.properties b/devices/ps.properties new file mode 100755 index 0000000..21fd4d2 --- /dev/null +++ b/devices/ps.properties @@ -0,0 +1,26 @@ +#Wed Feb 24 15:21:01 CET 2021 +spatialCalOffsetY=NaN +spatialCalOffsetX=NaN +colormapLogarithmic=false +scale=1.0 +grayscale=false +spatialCalScaleX=NaN +spatialCalScaleY=NaN +colormapMax=NaN +serverURL=localhost\:8889 +rescaleOffset=0.0 +roiWidth=-1 +colormap=Grayscale +invert=false +colormapMin=NaN +rotation=0.0 +rotationCrop=false +rescaleFactor=1.0 +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +flipHorizontally=false +colormapAutomatic=false +roiY=0 +roiX=0 +transpose=false diff --git a/devices/src1.properties b/devices/src1.properties new file mode 100755 index 0000000..e7dcdf0 --- /dev/null +++ b/devices/src1.properties @@ -0,0 +1,25 @@ +#Fri Jan 29 16:28:47 CET 2021 +spatialCalOffsetY=NaN +spatialCalOffsetX=NaN +colormapLogarithmic=false +scale=1.0 +grayscale=false +spatialCalScaleX=NaN +spatialCalScaleY=NaN +colormapMax=NaN +rescaleOffset=0.0 +roiWidth=-1 +colormap=Temperature +invert=false +colormapMin=NaN +rotation=0.0 +rotationCrop=false +rescaleFactor=1.0 +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +flipHorizontally=false +colormapAutomatic=true +roiY=0 +roiX=0 +transpose=false diff --git a/devices/src2.properties b/devices/src2.properties new file mode 100755 index 0000000..610d284 --- /dev/null +++ b/devices/src2.properties @@ -0,0 +1,25 @@ +#Fri Jan 29 16:28:47 CET 2021 +spatialCalOffsetY=NaN +spatialCalOffsetX=NaN +colormapLogarithmic=false +scale=1.0 +grayscale=false +spatialCalScaleX=NaN +spatialCalScaleY=NaN +colormapMax=NaN +rescaleOffset=0.0 +roiWidth=-1 +colormap=Grayscale +invert=false +colormapMin=NaN +rotation=0.0 +rotationCrop=false +rescaleFactor=1.0 +spatialCalUnits=mm +flipVertically=false +roiHeight=-1 +flipHorizontally=false +colormapAutomatic=true +roiY=0 +roiX=0 +transpose=false diff --git a/plugins/CameraCalibrationDialog.java b/plugins/CameraCalibrationDialog.java new file mode 120000 index 0000000..0b9cefd --- /dev/null +++ b/plugins/CameraCalibrationDialog.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/CameraCalibrationDialog.java \ No newline at end of file diff --git a/plugins/Chris.form b/plugins/Chris.form new file mode 100755 index 0000000..156c715 --- /dev/null +++ b/plugins/Chris.form @@ -0,0 +1,43 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/Chris.java b/plugins/Chris.java new file mode 100755 index 0000000..e076892 --- /dev/null +++ b/plugins/Chris.java @@ -0,0 +1,63 @@ +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; + +/** + * + */ +public class Chris extends Panel { + + public Chris() { + initComponents(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jRadioButton1 = new javax.swing.JRadioButton(); + + jRadioButton1.setText("jRadioButton1"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(111, 111, 111) + .addComponent(jRadioButton1) + .addContainerGap(213, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(49, 49, 49) + .addComponent(jRadioButton1) + .addContainerGap(65, Short.MAX_VALUE)) + ); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JRadioButton jRadioButton1; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/Correlation.java b/plugins/Correlation.java new file mode 120000 index 0000000..e469f39 --- /dev/null +++ b/plugins/Correlation.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/Correlation.java \ No newline at end of file diff --git a/plugins/Inventory.java b/plugins/Inventory.java new file mode 120000 index 0000000..88357da --- /dev/null +++ b/plugins/Inventory.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/Inventory.java \ No newline at end of file diff --git a/plugins/MonitoringCameras.form b/plugins/MonitoringCameras.form new file mode 100755 index 0000000..3ea4e65 --- /dev/null +++ b/plugins/MonitoringCameras.form @@ -0,0 +1,342 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/MonitoringCameras.java b/plugins/MonitoringCameras.java new file mode 100755 index 0000000..ce02aae --- /dev/null +++ b/plugins/MonitoringCameras.java @@ -0,0 +1,474 @@ +import ch.psi.pshell.core.Context; +import ch.psi.pshell.device.GenericDevice; +import ch.psi.pshell.imaging.MjpegSource; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import ch.psi.utils.Str; +import ch.psi.utils.swing.SwingUtils; +import java.awt.Component; +import java.io.File; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.DefaultComboBoxModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; + +/** + * + */ +public class MonitoringCameras extends Panel { + + public MonitoringCameras() { + initComponents(); + renderer.setMode(RendererMode.Fit); + updateControls(); + } + volatile boolean loadedCommands; + volatile boolean moving; + volatile String currentCamera; + + void updateControls(){ + boolean isCameraSelected = (currentCamera!=null); + boolean enabled = isCameraSelected && loadedCommands && !moving; + for (Component button : SwingUtils.getComponentsByType(panelControls, JButton.class)){ + button.setEnabled(enabled); + } + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + updateControls(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + renderer.setDeviceName(null); + for (GenericDevice dev : Context.getInstance().getDevicePool().getAllDevices(MjpegSource.class)){ + MjpegSource camera =(MjpegSource) dev; + model.addElement(camera.getName()); + } + model.addElement(""); + model.setSelectedItem(null); + comboCameras.setModel(model); + currentCamera = null; + comboCameras.requestFocus(); + } + + @Override + public void onStateChange(State state, State former) { + loadedCommands = false; + if ((state==State.Ready) & (former==State.Initializing)){ + try { + this.runAsync("devices/axis.py", true).handle((ret,ex)->{ + loadedCommands = true; + updateControls(); + return ret; + }); + } catch (Context.ContextStateException ex) { + getLogger().log(Level.SEVERE, null, ex); + } + } + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + void selectCamera(String name){ + renderer.clear(); + currentCamera = ((name == null)||(name.isBlank()))? null : name; + renderer.setDeviceName(currentCamera); + updateControls(); + } + + + void move(String direction){ + try { + moving = true; + updateControls(); + String camera = comboCameras.getSelectedItem().toString(); + this.evalAsync("axis_move(" + camera + ", '" + direction + "')", true).handle((ret,ex)->{ + moving = false; + updateControls(); + return ret; + }); + } catch (Context.ContextStateException ex) { + getLogger().log(Level.SEVERE, null, ex); + moving = false; + updateControls(); + + } + } + + void zoom(int steps){ + try { + moving = true; + updateControls(); + String camera = comboCameras.getSelectedItem().toString(); + this.evalAsync("axis_rzoom(" + camera + ", " + steps + ")", true).handle((ret,ex)->{ + moving = false; + updateControls(); + return ret; + }); + } catch (Context.ContextStateException ex) { + getLogger().log(Level.SEVERE, null, ex); + moving = false; + updateControls(); + + } + } + + ImageIcon getIcon(String name) { + ImageIcon ret = null; + try { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/" + name + ".png")); + if (ch.psi.utils.swing.MainFrame.isDark()) { + try { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/dark/" + name + ".png")); + } catch (Exception e) { + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return ret; + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + renderer = new ch.psi.pshell.imaging.Renderer(); + panelControls = new javax.swing.JPanel(); + jPanel2 = new javax.swing.JPanel(); + buttonMoveLeft = new javax.swing.JButton(); + buttonMoveDLeft = new javax.swing.JButton(); + buttonMoveDRight = new javax.swing.JButton(); + buttonMoveRight = new javax.swing.JButton(); + buttonMoveUReight = new javax.swing.JButton(); + buttonMoveHome = new javax.swing.JButton(); + buttonMoveDown = new javax.swing.JButton(); + buttonMoveULeft = new javax.swing.JButton(); + buttonMoveUp = new javax.swing.JButton(); + jPanel1 = new javax.swing.JPanel(); + buttonZoomOut = new javax.swing.JButton(); + buttonZooHome = new javax.swing.JButton(); + buttonZoomIn = new javax.swing.JButton(); + jPanel3 = new javax.swing.JPanel(); + comboCameras = new javax.swing.JComboBox<>(); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Move")); + + buttonMoveLeft.setIcon(getIcon("arrows/Left")); + buttonMoveLeft.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveLeftActionPerformed(evt); + } + }); + + buttonMoveDLeft.setIcon(getIcon("arrows/DLeft")); + buttonMoveDLeft.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveDLeftActionPerformed(evt); + } + }); + + buttonMoveDRight.setIcon(getIcon("arrows/DRight")); + buttonMoveDRight.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveDRightActionPerformed(evt); + } + }); + + buttonMoveRight.setIcon(getIcon("arrows/Right")); + buttonMoveRight.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveRightActionPerformed(evt); + } + }); + + buttonMoveUReight.setIcon(getIcon("arrows/URight")); + buttonMoveUReight.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveUReightActionPerformed(evt); + } + }); + + buttonMoveHome.setIcon(getIcon("arrows/Center")); + buttonMoveHome.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveHomeActionPerformed(evt); + } + }); + + buttonMoveDown.setIcon(getIcon("arrows/Down")); + buttonMoveDown.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveDownActionPerformed(evt); + } + }); + + buttonMoveULeft.setIcon(getIcon("arrows/ULeft")); + buttonMoveULeft.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveULeftActionPerformed(evt); + } + }); + + buttonMoveUp.setIcon(getIcon("arrows/Up")); + buttonMoveUp.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMoveUpActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonMoveULeft, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonMoveDLeft, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(buttonMoveLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(buttonMoveDown, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) + .addComponent(buttonMoveHome, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) + .addComponent(buttonMoveUp, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(buttonMoveRight, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) + .addComponent(buttonMoveUReight, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) + .addComponent(buttonMoveDRight, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonMoveDLeft, buttonMoveDRight, buttonMoveDown, buttonMoveHome, buttonMoveLeft, buttonMoveRight, buttonMoveULeft, buttonMoveUReight, buttonMoveUp}); + + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonMoveUp, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonMoveUReight, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonMoveULeft, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonMoveLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonMoveRight, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonMoveHome, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonMoveDown, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonMoveDLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonMoveDRight, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {buttonMoveDLeft, buttonMoveDRight, buttonMoveDown, buttonMoveHome, buttonMoveLeft, buttonMoveRight, buttonMoveULeft, buttonMoveUReight, buttonMoveUp}); + + jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Zoom")); + + buttonZoomOut.setIcon(getIcon("arrows/Out")); + buttonZoomOut.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomOutActionPerformed(evt); + } + }); + + buttonZooHome.setIcon(getIcon("arrows/Center")); + buttonZooHome.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZooHomeActionPerformed(evt); + } + }); + + buttonZoomIn.setIcon(getIcon("arrows/In")); + buttonZoomIn.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomInActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonZoomOut, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonZooHome, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonZoomIn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonZooHome, buttonZoomIn, buttonZoomOut}); + + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonZoomOut, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonZoomIn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonZooHome, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Camera")); + + comboCameras.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboCamerasActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addComponent(comboCameras, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addContainerGap()) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + javax.swing.GroupLayout panelControlsLayout = new javax.swing.GroupLayout(panelControls); + panelControls.setLayout(panelControlsLayout); + panelControlsLayout.setHorizontalGroup( + panelControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelControlsLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelControlsLayout.setVerticalGroup( + panelControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelControlsLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(322, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGap(0, 0, 0) + .addComponent(panelControls, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(panelControls, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(renderer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + }// //GEN-END:initComponents + + private void comboCamerasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboCamerasActionPerformed + try{ + if (getState().isInitialized()){ + Object selection = comboCameras.getSelectedItem(); + selectCamera((selection==null) ? null :selection.toString()); + } + } catch(Exception ex){ + showException(ex); + } + }//GEN-LAST:event_comboCamerasActionPerformed + + private void buttonMoveULeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveULeftActionPerformed + move("upleft"); + }//GEN-LAST:event_buttonMoveULeftActionPerformed + + private void buttonMoveUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveUpActionPerformed + move("up"); + }//GEN-LAST:event_buttonMoveUpActionPerformed + + private void buttonMoveUReightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveUReightActionPerformed + move("upright"); + }//GEN-LAST:event_buttonMoveUReightActionPerformed + + private void buttonMoveLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveLeftActionPerformed + move("left"); + }//GEN-LAST:event_buttonMoveLeftActionPerformed + + private void buttonMoveHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveHomeActionPerformed + move("home"); + }//GEN-LAST:event_buttonMoveHomeActionPerformed + + private void buttonMoveRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveRightActionPerformed + move("right"); + }//GEN-LAST:event_buttonMoveRightActionPerformed + + private void buttonMoveDLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveDLeftActionPerformed + move("downleft"); + }//GEN-LAST:event_buttonMoveDLeftActionPerformed + + private void buttonMoveDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveDownActionPerformed + move("down"); + }//GEN-LAST:event_buttonMoveDownActionPerformed + + private void buttonMoveDRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMoveDRightActionPerformed + move("downright"); + }//GEN-LAST:event_buttonMoveDRightActionPerformed + + private void buttonZoomOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutActionPerformed + zoom(-100); + }//GEN-LAST:event_buttonZoomOutActionPerformed + + private void buttonZooHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZooHomeActionPerformed + move("home"); + }//GEN-LAST:event_buttonZooHomeActionPerformed + + private void buttonZoomInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInActionPerformed + zoom(100); + }//GEN-LAST:event_buttonZoomInActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton buttonMoveDLeft; + private javax.swing.JButton buttonMoveDRight; + private javax.swing.JButton buttonMoveDown; + private javax.swing.JButton buttonMoveHome; + private javax.swing.JButton buttonMoveLeft; + private javax.swing.JButton buttonMoveRight; + private javax.swing.JButton buttonMoveULeft; + private javax.swing.JButton buttonMoveUReight; + private javax.swing.JButton buttonMoveUp; + private javax.swing.JButton buttonZooHome; + private javax.swing.JButton buttonZoomIn; + private javax.swing.JButton buttonZoomOut; + private javax.swing.JComboBox comboCameras; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel panelControls; + private ch.psi.pshell.imaging.Renderer renderer; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/PSSS.form b/plugins/PSSS.form new file mode 100755 index 0000000..6ffd0ee --- /dev/null +++ b/plugins/PSSS.form @@ -0,0 +1,712 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/plugins/PSSS.java b/plugins/PSSS.java new file mode 100755 index 0000000..d9b5482 --- /dev/null +++ b/plugins/PSSS.java @@ -0,0 +1,732 @@ +import ch.psi.pshell.bs.PipelineServer; +import ch.psi.pshell.core.Context; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.pshell.plot.Plot; +import ch.psi.pshell.plot.LinePlotJFree; +import ch.psi.pshell.ui.Panel; +import ch.psi.utils.State; +import ch.psi.utils.Str; +import java.awt.CardLayout; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + + +/** + * + */ +public class PSSS extends Panel { + + final String CAMERA_NAME = "SARFE10-PSSS059"; + PipelineServer pipelineServer; + volatile boolean updatingPlot; + volatile boolean updatingImage; + + public PSSS() { + initComponents(); + plot.getAxis(Plot.AxisId.X).setLabel(null); + plot.getAxis(Plot.AxisId.Y).setLabel(null); + renderer.setMode(RendererMode.Stretch); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + startTimer(1000); + + try { + setGlobalVar("PSSS_PLOT", plot); + setGlobalVar("HISTORY_PLOT", history); + setGlobalVar("PSSS_RENDERER", renderer); + + pipelineServer = (PipelineServer) getDevice("cam_server"); + ((LinePlotJFree)histogramGeneratorPanelCenter.getPlot()).setLegendVisible(true); + ((LinePlotJFree)histogramGeneratorFwhm.getPlot()).setLegendVisible(true); + histogramGeneratorPanelCenter.getPlot().getAxis(Plot.AxisId.Y).setRange(0, 100); + histogramGeneratorFwhm.getPlot().getAxis(Plot.AxisId.Y).setRange(0, 100); + //setImageEnabled(true); + tabStateChanged(null); + + } catch (Exception ex) { + getLogger().log(Level.WARNING, null, ex); + } + } + + @Override + public void onStateChange(State state, State former) { + this.btStartCr.setEnabled(state == State.Ready); + this.btStartEn.setEnabled(state == State.Ready); + this.btStartCam.setEnabled(state == State.Ready); + radioEnergyScan.setEnabled(state == State.Ready); + radioCrystalScan.setEnabled(state == State.Ready); + radioCameraScan.setEnabled(state == State.Ready); + this.btAbort.setEnabled(state.isRunning()); + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + @Override + public void onTimer() { + try { + if (!updatingPlot){ + updatingPlot = true; + evalAsync("plot_psss(PSSS_PLOT, HISTORY_PLOT, " + spinnerAverage.getValue() + ")", true).handle((ret,ex)->{ + updatingPlot = false; + return ret; + }); + } + if (isImageEnabled()){ + if (!updatingImage){ + updatingImage = true; + evalAsync("update_psss_image(PSSS_RENDERER)", true).handle((ret,ex)->{ + updatingImage = false; + return ret; + }); + } + } + } catch (Exception ex) { + getLogger().log(Level.WARNING, null, ex); + } + } + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + void setImageEnabled(boolean enabled){ + try{ + imageEnabled = enabled; + evalAsync("enable_psss_image(" + Str.capitalizeFirst(String.valueOf(enabled)) + ", PSSS_RENDERER)", true); + } catch (Exception ex) { + getLogger().log(Level.WARNING, null, ex); + } + } + volatile boolean imageEnabled; + + boolean isImageEnabled(){ + return imageEnabled; + } + + + void runScan(String name, Map args){ + try { + args.put("PLOT", plotScan); + this.runAsync(name, args).handle((ret,ex)->{ + if (ex!=null){ + if (!getContext().isAborted()){ + showException((Exception)ex); + } + } + return ret; + }); + } catch (Context.ContextStateException ex) { + showException(ex); + } + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + tab = new javax.swing.JTabbedPane(); + jPanel1 = new javax.swing.JPanel(); + plot = new ch.psi.pshell.plot.LinePlotJFree(); + history = new ch.psi.pshell.plot.TimePlotJFree(); + jLabel1 = new javax.swing.JLabel(); + spinnerAverage = new javax.swing.JSpinner(); + histogramGeneratorPanelCenter = new ch.psi.pshell.swing.HistogramGeneratorPanel(); + histogramGeneratorFwhm = new ch.psi.pshell.swing.HistogramGeneratorPanel(); + jPanel4 = new javax.swing.JPanel(); + renderer = new ch.psi.pshell.imaging.Renderer(); + jPanel3 = new javax.swing.JPanel(); + jPanel2 = new javax.swing.JPanel(); + btAbort = new javax.swing.JButton(); + radioEnergyScan = new javax.swing.JRadioButton(); + radioCameraScan = new javax.swing.JRadioButton(); + radioCrystalScan = new javax.swing.JRadioButton(); + jPanel5 = new javax.swing.JPanel(); + panelScan = new javax.swing.JPanel(); + panelEnergyScan = new javax.swing.JPanel(); + spFromEn = new javax.swing.JSpinner(); + jLabel6 = new javax.swing.JLabel(); + jLabel7 = new javax.swing.JLabel(); + spToEn = new javax.swing.JSpinner(); + spStepsEn = new javax.swing.JSpinner(); + jLabel8 = new javax.swing.JLabel(); + jLabel9 = new javax.swing.JLabel(); + spShotsEn = new javax.swing.JSpinner(); + btStartEn = new javax.swing.JButton(); + panelCameraScan = new javax.swing.JPanel(); + jLabel10 = new javax.swing.JLabel(); + spFromCam = new javax.swing.JSpinner(); + jLabel11 = new javax.swing.JLabel(); + spToCam = new javax.swing.JSpinner(); + jLabel12 = new javax.swing.JLabel(); + spStepsCam = new javax.swing.JSpinner(); + jLabel13 = new javax.swing.JLabel(); + spShotsCam = new javax.swing.JSpinner(); + btStartCam = new javax.swing.JButton(); + panelCrystalScan = new javax.swing.JPanel(); + jLabel2 = new javax.swing.JLabel(); + spFromCr = new javax.swing.JSpinner(); + jLabel3 = new javax.swing.JLabel(); + spToCr = new javax.swing.JSpinner(); + jLabel4 = new javax.swing.JLabel(); + spStepsCr = new javax.swing.JSpinner(); + jLabel5 = new javax.swing.JLabel(); + spShotsCr = new javax.swing.JSpinner(); + btStartCr = new javax.swing.JButton(); + plotScan = new ch.psi.pshell.plot.LinePlotJFree(); + + tab.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + tabStateChanged(evt); + } + }); + + plot.setTitle(""); + + jLabel1.setText("Average:"); + + spinnerAverage.setModel(new javax.swing.SpinnerNumberModel(1, 1, 100, 1)); + + histogramGeneratorPanelCenter.setDeviceName("histo_center"); + + histogramGeneratorFwhm.setDeviceName("histo_fwhm"); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spinnerAverage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(history, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE) + .addComponent(plot, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGap(12, 12, 12) + .addComponent(histogramGeneratorFwhm, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(histogramGeneratorPanelCenter, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0)) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel1) + .addComponent(spinnerAverage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(6, 6, 6) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(histogramGeneratorPanelCenter, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE) + .addComponent(plot, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(history, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE) + .addComponent(histogramGeneratorFwhm, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))) + ); + + tab.addTab("Spectrum", jPanel1); + + javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); + jPanel4.setLayout(jPanel4Layout); + jPanel4Layout.setHorizontalGroup( + jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 843, Short.MAX_VALUE) + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, 843, Short.MAX_VALUE)) + ); + jPanel4Layout.setVerticalGroup( + jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 432, Short.MAX_VALUE) + .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)) + ); + + tab.addTab("Camera", jPanel4); + + btAbort.setText("Abort"); + btAbort.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btAbortActionPerformed(evt); + } + }); + + buttonGroup1.add(radioEnergyScan); + radioEnergyScan.setSelected(true); + radioEnergyScan.setText("Energy Scan"); + radioEnergyScan.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioEnergyScanActionPerformed(evt); + } + }); + + buttonGroup1.add(radioCameraScan); + radioCameraScan.setText("Camera Scan"); + radioCameraScan.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioCameraScanActionPerformed(evt); + } + }); + + buttonGroup1.add(radioCrystalScan); + radioCrystalScan.setText("Crystal Height Scan"); + radioCrystalScan.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + radioCrystalScanActionPerformed(evt); + } + }); + + panelScan.setLayout(new java.awt.CardLayout()); + + spFromEn.setModel(new javax.swing.SpinnerNumberModel(7200.0d, 1.0d, 20000.0d, 10.0d)); + + jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel6.setText("Range From:"); + + jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel7.setText("Range To:"); + + spToEn.setModel(new javax.swing.SpinnerNumberModel(7340.0d, 1.0d, 20000.0d, 10.0d)); + + spStepsEn.setModel(new javax.swing.SpinnerNumberModel(20, 1, 1000, 1)); + + jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel8.setText("Steps:"); + + jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel9.setText("Num Shots:"); + + spShotsEn.setModel(new javax.swing.SpinnerNumberModel(100, 1, 1000, 1)); + + btStartEn.setText("Start Energy Scan"); + btStartEn.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btStartEnActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelEnergyScanLayout = new javax.swing.GroupLayout(panelEnergyScan); + panelEnergyScan.setLayout(panelEnergyScanLayout); + panelEnergyScanLayout.setHorizontalGroup( + panelEnergyScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelEnergyScanLayout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelEnergyScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelEnergyScanLayout.createSequentialGroup() + .addComponent(jLabel7) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spToEn, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelEnergyScanLayout.createSequentialGroup() + .addComponent(jLabel6) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spFromEn, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelEnergyScanLayout.createSequentialGroup() + .addComponent(jLabel8) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spStepsEn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelEnergyScanLayout.createSequentialGroup() + .addComponent(jLabel9) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spShotsEn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + .addComponent(btStartEn, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + + panelEnergyScanLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel6, jLabel7, jLabel8, jLabel9}); + + panelEnergyScanLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spFromEn, spShotsEn, spStepsEn, spToEn}); + + panelEnergyScanLayout.setVerticalGroup( + panelEnergyScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelEnergyScanLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelEnergyScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel6) + .addComponent(spFromEn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelEnergyScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel7) + .addComponent(spToEn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelEnergyScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel8) + .addComponent(spStepsEn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelEnergyScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel9) + .addComponent(spShotsEn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btStartEn) + .addContainerGap()) + ); + + panelScan.add(panelEnergyScan, "energy"); + + jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel10.setText("Range From:"); + + spFromCam.setModel(new javax.swing.SpinnerNumberModel(-17.0d, -30.0d, 30.0d, 1.0d)); + + jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel11.setText("Range To:"); + + spToCam.setModel(new javax.swing.SpinnerNumberModel(-11.0d, -30.0d, 30.0d, 1.0d)); + + jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel12.setText("Steps:"); + + spStepsCam.setModel(new javax.swing.SpinnerNumberModel(20, 1, 1000, 1)); + + jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel13.setText("Num Shots:"); + + spShotsCam.setModel(new javax.swing.SpinnerNumberModel(100, 1, 1000, 1)); + + btStartCam.setText("Start Camera Scan"); + btStartCam.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btStartCamActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelCameraScanLayout = new javax.swing.GroupLayout(panelCameraScan); + panelCameraScan.setLayout(panelCameraScanLayout); + panelCameraScanLayout.setHorizontalGroup( + panelCameraScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraScanLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelCameraScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraScanLayout.createSequentialGroup() + .addComponent(jLabel11) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spToCam, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelCameraScanLayout.createSequentialGroup() + .addComponent(jLabel10) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spFromCam, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelCameraScanLayout.createSequentialGroup() + .addComponent(jLabel12) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spStepsCam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelCameraScanLayout.createSequentialGroup() + .addComponent(jLabel13) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spShotsCam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addComponent(btStartCam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + + panelCameraScanLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel11, jLabel12, jLabel13}); + + panelCameraScanLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spFromCam, spShotsCam, spStepsCam, spToCam}); + + panelCameraScanLayout.setVerticalGroup( + panelCameraScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraScanLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelCameraScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel10) + .addComponent(spFromCam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelCameraScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel11) + .addComponent(spToCam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelCameraScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel12) + .addComponent(spStepsCam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelCameraScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel13) + .addComponent(spShotsCam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btStartCam) + .addContainerGap()) + ); + + panelScan.add(panelCameraScan, "camera"); + + jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel2.setText("Range From:"); + + spFromCr.setModel(new javax.swing.SpinnerNumberModel(-0.8d, -10.0d, 10.0d, 0.1d)); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Range To:"); + + spToCr.setModel(new javax.swing.SpinnerNumberModel(-1.7d, -10.0d, 10.0d, 0.1d)); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Steps:"); + + spStepsCr.setModel(new javax.swing.SpinnerNumberModel(20, 1, 1000, 1)); + + jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel5.setText("Num Shots:"); + + spShotsCr.setModel(new javax.swing.SpinnerNumberModel(100, 1, 1000, 1)); + + btStartCr.setText("Start Crystal Height Scan"); + btStartCr.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btStartCrActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelCrystalScanLayout = new javax.swing.GroupLayout(panelCrystalScan); + panelCrystalScan.setLayout(panelCrystalScanLayout); + panelCrystalScanLayout.setHorizontalGroup( + panelCrystalScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCrystalScanLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelCrystalScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCrystalScanLayout.createSequentialGroup() + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spToCr, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelCrystalScanLayout.createSequentialGroup() + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spFromCr, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelCrystalScanLayout.createSequentialGroup() + .addComponent(jLabel4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spStepsCr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(panelCrystalScanLayout.createSequentialGroup() + .addComponent(jLabel5) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(spShotsCr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addComponent(btStartCr, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + + panelCrystalScanLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel2, jLabel3, jLabel4, jLabel5}); + + panelCrystalScanLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spFromCr, spShotsCr, spStepsCr, spToCr}); + + panelCrystalScanLayout.setVerticalGroup( + panelCrystalScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCrystalScanLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelCrystalScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel2) + .addComponent(spFromCr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelCrystalScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel3) + .addComponent(spToCr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelCrystalScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel4) + .addComponent(spStepsCr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(panelCrystalScanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel5) + .addComponent(spShotsCr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btStartCr) + .addContainerGap()) + ); + + panelScan.add(panelCrystalScan, "crystal"); + + javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); + jPanel5.setLayout(jPanel5Layout); + jPanel5Layout.setHorizontalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 0, Short.MAX_VALUE) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(panelScan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0))) + ); + jPanel5Layout.setVerticalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 0, Short.MAX_VALUE) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(panelScan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(0, 0, 0))) + ); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(12, 12, 12) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(radioCrystalScan) + .addComponent(radioCameraScan) + .addComponent(radioEnergyScan) + .addComponent(btAbort, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)) + .addContainerGap()) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addGap(20, 20, 20) + .addComponent(radioEnergyScan) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(radioCameraScan) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(radioCrystalScan) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(btAbort) + .addContainerGap()) + ); + + plotScan.setTitle(""); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0) + .addComponent(plotScan, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(plotScan, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE) + ); + + tab.addTab("Alignment", jPanel3); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(tab) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(tab, javax.swing.GroupLayout.Alignment.TRAILING) + ); + }// //GEN-END:initComponents + + private void tabStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tabStateChanged + setImageEnabled(tab.getSelectedIndex()==1); + }//GEN-LAST:event_tabStateChanged + + private void btAbortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAbortActionPerformed + try { + abort(); + } catch (InterruptedException ex) { + showException(ex); + } + }//GEN-LAST:event_btAbortActionPerformed + + private void btStartCrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btStartCrActionPerformed + Map args = new HashMap(); + args.put("RANGE_FROM", spFromCr.getValue()); + args.put("RANGE_TO", spToCr.getValue()); + args.put("STEPS", spStepsCr.getValue()); + args.put("NUM_SHOTS", spShotsCr.getValue()); + runScan("psss/CrystalHeightScan",args); + }//GEN-LAST:event_btStartCrActionPerformed + + private void btStartCamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btStartCamActionPerformed + Map args = new HashMap(); + args.put("RANGE_FROM", spFromCam.getValue()); + args.put("RANGE_TO", spToCam.getValue()); + args.put("STEPS", spStepsCam.getValue()); + args.put("NUM_SHOTS", spShotsCam.getValue()); + runScan("psss/CameraScan",args); + }//GEN-LAST:event_btStartCamActionPerformed + + private void btStartEnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btStartEnActionPerformed + Map args = new HashMap(); + args.put("RANGE_OFF", null); + args.put("RANGE_FROM", spFromEn.getValue()); + args.put("RANGE_TO", spToEn.getValue()); + args.put("STEPS", spStepsEn.getValue()); + args.put("NUM_SHOTS", spShotsEn.getValue()); + runScan("psss/EnergyScan",args); + }//GEN-LAST:event_btStartEnActionPerformed + + private void radioEnergyScanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioEnergyScanActionPerformed + ((CardLayout)panelScan.getLayout()).show(panelScan, "energy"); + }//GEN-LAST:event_radioEnergyScanActionPerformed + + private void radioCameraScanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioCameraScanActionPerformed + ((CardLayout)panelScan.getLayout()).show(panelScan, "camera"); + }//GEN-LAST:event_radioCameraScanActionPerformed + + private void radioCrystalScanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioCrystalScanActionPerformed + ((CardLayout)panelScan.getLayout()).show(panelScan, "crystal"); + }//GEN-LAST:event_radioCrystalScanActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btAbort; + private javax.swing.JButton btStartCam; + private javax.swing.JButton btStartCr; + private javax.swing.JButton btStartEn; + private javax.swing.ButtonGroup buttonGroup1; + private ch.psi.pshell.swing.HistogramGeneratorPanel histogramGeneratorFwhm; + private ch.psi.pshell.swing.HistogramGeneratorPanel histogramGeneratorPanelCenter; + private ch.psi.pshell.plot.TimePlotJFree history; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel10; + private javax.swing.JLabel jLabel11; + private javax.swing.JLabel jLabel12; + private javax.swing.JLabel jLabel13; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel panelCameraScan; + private javax.swing.JPanel panelCrystalScan; + private javax.swing.JPanel panelEnergyScan; + private javax.swing.JPanel panelScan; + private ch.psi.pshell.plot.LinePlotJFree plot; + private ch.psi.pshell.plot.LinePlotJFree plotScan; + private javax.swing.JRadioButton radioCameraScan; + private javax.swing.JRadioButton radioCrystalScan; + private javax.swing.JRadioButton radioEnergyScan; + private ch.psi.pshell.imaging.Renderer renderer; + private javax.swing.JSpinner spFromCam; + private javax.swing.JSpinner spFromCr; + private javax.swing.JSpinner spFromEn; + private javax.swing.JSpinner spShotsCam; + private javax.swing.JSpinner spShotsCr; + private javax.swing.JSpinner spShotsEn; + private javax.swing.JSpinner spStepsCam; + private javax.swing.JSpinner spStepsCr; + private javax.swing.JSpinner spStepsEn; + private javax.swing.JSpinner spToCam; + private javax.swing.JSpinner spToCr; + private javax.swing.JSpinner spToEn; + private javax.swing.JSpinner spinnerAverage; + private javax.swing.JTabbedPane tab; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/ScreenPanel.java b/plugins/ScreenPanel.java new file mode 120000 index 0000000..bc84b3d --- /dev/null +++ b/plugins/ScreenPanel.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/ScreenPanel.java \ No newline at end of file diff --git a/plugins/ScreenPanel2.java b/plugins/ScreenPanel2.java new file mode 120000 index 0000000..e78c950 --- /dev/null +++ b/plugins/ScreenPanel2.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/ScreenPanel2.java \ No newline at end of file diff --git a/plugins/ScreenPanel3.java b/plugins/ScreenPanel3.java new file mode 120000 index 0000000..6fe4315 --- /dev/null +++ b/plugins/ScreenPanel3.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/ScreenPanel3.java \ No newline at end of file diff --git a/plugins/ScreenPanel4.java b/plugins/ScreenPanel4.java new file mode 120000 index 0000000..f3d1d3a --- /dev/null +++ b/plugins/ScreenPanel4.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/ScreenPanel4.java \ No newline at end of file diff --git a/plugins/ScreenPanel5.java b/plugins/ScreenPanel5.java new file mode 100755 index 0000000..f8899d5 --- /dev/null +++ b/plugins/ScreenPanel5.java @@ -0,0 +1,4415 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.bs.CameraServer; +import ch.psi.pshell.core.Context;f +import java.io.IOException; +import java.nio.file.Paths; +import javax.swing.DefaultComboBoxModel; +import ch.psi.pshell.ui.Panel; +import ch.psi.pshell.imaging.ImageListener; +import ch.psi.utils.State; +import ch.psi.utils.Chrono; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.utils.swing.TextEditor; +import ch.psi.pshell.bs.PipelineServer; +import ch.psi.pshell.bs.StreamValue; +import ch.psi.pshell.core.JsonSerializer; +import ch.psi.pshell.data.DataManager; +import ch.psi.pshell.device.Device; +import ch.psi.pshell.device.Readable.ReadableArray; +import ch.psi.pshell.device.Readable.ReadableNumber; +import ch.psi.pshell.device.ReadableRegister.ReadableRegisterArray; +import ch.psi.pshell.device.ReadableRegister.ReadableRegisterNumber; +import ch.psi.pshell.epics.ChannelInteger; +import ch.psi.pshell.epics.DiscretePositioner; +import ch.psi.pshell.epics.Epics; +import ch.psi.pshell.imaging.Colormap; +import ch.psi.pshell.imaging.ColormapSource; +import ch.psi.pshell.imaging.ColormapSource.ColormapSourceConfig; +import ch.psi.pshell.ui.App; +import ch.psi.pshell.imaging.Data; +import ch.psi.pshell.imaging.DimensionDouble; +import ch.psi.pshell.imaging.Histogram; +import ch.psi.pshell.imaging.ImageBuffer; +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Overlays.Text; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.PointDouble; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.pshell.imaging.Source; +import ch.psi.pshell.scripting.InterpreterResult; +import ch.psi.pshell.scripting.ScriptManager; +import ch.psi.pshell.swing.DeviceValueChart; +import ch.psi.pshell.swing.ValueSelection; +import ch.psi.pshell.swing.ValueSelection.ValueSelectionListener; +import ch.psi.pshell.ui.Console; +import ch.psi.utils.Arr; +import ch.psi.utils.ArrayProperties; +import ch.psi.utils.Config; +import ch.psi.utils.Convert; +import ch.psi.utils.Str; +import ch.psi.utils.swing.Editor.EditorDialog; +import ch.psi.utils.swing.MainFrame; +import ch.psi.utils.swing.StandardDialog; +import ch.psi.utils.swing.StandardDialog.StandardDialogListener; +import ch.psi.utils.swing.SwingUtils.OptionResult; +import ch.psi.utils.swing.SwingUtils.OptionType; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.event.ActionEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileInputStream; +import java.lang.reflect.Array; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.table.DefaultTableModel; +import org.apache.commons.math3.analysis.function.Gaussian; +import org.apache.commons.math3.fitting.GaussianCurveFitter; +import org.apache.commons.math3.fitting.PolynomialCurveFitter; +import org.apache.commons.math3.fitting.WeightedObservedPoint; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; + +/** + * + */ +public class ScreenPanel5 extends Panel { + + public static final String LASER_TYPE = "Laser"; + public static final String ELECTRONS_TYPE = "Electrons"; + public static final String PHOTONICS_TYPE = "Photonics"; + + final String CAMERA_DEVICE_NAME = "CurrentCamera"; + boolean useServerStats = true; + String userOverlaysConfigFile; + ColormapSource camera; + PipelineServer server; + String cameraName; + int polling = 1000; + Overlay marker = null; + JDialog histogramDialog; + DiscretePositioner screen; + DiscretePositioner filter; + boolean showFit; + boolean showProfile; + Overlay[] userOv; + Overlay[] fitOv; + Overlay[] profileOv; + Overlay errorOverlay; + boolean requestCameraListUpdate; + boolean goodRegion; + boolean slicing; + String serverUrl; + String camServerUrl; + String instanceName; + Overlay titleOv = null; + int integration = 0; + boolean persistCameraState; + + public class CameraState extends Config { + + public boolean valid; + public boolean showSidePanel; + //public boolean showMarker; Saved in the stream instance config + public boolean showProfile; + public boolean showFit; + public boolean showReticle; + public boolean showScale; + public boolean showTitle; + public double zoom; + public RendererMode mode; + public boolean colormapAutomatic; + public double colormapMin; + public double colormapMax; + public Colormap colormap; + public boolean colormapLogarithmic; + + String getFile() { + if (camera == null) { + return null; + } + return getContext().getSetup().expandPath("{context}/screen_panel/" + cameraName + ".properties"); + } + } + + void loadCameraState() { + if (persistCameraState) { + try { + CameraState state = new CameraState(); + state.load(state.getFile()); + if (state.valid) { + buttonSidePanel.setSelected(state.showSidePanel); + buttonSidePanelActionPerformed(null); + buttonProfile.setSelected(state.showProfile); + buttonProfileActionPerformed(null); + buttonFit.setSelected(state.showFit); + buttonFitActionPerformed(null); + buttonReticle.setSelected(state.showReticle); + buttonReticleActionPerformed(null); + buttonScale.setSelected(state.showScale); + buttonScaleActionPerformed(null); + buttonTitle.setSelected(state.showTitle); + buttonTitleActionPerformed(null); + renderer.setMode(state.mode); + renderer.setZoom(state.zoom); + if (camera instanceof ColormapSource) { + camera.getConfig().colormap = state.colormap; + camera.getConfig().colormapAutomatic = state.colormapAutomatic; + camera.getConfig().colormapLogarithmic = state.colormapLogarithmic; + camera.getConfig().colormapMax = state.colormapMax; + camera.getConfig().colormapMin = state.colormapMin; + updateColormap(); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + void saveCameraState() { + if (persistCameraState) { + try { + CameraState state = new CameraState(); + state.valid = true; + if (camera instanceof ColormapSource) { + state.colormap = camera.getConfig().colormap; + state.colormapAutomatic = camera.getConfig().colormapAutomatic; + state.colormapLogarithmic = camera.getConfig().colormapLogarithmic; + state.colormapMax = camera.getConfig().colormapMax; + state.colormapMin = camera.getConfig().colormapMin; + } + state.mode = renderer.getMode(); + state.zoom = renderer.getZoom(); + + state.showSidePanel = buttonSidePanel.isSelected(); + state.showProfile = buttonProfile.isSelected(); + state.showFit = buttonFit.isSelected(); + state.showReticle = buttonReticle.isSelected(); + state.showScale = buttonScale.isSelected(); + state.showTitle = buttonTitle.isSelected(); + + state.save(state.getFile()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + String pipelineSuffix = "_sp"; + + Double getServerDouble(String name) { + return (Double) Convert.toDouble(server.getValue(name)); + } + + double[] getServerDoubleArray(String name) { + return (double[]) Convert.toDouble(server.getValue(name)); + } + + class ImageData { + + ImageData() { + if (server != null) { + cache = server.getStream().take(); + String prefix = goodRegion ? "gr_" : ""; + x_fit_mean = getDouble(prefix + "x_fit_mean"); + y_fit_mean = getDouble(prefix + "y_fit_mean"); + x_fit_standard_deviation = getDouble(prefix + "x_fit_standard_deviation"); + y_fit_standard_deviation = getDouble(prefix + "y_fit_standard_deviation"); + x_fit_gauss_function = getDoubleArray(prefix + "x_fit_gauss_function"); + y_fit_gauss_function = getDoubleArray(prefix + "y_fit_gauss_function"); + x_profile = getDoubleArray("x_profile"); + y_profile = getDoubleArray("y_profile"); + x_center_of_mass = getDouble("x_center_of_mass"); + y_center_of_mass = getDouble("y_center_of_mass"); + x_rms = getDouble("x_rms"); + y_rms = getDouble("y_rms"); + if (goodRegion) { + double[] gX2 = new double[x_profile.length]; + Arrays.fill(gX2, Double.NaN); + try { + double[] axis = getDoubleArray("x_axis"); + gr_x_axis = getDoubleArray("gr_x_axis"); + double x = gr_x_axis[0]; + gr_size_x = x_fit_gauss_function.length; + //If gr axis values are not identical, calculate the index... + gr_pos_x = (int) ((renderer.getCalibration() != null) ? renderer.getCalibration().convertToImageX(x) : x); + //But prefer checking the value to avoid raounding errors + for (int i=0;i imageBuffer = new ArrayList(); + Frame currentFrame; + int imageBufferLenght = 1; + Text imagePauseOverlay; + final Console console; + + public ScreenPanel5() { + try { + initComponents(); + spinnerThreshold.setVisible(false); + btFixColormapRange.setVisible(false); + setGoodRegionOptionsVisible(false); + setSlicingOptionsVisible(false); + setRotationOptionsVisible(false); + JComponent editor = spinnerSlOrientation.getEditor(); + if (editor instanceof JSpinner.DefaultEditor) { + ((JSpinner.DefaultEditor) editor).getTextField().setHorizontalAlignment(JTextField.RIGHT); + } + renderer.setPersistenceFile(Paths.get(getContext().getSetup().getContextPath(), "Renderer_Cameras.bin")); + //setPersistedComponents(new Component[]{buttonServer, buttonDirect}); + setPersistedComponents(new Component[]{buttonTitle}); + comboCameras.setEnabled(false); + comboType.setEnabled(false); + + SwingUtils.setEnumCombo(comboColormap, Colormap.class); + if (App.hasArgument("poll")) { + try { + polling = Integer.valueOf(App.getArgumentValue("poll")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("zoom")) { + try { + renderer.setDefaultZoom(Double.valueOf(App.getArgumentValue("zoom"))); + renderer.resetZoom(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("buf")) { + try { + imageBufferLenght = Integer.valueOf(App.getArgumentValue("buf")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("usr_ov")) { + try { + userOverlaysConfigFile = App.getArgumentValue("usr_ov"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("srv_url")) { + serverUrl = App.getArgumentValue("srv_url"); + } + + if (App.hasArgument("cam_srv_url")) { + camServerUrl = App.getArgumentValue("cam_srv_url"); + } + + if (App.hasArgument("calc")) { + useServerStats = false; + } + + if (App.hasArgument("persist")) { + persistCameraState = true; + } + + if (App.hasArgument("suffix")) { + pipelineSuffix = App.getArgumentValue("suffix"); + } + if (App.hasArgument("integration")) { + try { + setIntegration(Integer.valueOf(App.getArgumentValue("integration"))); + if (integration != 0) { + buttonFit.setSelected(false); + buttonProfile.setSelected(false); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + renderer.setProfileNormalized(true); + renderer.setShowProfileLimits(false); + + JMenuItem menuCalibrate = new JMenuItem("Calibrate..."); + menuCalibrate.addActionListener((ActionEvent e) -> { + try { + calibrate(); + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuRendererConfig = new JMenuItem("Renderer Parameters"); + menuRendererConfig.addActionListener((ActionEvent e) -> { + try { + if (camera != null) { + this.showDeviceConfigDialog(camera, false); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuCameraConfig = new JMenuItem("Camera Configurarion"); + menuCameraConfig.addActionListener((ActionEvent e) -> { + try { + if (camera != null) { + String cameraConfigJson = null; + if (usingServer) { + String cameraServerUrl = (camServerUrl == null) ? server.getUrl().substring(0, server.getUrl().length() - 1) + "8" : camServerUrl; + try (CameraServer srv = new CameraServer("CamServer", cameraServerUrl)) { + srv.initialize(); + //TODO: replace into encodeMultiline + cameraConfigJson = JsonSerializer.encode(srv.getConfig(cameraName), true); + } + + } else { + String configFolder = (String) getContext().getClassByName("SfCamera").getMethod("getConfigFolder", new Class[]{}).invoke(null); + Path configFile = Paths.get(configFolder, cameraName + ".json"); + cameraConfigJson = configFile.toFile().exists() ? new String(Files.readAllBytes(configFile)) : null; + } + TextEditor configEditor = new TextEditor(); + configEditor.setText(cameraConfigJson); + configEditor.setReadOnly(true); + configEditor.setTitle(cameraName); + EditorDialog dlg = configEditor.getDialog(getTopLevel(), false); + dlg.setSize(480, 640); + dlg.setVisible(true); + SwingUtils.centerComponent(getTopLevel(), dlg); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSetImageBufferSize = new JMenuItem("Set Stack Size..."); + menuSetImageBufferSize.addActionListener((ActionEvent e) -> { + try { + String ret = SwingUtils.getString(getTopLevel(), "Enter size of image buffer: ", String.valueOf(imageBufferLenght)); + if (ret != null) { + this.setImageBufferSize(Integer.valueOf(ret)); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSaveStack = new JMenuItem("Save Stack"); + menuSaveStack.addActionListener((ActionEvent e) -> { + try { + saveStack(); + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSetROI = new JMenuItem("Set ROI..."); + menuSetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (server != null) { + final Overlays.Rect selection = new Overlays.Rect(renderer.getPenMovingOverlay()); + renderer.addListener(new RendererListener() { + @Override + public void onSelectionFinished(Renderer renderer, Overlay overlay) { + try { + renderer.setShowReticle(false); + Rectangle roi = overlay.isFixed() ? renderer.toImageCoord(overlay.getBounds()) : overlay.getBounds(); + if (server.isRoiEnabled()) { + int[] cur = server.getRoi(); + server.setRoi(new int[]{roi.x + cur[0], roi.y + cur[1], roi.width, roi.height}); + } else { + server.setRoi(new int[]{roi.x, roi.y, roi.width, roi.height}); + } + } catch (Exception ex) { + } finally { + renderer.removeListener(this); + } + } + + @Override + public void onSelectionAborted(Renderer renderer, Overlay overlay) { + renderer.removeListener(this); + } + }); + selection.setFixed(true); + renderer.startSelection(selection); + } + }); + + JMenuItem menuResetROI = new JMenuItem("Reset ROI"); + menuResetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (server != null) { + try { + renderer.setShowReticle(false); + server.resetRoi(); + } catch (IOException ex) { + showException(ex); + } + } + }); + + JCheckBoxMenuItem menuFrameIntegration = new JCheckBoxMenuItem("Multi-Frame", (integration != 0)); + menuFrameIntegration.addActionListener((ActionEvent e) -> { + if (integration == 0) { + JPanel panel = new JPanel(); + GridBagLayout layout = new GridBagLayout(); + layout.columnWidths = new int[]{150, 50}; //Minimum width + layout.rowHeights = new int[]{30, 30}; //Minimum height + panel.setLayout(layout); + JCheckBox checkContinuous = new JCheckBox(""); + checkContinuous.setSelected(true); + JTextField textFrames = new JTextField(); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Number of frames:"), c); + c.gridy = 1; + panel.add(new JLabel("Continuous:"), c); + c.fill = GridBagConstraints.HORIZONTAL; + c.gridx = 1; + panel.add(checkContinuous, c); + c.gridy = 0; + panel.add(textFrames, c); + if (SwingUtils.showOption(getTopLevel(), "Multi-Frame Integration", panel, OptionType.OkCancel) == OptionResult.Yes) { + setIntegration(checkContinuous.isSelected() ? -(Integer.valueOf(textFrames.getText())) : (Integer.valueOf(textFrames.getText()))); + } + } else { + if (SwingUtils.showOption(getTopLevel(), "Multi-Frame Integration", + "Do you want to disable " + ((integration < 0) ? "continuous " : "") + "multi-frame integration (" + Math.abs(integration) + ")?", OptionType.YesNo) == OptionResult.Yes) { + setIntegration(0); + } + } + }); + + for (Component cmp : SwingUtils.getComponentsByType(renderer.getPopupMenu(), JMenu.class)) { + JMenu menu = (JMenu) cmp; + if (menu.getText().equals("Integration")) { + menu.addSeparator(); + menu.add(menuFrameIntegration); + } + } + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuRendererConfig); + renderer.getPopupMenu().add(menuCameraConfig); + renderer.getPopupMenu().add(menuSetImageBufferSize); + renderer.getPopupMenu().add(menuSaveStack); + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuCalibrate); + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuSetROI); + renderer.getPopupMenu().add(menuResetROI); + renderer.getPopupMenu().addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + menuResetROI.setEnabled(server != null); + menuSetROI.setEnabled(server != null); + menuCalibrate.setVisible(server != null); + menuCalibrate.setEnabled((calibrationDialolg == null) || (!calibrationDialolg.isShowing())); + menuSaveStack.setEnabled(imageBufferLenght > 0); + menuSetImageBufferSize.setEnabled(!renderer.isPaused()); + menuFrameIntegration.setSelected(integration != 0); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + renderer.getPopupMenu().setVisible(false); + buttonScale.setSelected(renderer.getShowColormapScale()); + clearMarker(); + + showFit = buttonFit.isSelected(); + showProfile = buttonProfile.isSelected(); + + pauseSelection.setVisible(false); + pauseSelection.setMinValue(1); + pauseSelection.addListener(new ValueSelectionListener() { + @Override + public void onValueChanged(ValueSelection origin, double value, boolean editing) { + if (editing && (value >= 1) && (value <= imageBuffer.size())) { + updatePause(); + } + } + }); + renderer.addListener(new RendererListener() { + @Override + public void onMoveFinished(Renderer renderer, Overlay overlay) { + if (overlay == marker) { + try { + onMarkerChanged(); + } catch (IOException ex) { + Logger.getLogger(ScreenPanel5.class.getName()).log(Level.WARNING, null, ex); + } + } + } + }); + if (MainFrame.isDark()) { + textState.setDisabledTextColor(textState.getForeground()); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + + console = (!App.hasArgument("console")) ? null : new Console() { + /* + protected void onConsoleCommand(String name, String[] pars, String trimming) throws Exception { + switch (name) { + case "cam": + comboCameras.setSelectedItem(tokens[1]); + break; + } + }*/ + @Override + protected void onConsoleCommand(String command) { + String[] tokens = command.split(" "); + if ((tokens.length > 1) && tokens[0].equals("cam")) { + try { + if (!tokens[1].equals(comboCameras.getSelectedItem())) { + setComboTypeSelection("All"); + updateCameraList(); + comboCameras.setSelectedItem(tokens[1]); + if (!tokens[1].equals(comboCameras.getSelectedItem())) { + comboCameras.setSelectedItem(""); + throw new Exception("Invalid camera name : " + tokens[1]); + } + System.out.println("Console set camera: " + tokens[1]); + } + } catch (Exception ex) { + System.err.println(ex); + } + } else { + System.err.println("Invalid command: " + command); + } + } + }; + } + + void setIntegration(int frames) { + try { + if (integration != frames) { + integration = frames; + if (camera != null) { + if (Math.abs(integration) > 1) { + renderer.setDevice(new ImageIntegrator(integration)); + } else { + renderer.setDevice(camera); + } + synchronized (imageBuffer) { + currentFrame = null; + imageBuffer.clear(); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @Override + public void onStart() { + super.onStart(); + updateDialogTitle(); + if (App.hasArgument("ct")) { + boolean direct = App.getArgumentValue("ct").equals("0") || App.getArgumentValue("ct").equalsIgnoreCase("false"); + buttonServer.setSelected(!direct); + buttonDirect.setSelected(direct); + } + if (App.hasArgument("console")) { + console.start(); + } + } + + @Override + public void onStop() { + try { + if (camera != null) { + saveCameraState(); + camera.close(); + camera = null; + server = null; + updateButtons(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + try { + if (console != null) { + console.stop(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + super.onStop(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + comboCameras.setEnabled(false); + comboType.setEnabled(false); + if (App.hasArgument("s")) { + renderer.setDevice((Source) getDevice("image")); + renderer.setAutoScroll(true); + ((Source) getDevice("image")).addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + manageFit(bi, data); + manageUserOverlays(bi, data); + } + + @Override + public void onError(Object o, Exception ex) { + } + } + ); + + } else { + usingServer = buttonServer.isSelected(); + updateCameraList(); + comboCameras.setEnabled(true); + comboType.setEnabled(true); + setComboCameraSelection(null); + setComboTypeSelection("All"); + + if (comboCameras.getModel().getSize() > 0) { + try { + if (App.hasArgument("cam")) { + setComboCameraSelection(App.getArgumentValue("cam")); + comboCamerasActionPerformed(null); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + updateButtons(); + startTimer(1000); + } + + boolean isVisible(String camera) { + return ((comboType.getSelectedIndex() == 0) || (getCameraType(camera).equals(comboType.getSelectedItem()))); + } + + DefaultComboBoxModel getCameraList(boolean fromServer) throws Exception { + DefaultComboBoxModel model = new DefaultComboBoxModel(); + if (fromServer) { + try (PipelineServer srv = newServer()) { + srv.initialize(); + List cameras = srv.getCameras(); + Collections.sort(cameras); + for (String camera : cameras) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + + } else { + ArrayList cameras = (ArrayList) getContext().getClassByName("SfCamera").getMethod("getCameras", new Class[]{}).invoke(null); + for (String camera : cameras) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + if (App.hasArgument("cam")) { + String camera = App.getArgumentValue("cam"); + if (model.getIndexOf(camera) < 0) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + model.addElement(""); + + return model; + } + + PipelineServer newServer() throws IOException { + if (serverUrl != null) { + System.out.println("Connecting to server: " + serverUrl); + server = new PipelineServer(CAMERA_DEVICE_NAME, serverUrl); + } else { + System.out.println("Connecting to server"); + server = new PipelineServer(CAMERA_DEVICE_NAME); + } + updateButtons(); + return server; + } + + boolean updatingCameraSelection; + + void setComboCameraSelection(Object selection) { + updatingCameraSelection = true; + try { + comboCameras.setSelectedItem(selection); + } finally { + updatingCameraSelection = false; + } + } + + void setComboTypeSelection(Object selection) { + updatingCameraSelection = true; + try { + comboType.setSelectedItem(selection); + } finally { + updatingCameraSelection = false; + } + } + boolean usingServer; + + void updateCameraList() { + try { + String selected = (String) comboCameras.getSelectedItem(); + comboCameras.setModel(getCameraList(usingServer)); + if (selected != null) { + if (((DefaultComboBoxModel) comboCameras.getModel()).getIndexOf(camera) < 0) { + setComboCameraSelection(selected); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + } + } + + final Object lockOverlays = new Object(); + + void manageFit(BufferedImage bi, Data data) { + Overlay[][] fo = null; + if ((showFit || showProfile)) { + try { + fo = getFitOverlays(data); + } catch (Exception ex) { + System.err.println(ex); + } + } + synchronized (lockOverlays) { + fo = (fo == null) ? new Overlay[][]{null, null} : fo; + renderer.updateOverlays(fo[0], profileOv); + profileOv = fo[0]; + renderer.updateOverlays(fo[1], fitOv); + fitOv = fo[1]; + } + } + + void manageUserOverlays(BufferedImage bi, Data data) { + Overlay[] fo = (bi == null) ? null : getUserOverlays(data); + synchronized (lockOverlays) { + renderer.updateOverlays(fo, userOv); + userOv = fo; + } + } + + void updateDialogTitle() { + if (App.isDetached()) { + getTopLevel().setTitle(cameraName == null ? "ScreenPanel" : cameraName); + } + } + + void manageTitleOverlay() { + Overlay to = null; + if ((buttonTitle.isSelected()) && (cameraName != null)) { + Font font = new Font("Arial", Font.PLAIN, 28); + to = new Text(renderer.getPenErrorText(), cameraName, font, new Point(-SwingUtils.getTextSize(cameraName, renderer.getGraphics().getFontMetrics(font)).width - 14, 26)); + to.setFixed(true); + to.setAnchor(Overlay.ANCHOR_VIEWPORT_OR_IMAGE_TOP_RIGHT); + } + + synchronized (lockOverlays) { + renderer.updateOverlays(to, titleOv); + titleOv = to; + } + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + Thread devicesInitTask; + + void setCamera(String cameraName) throws IOException, InterruptedException { + System.out.println("Initializing: " + cameraName); + parseUserOverlays(); + errorOverlay = null; + lastMarkerPos = null; + lastFrame = null; + lastPipelinePars = null; + + if (dataTableDialog != null) { + dataTableDialog.dispose(); + dataTableDialog = null; + } + dataTableModel = null; + + if (calibrationDialolg != null) { + calibrationDialolg.dispose(); + calibrationDialolg = null; + } + + boolean was_server = false; + if (camera != null) { + saveCameraState(); + //camera.removeAllListeners(); + was_server = (server != null); + camera.close(); + camera = null; + server = null; + } + updateButtons(); + instanceName = null; + renderer.setDevice(null); + renderer.setShowReticle(false); + renderer.removeOverlays(fitOv); + renderer.removeOverlays(profileOv); + renderer.removeOverlays(userOv); + renderer.clear(); + renderer.resetZoom(); + + boolean changed = !String.valueOf(cameraName).equals(this.cameraName); + this.cameraName = cameraName; + + if (changed || buttonDirect.isSelected()) { + spinnerThreshold.setVisible(false); + checkThreshold.setEnabled(false); + checkRotation.setEnabled(false); + checkGoodRegion.setEnabled(false); + setGoodRegionOptionsVisible(false); + setSlicingOptionsVisible(false); + setRotationOptionsVisible(false); + } + synchronized (imageBuffer) { + currentFrame = null; + imageBuffer.clear(); + } + if (changed) { + checkBackground.setEnabled(false); + if ((devicesInitTask != null) && (devicesInitTask.isAlive())) { + devicesInitTask.interrupt(); + } + if (screen != null) { + screen.close(); + screen = null; + } + if (filter != null) { + filter.close(); + filter = null; + } + if (renderer.isPaused()) { + renderer.resume(); + removePauseOverlay(); + pauseSelection.setVisible(false); + panelCameraSelection.setVisible(true); + } + } + manageTitleOverlay(); + updateDialogTitle(); + + if (cameraName == null) { + return; + } + + System.out.println("Setting camera: " + cameraName + " [" + (buttonServer.isSelected() ? "server" : "direct") + "]"); + try { + if (buttonServer.isSelected()) { + camera = newServer(); + camera.getConfig().flipHorizontally = false; + camera.getConfig().flipVertically = false; + camera.getConfig().rotation = 0.0; + camera.getConfig().roiX = 0; + camera.getConfig().roiY = 0; + camera.getConfig().roiWidth = -1; + camera.getConfig().roiHeight = -1; + } else { + //camera = new SfCamera(CAMERA_DEVICE_NAME, cameraName); + camera = (ColormapSource) getContext().getClassByName("SfCamera").getConstructor(new Class[]{String.class, String.class}).newInstance(new Object[]{CAMERA_DEVICE_NAME, cameraName}); + } + camera.initialize(); + camera.assertInitialized(); + System.out.println("Camera initialization OK"); + loadCameraState(); + if (server != null) { + //server.start(cameraName, false); + String pipelineName = cameraName + pipelineSuffix; + instanceName = cameraName + pipelineSuffix + "1"; + if (!server.getPipelines().contains(pipelineName)) { + System.out.println("Creating pipeline: " + pipelineName); + HashMap config = new HashMap<>(); + config.put("camera_name", cameraName); + //server.createFromConfig(config, pipelineName); + server.savePipelineConfig(pipelineName, config); + } + server.start(pipelineName, instanceName); + + updatePipelineControls(); + checkThreshold.setEnabled(true); + checkRotation.setEnabled(true); + checkGoodRegion.setEnabled(true); + } else { + checkThreshold.setSelected(false); + checkRotation.setSelected(false); + checkGoodRegion.setSelected(false); + if (polling <= 0) { + camera.setMonitored(true); + } else { + camera.setPolling(polling); + } + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + updateButtons(); + camera.getConfig().save(); + if (Math.abs(integration) > 1) { + renderer.setDevice(new ImageIntegrator(integration)); + } else { + renderer.setDevice(camera); + } + renderer.setAutoScroll(true); + //renderer.setMarker(marker); + clearMarker(); + imageSize = null; + + camera.addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + if (bi != null) { + if ((imageSize == null) || imageSize.width != bi.getWidth() || imageSize.height != bi.getHeight()) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + if ((renderer.getMode() == RendererMode.Zoom) || (renderer.getMode() == RendererMode.Fixed)) { + centralizeRenderer(); + } + checkReticle(); + } + }); + imageSize = new Dimension(bi.getWidth(), bi.getHeight()); + } + renderer.setProfileSize(Math.min(bi.getWidth(), bi.getHeight())); + } + //renderer.setCalibration(camera.getCalibration()); + if (!renderer.isPaused()) { + if (data != null) { + synchronized (imageBuffer) { + currentFrame = new Frame(data); + if (imageBufferLenght >= 1) { + imageBuffer.add(currentFrame); + if (imageBuffer.size() > imageBufferLenght) { + imageBuffer.remove(0); + setBufferFull(true); + } else { + setBufferFull(false); + } + } else { + setBufferFull(true); + } + //Update data + if (!renderer.isPaused()) { + updateStreamData(); + } + updateMarker(); + } + } + manageFit(bi, data); + manageUserOverlays(bi, data); + } + //updateImageData(); + } + + @Override + public void onError(Object o, Exception ex) { + //System.err.println(ex); + } + }); + + } catch (Exception ex) { + showException(ex); + renderer.clearOverlays(); + updatePipelineControls(); + if (renderer.getDevice() == null) { + //renderer.setZoom(1.0); + //renderer.setMode(RendererMode.Zoom); + errorOverlay = new Text(renderer.getPenErrorText(), ex.toString(), new Font("Verdana", Font.PLAIN, 12), new Point(20, 20)); + errorOverlay.setFixed(true); + errorOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + renderer.addOverlay(errorOverlay); + } + } finally { + //checkReticle(); + onTimer(); + } + onChangeColormap(null); + checkBackground.setEnabled(true); + if (changed) { + boolean electrons = getCameraType(cameraName).equals(ELECTRONS_TYPE); + comboScreen.setModel(new DefaultComboBoxModel()); + comboScreen.setEnabled(false); + comboFilter.setModel(new DefaultComboBoxModel()); + comboFilter.setEnabled(false); + panelFilter.setVisible(electrons); + panelScreen.setVisible(electrons); + if (electrons) { + //Parallelizing initialization + devicesInitTask = new Thread(() -> { + try { + if (cameraName.contains("DSRM")) { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":POSITION_SP", cameraName + ":POSITION"); + } else { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":SET_SCREEN1_POS", cameraName + ":GET_SCREEN1_POS"); + } + screen.setMonitored(true); + screen.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : screen.getPositions()) { + model.addElement(pos); + } + comboScreen.setModel(model); + comboScreen.setSelectedItem(screen.read()); + + } catch (Exception ex) { + comboScreen.setModel(new DefaultComboBoxModel()); + System.err.println(ex.getMessage()); + screen = null; + } + comboScreen.setEnabled(screen != null); + valueScreen.setDevice(screen); + + try { + filter = new DiscretePositioner("CurrentFilter", cameraName + ":SET_FILTER", cameraName + ":GET_FILTER"); + filter.setMonitored(true); + filter.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : filter.getPositions()) { + model.addElement(pos); + } + comboFilter.setModel(model); + comboFilter.setSelectedItem(filter.read()); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + filter = null; + } + comboFilter.setEnabled(filter != null); + valueFilter.setDevice(filter); + }); + devicesInitTask.start(); + } + } + } + + class ImageIntegrator extends ColormapSource { + + ImageIntegrator(int num) { + super("Image Averager", camera.getConfig()); + boolean continuous = (num < 0); + final int numImages = Math.abs(num); + + camera.addListener(new ImageListener() { + final ArrayList buffer = new ArrayList(); + Data integration = null; + + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + try { + if (continuous) { + buffer.add(data); + if (buffer.size() >= numImages) { + for (Data d : buffer) { + process(d); + } + } + } else { + buffer.add(null); //Just to count + process(data); + } + } catch (Exception ex) { + buffer.clear(); + integration = null; + ImageIntegrator.this.pushData(null); + ex.printStackTrace(); + return; + } + if (buffer.size() >= numImages) { + if (continuous) { + buffer.remove(0); + } else { + buffer.clear(); + } + if (integration != null) { + //integration.div(numImages); + ImageIntegrator.this.pushData(integration); + } + integration = null; + } + } + + void process(Data data) { + if (integration == null) { + integration = new Data(data); + } else { + integration.sum(data); + } + } + + @Override + public void onError(Object origin, Exception ex) { + } + }); + + } + } + + boolean bufferFull = true; + + void setBufferFull(boolean value) { + if (value != bufferFull) { + SwingUtilities.invokeLater(() -> { + buttonPause.setBackground(value ? buttonSave.getBackground() : buttonSave.getBackground().brighter()); + }); + bufferFull = value; + } + } + + volatile Dimension imageSize; + + void checkReticle() { + if ((renderer.getDevice() != null) && (camera != null) && (camera.getConfig().isCalibrated()) && buttonReticle.isSelected()) { + //renderer.setCalibration(camera.getCalibration()); + renderer.configureReticle(new Dimension(800, 800), 200); + renderer.setShowReticle(true); + } else { + //renderer.setCalibration(null); + renderer.setShowReticle(false); + } + renderer.refresh(); + } + + void checkMarker(Point p) throws IOException { + if (camera != null) { + if (buttonMarker.isSelected()) { + Dimension d = renderer.getImageSize(); + if (p == null) { + p = (d == null) ? new Point(renderer.getWidth() / 2, renderer.getHeight() / 2) : new Point(d.width / 2, d.height / 2); + } + Overlay ov = null; + marker = new Overlays.Crosshairs(renderer.getPenMarker(), p, new Dimension(100, 100)); + marker.setMovable(true); + marker.setPassive(false); + } else { + marker = null; + } + renderer.setMarker(marker); + onMarkerChanged(); + } + } + + Point lastMarkerPos; + + void onMarkerChanged() throws IOException { + lastMarkerPos = getStreamMarkerPos(); + if (marker == null) { + setInstanceConfigValue("Marker", null); + } else { + setInstanceConfigValue("Marker", new int[]{marker.getPosition().x, marker.getPosition().y}); + } + } + + void updateMarker() { + try { + if (server != null) { + Point p = getStreamMarkerPos(); + if (p != null) { + //To prevent a local change being overriden by a message having the old settings. + //TODO: This is not bullet-proof, as one can have 2 changes between 2 frames... + if (!p.equals(lastMarkerPos)) { + if (p.x == Integer.MIN_VALUE) { + if (buttonMarker.isSelected()) { + buttonMarker.setSelected(false); + checkMarker(null); + } + } else { + if (!buttonMarker.isSelected()) { + buttonMarker.setSelected(true); + checkMarker(p); + } else { + if (!p.equals(marker.getPosition())) { + marker.setPosition(p); + } + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + Point getStreamMarkerPos() throws IOException { + //System.out.println(server.getInstanceConfig().get("Marker")); + Map pars = server.getProcessingParameters(); + if (pars != null) { + List markerPosition = (List) pars.get("Marker"); + if (markerPosition != null) { + return new Point((Integer) markerPosition.get(0), (Integer) markerPosition.get(1)); + } + return new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); + } + return null; + } + + void clearMarker() { + marker = null; + renderer.setMarker(marker); + } + + void setInstanceConfigValue(String name, Object value) throws IOException { + if (server != null) { + Map map = server.getInstanceConfig(); + map.put(name, value); + server.setInstanceConfig(map); + } + } + + void updateZoom() { + try { + buttonZoomStretch.setSelected(renderer.getMode() == RendererMode.Stretch); + buttonZoomFit.setSelected(renderer.getMode() == RendererMode.Fit); + if (renderer.getMode() == RendererMode.Fixed) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getMode() == RendererMode.Zoom) { + if (renderer.getZoom() == 1) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getZoom() == 0.5) { + buttonZoom05.setSelected(true); + } else if (renderer.getZoom() == 0.25) { + buttonZoom025.setSelected(true); + } else if (renderer.getZoom() == 2.0) { + buttonZoom2.setSelected(true); + } else { + buttonGroup1.clearSelection(); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + boolean updatingColormap; + + void updateColormap() { + updatingColormap = true; + try { + if ((camera != null) && (camera instanceof ColormapSource)) { + ColormapSourceConfig config = ((ColormapSource) camera).getConfig(); + comboColormap.setSelectedItem(config.colormap); + if (config.isDefaultColormap()) { + buttonFullRange.setSelected(true); + } else if (config.colormapAutomatic) { + buttonAutomatic.setSelected(true); + } else { + buttonManual.setSelected(true); + } + btFixColormapRange.setVisible(buttonAutomatic.isSelected()); + spinnerMin.setEnabled(buttonManual.isSelected()); + spinnerMax.setEnabled(buttonManual.isSelected()); + if (!Double.isNaN(config.colormapMin)) { + spinnerMin.setValue(Math.min(Math.max((int) config.colormapMin, 0), 65535)); + } + if (!Double.isNaN(config.colormapMax)) { + spinnerMax.setValue(Math.min(Math.max((int) config.colormapMax, 0), 65535)); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + updatingColormap = false; + } + + void updatePipelineProperties() { + goodRegion = checkGoodRegion.isSelected(); + spinnerThreshold.setVisible(checkThreshold.isSelected()); + setGoodRegionOptionsVisible(goodRegion); + slicing = goodRegion && checkSlicing.isSelected(); + setSlicingOptionsVisible(slicing); + updatingServerControls = false; + boolean rotation = checkRotation.isSelected(); + setRotationOptionsVisible(rotation); + } + + boolean updatingServerControls; + + void updatePipelineControls() { + if (server != null) { + updatingServerControls = true; + if (server.isStarted()) { + try { + checkBackground.setSelected(server.getBackgroundSubtraction()); + Double threshold = (server.getThreshold()); + checkThreshold.setSelected(threshold != null); + spinnerThreshold.setValue((threshold == null) ? 0 : threshold); + Map gr = (server.getGoodRegion()); + checkGoodRegion.setSelected(gr != null); + if (gr != null) { + spinnerGrThreshold.setValue(((Number) gr.get("threshold")).doubleValue()); + spinnerGrScale.setValue(((Number) gr.get("gfscale")).doubleValue()); + } + Map rotation = server.getRotation(); + checkRotation.setSelected(rotation != null); + if (rotation!=null){ + spinnerRotationAngle.setValue(((Number) rotation.get("angle")).doubleValue()); + spinnerRotationOrder.setValue(((Number) rotation.get("order")).intValue()); + String mode = (String) rotation.get("mode"); + try{ + spinnerRotationConstant.setValue(Double.valueOf(mode)); + spinnerRotationMode.setValue("constant"); + } catch (Exception ex){ + spinnerRotationConstant.setValue(0); + spinnerRotationMode.setValue(mode); + } + } + + Map slicing = (server.getSlicing()); + checkSlicing.setSelected(slicing != null); + if (slicing != null) { + spinnerSlNumber.setValue(((Number) slicing.get("number_of_slices")).intValue()); + spinnerSlScale.setValue(((Number) slicing.get("scale")).doubleValue()); + spinnerSlOrientation.setValue((String) slicing.get("orientation")); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + updatePipelineProperties(); + } + } + + boolean changedPipelinePars(Map pars1, Map pars2) { + String[] keys = new String[]{"image_background_enable", "image_threshold", "image_good_region", + "threshold", "gfscale", "image_slices", "number_of_slices", "scale", "orientation"}; + for (String key : keys) { + Object o1 = pars1.get(key); + Object o2 = pars2.get(key); + if (o1 == null) { + if (o2 != null) { + return true; + } + } else if (!o1.equals(o2)) { + return true; + } + } + return false; + } + + void updatePipelineControls(Map pars) { + if (pars != null) { + updatingServerControls = true; + try { + boolean background = (boolean) pars.get("image_background_enable"); + checkBackground.setSelected(background); + Double threshold = (Double) (pars.get("image_threshold")); + checkThreshold.setSelected(threshold != null); + spinnerThreshold.setValue((threshold == null) ? 0 : threshold); + Map gr = (Map) pars.get("image_good_region"); + checkGoodRegion.setSelected(gr != null); + if (gr != null) { + Double value = ((Number) gr.get("threshold")).doubleValue(); + spinnerGrThreshold.setValue(value); + Double scale = ((Number) gr.get("gfscale")).doubleValue(); + spinnerGrScale.setValue(scale); + } + Map slicing = (Map) (pars.get("image_slices")); + checkSlicing.setSelected(slicing != null); + if (slicing != null) { + int slices = ((Number) slicing.get("number_of_slices")).intValue(); + spinnerSlNumber.setValue(slices); + double scale = ((Number) slicing.get("scale")).doubleValue(); + spinnerSlScale.setValue(scale); + String orientation = (String) slicing.get("orientation"); + spinnerSlOrientation.setValue(orientation); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + updatePipelineProperties(); + } + } + + void setGoodRegionOptionsVisible(boolean visible) { + spinnerGrThreshold.setVisible(visible); + labelGrThreshold.setVisible(visible); + spinnerGrScale.setVisible(visible); + labelGrScale.setVisible(visible); + panelSlicing.setVisible(visible); + } + + void setSlicingOptionsVisible(boolean visible) { + spinnerSlNumber.setVisible(visible); + labelSlNumber.setVisible(visible); + spinnerSlScale.setVisible(visible); + labelSlScale.setVisible(visible); + spinnerSlOrientation.setVisible(visible); + labelSlOrientation.setVisible(visible); + } + + void setRotationOptionsVisible(boolean visible) { + labelAngle.setVisible(visible); + labelOrder.setVisible(visible); + labelMode.setVisible(visible); + labelConstant.setVisible(visible); + spinnerRotationAngle.setVisible(visible); + spinnerRotationOrder.setVisible(visible); + spinnerRotationMode.setVisible(visible); + spinnerRotationConstant.setVisible(visible); + } + + boolean isCameraStopped() { + if ((server != null) && !server.isStarted()) { + return true; + } + return ((camera == null) || camera.isClosed()); + } + + boolean updatingButtons; + + void updateButtons() { + updatingButtons = true; + try { + boolean active = !isCameraStopped();//(camera != null); + buttonSave.setEnabled(active); + buttonGrabBackground.setEnabled(active); + buttonMarker.setEnabled(active); + buttonProfile.setEnabled(active); + buttonFit.setEnabled(active); + buttonReticle.setEnabled(active && camera.getConfig().isCalibrated()); + buttonStreamData.setEnabled(active && (server != null)); + buttonPause.setEnabled(active); + + if (renderer.isPaused() != buttonPause.isSelected()) { + buttonPause.setSelected(renderer.isPaused()); + buttonPauseActionPerformed(null); + } + if (renderer.getShowReticle() != buttonReticle.isSelected()) { + //buttonReticle.setSelected(renderer.getShowReticle()); + } + if ((renderer.getMarker() == null) && buttonMarker.isSelected()) { + buttonMarker.setSelected(false); + } + buttonSave.setSelected(renderer.isSnapshotDialogVisible()); + + } finally { + updatingButtons = false; + } + } + + Frame lastFrame = null; + Map lastPipelinePars = null; + + @Override + protected void onTimer() { + for (Device dev : new Device[]{screen, filter}) { + if (dev != null) { + dev.request(); + } + } + + textState.setText((camera == null) ? "" : camera.getState().toString()); + if (App.hasArgument("s")) { + try { + ((Source) getDevice("image")).initialize(); + } catch (IOException ex) { + Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); + } catch (InterruptedException ex) { + Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); + } + } + updateZoom(); + updateColormap(); + updateButtons(); + checkHistogram.setSelected((histogramDialog != null) && (histogramDialog.isShowing())); + buttonScale.setSelected(renderer.getShowColormapScale()); + try { + Frame frame = getCurrentFrame(); + if (frame != lastFrame) { + lastFrame = frame; + if (frame != null) { + Map pars = getProcessingParameters(frame.cache); + if ((lastPipelinePars == null) || changedPipelinePars(pars, lastPipelinePars)) { + //System.out.println("Update pipeline: " + pars); + lastPipelinePars = pars; + updatePipelineControls(pars); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + Pen penFit = new Pen(new Color(192, 105, 0), 0); + Pen penCross = new Pen(new Color(192, 105, 0), 0); + Pen penSlices = new Pen(Color.CYAN.darker(), 1); + + Frame getCurrentFrame() { + if ((imageBufferLenght > 1) && (renderer.isPaused())) { + int index = ((int) pauseSelection.getValue()) - 1; + synchronized (imageBuffer) { + return (index < imageBuffer.size()) ? imageBuffer.get(index) : null; + } + } + return currentFrame; + } + + Frame getFrame(Data data) { + synchronized (imageBuffer) { + for (Frame f : imageBuffer) { + if (f.data == data) { + return f; + } + } + } + return null; + } + + void setImageBufferSize(int size) { + if (renderer.isPaused()) { + throw new RuntimeException("Cannot change buffer size whn paused"); + } + synchronized (imageBuffer) { + imageBufferLenght = size; + imageBuffer.clear(); + } + + } + + Overlay[][] getFitOverlays(Data data) { + Overlays.Polyline hgaussian = null; + Overlays.Polyline vgaussian = null; + Overlays.Polyline hprofile = null; + Overlays.Polyline vprofile = null; + Double xMean = null, xSigma = null, xNorm = null, xCom = null, xRms = null; + Double yMean = null, ySigma = null, yNorm = null, yCom = null, yRms = null; + double[] pX = null, pY = null, gX = null, gY = null; + PointDouble[] sliceCenters = null; + if (data != null) { + int height = data.getHeight(); + int width = data.getWidth(); + int profileSize = renderer.getProfileSize(); + ImageData id = null; + if ((useServerStats) && (server != null)) { + try { + id = getFrame(data); + if (id == null) { + return null; + } + xMean = id.x_fit_mean; + xSigma = id.x_fit_standard_deviation; + yMean = id.y_fit_mean; + ySigma = id.y_fit_standard_deviation; + gX = id.x_fit_gauss_function; + gY = id.y_fit_gauss_function; + pX = id.x_profile; + pY = id.y_profile; + xCom = id.x_center_of_mass; + xRms = id.x_rms; + yCom = id.y_center_of_mass; + yRms = id.y_rms; + sliceCenters = id.sliceCenters; + + profileSize /= 4; + if (pX != null) { + int[] xp = Arr.indexesInt(pX.length); + int[] xg = xp; + int[] yp = new int[pX.length]; + int[] yg = new int[pX.length]; + + List l = Arrays.asList((Double[]) Convert.toWrapperArray(pX)); + double minProfile = Collections.min(l); + double maxProfile = Collections.max(l); + double rangeProfile = maxProfile - minProfile; + double minGauss = minProfile; + double rangeGauss = rangeProfile; + //If not good region, range of profile and fit are similar so save this calcultion + if (goodRegion && id.gr_size_x > 0) { + l = Arrays.asList((Double[]) Convert.toWrapperArray(Arrays.copyOfRange(gX, id.gr_pos_x, id.gr_pos_x + id.gr_size_x))); + minGauss = Collections.min(l); + rangeGauss = Collections.max(l) - minGauss; + } + + for (int i = 0; i < xp.length; i++) { + if (gX != null) { + yg[i] = (int) (height - 1 - (((gX[i] - minGauss) / rangeGauss) * profileSize)); + } + yp[i] = (int) (height - 1 - (((pX[i] - minProfile) / rangeProfile) * profileSize)); + } + + if (goodRegion && id.gr_size_x > 0) { + xg = Arrays.copyOfRange(xg, id.gr_pos_x, id.gr_pos_x + id.gr_size_x); + yg = Arrays.copyOfRange(yg, id.gr_pos_x, id.gr_pos_x + id.gr_size_x); + } + + vgaussian = new Overlays.Polyline(penFit, xg, yg); + vprofile = new Overlays.Polyline(renderer.getPenProfile(), xp, yp); + } + + if (pY != null) { + int[] xp = new int[pY.length]; + int[] xg = new int[pY.length]; + int[] yp = Arr.indexesInt(pY.length); + int[] yg = yp; + + List l = Arrays.asList((Double[]) Convert.toWrapperArray(pY)); + double minProfile = Collections.min(l); + double maxProfile = Collections.max(l); + double rangeProfile = maxProfile - minProfile; + double minGauss = minProfile; + double rangeGauss = rangeProfile; + //If not good region, range of profile and fit are similar so save this calcultion + if (goodRegion && id.gr_size_y > 0) { + l = Arrays.asList((Double[]) Convert.toWrapperArray(Arrays.copyOfRange(gY, id.gr_pos_y, id.gr_pos_y + id.gr_size_y))); + minGauss = Collections.min(l); + rangeGauss = Collections.max(l) - minGauss; + } + + for (int i = 0; i < xp.length; i++) { + if (gY != null) { + xg[i] = (int) (((gY[i] - minGauss) / rangeGauss) * profileSize); + } + xp[i] = (int) (((pY[i] - minProfile) / rangeProfile) * profileSize); + } + + if (goodRegion && id.gr_size_y > 0) { + xg = Arrays.copyOfRange(xg, id.gr_pos_y, id.gr_pos_y + id.gr_size_y); + yg = Arrays.copyOfRange(yg, id.gr_pos_y, id.gr_pos_y + id.gr_size_y); + } + hgaussian = new Overlays.Polyline(penFit, xg, yg); + hprofile = new Overlays.Polyline(renderer.getPenProfile(), xp, yp); + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + return null; + } + } else { + ArrayProperties properties = data.getProperties(); + double maxPlot = properties.max; + double minPlot = properties.min; + double rangePlot = maxPlot - minPlot; + + if (rangePlot <= 0) { + return null; + } + if (renderer.getCalibration() != null) { + try { + double[] sum = data.integrateVertically(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] x_egu = renderer.getCalibration().getAxisX(sum.length); + double[] comRms = getComRms(sum, x_egu); + xCom = comRms[0]; + xRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + if (showFit) { + double[] gaussian = fitGaussian(saux, x); + if (gaussian != null) { + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + xNorm = gaussian[0]; + xMean = gaussian[1]; + xSigma = gaussian[2]; + double[] fit = getFitFunction(gaussian, x); + int[] y = new int[x.length]; + for (int i = 0; i < x.length; i++) { + y[i] = (int) (height - 1 - ((((fit[i] + min) / height - minPlot) / rangePlot) * profileSize)); + } + vgaussian = new Overlays.Polyline(penFit, x, y); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (height - 1 - (((sum[i] / height - minPlot) / rangePlot) * profileSize)); + } + vprofile = new Overlays.Polyline(renderer.getPenProfile(), x, p); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + try { + double[] sum = data.integrateHorizontally(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] y_egu = renderer.getCalibration().getAxisY(sum.length); + double[] comRms = getComRms(sum, y_egu); + yCom = comRms[0]; + yRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + + if (showFit) { + double[] gaussian = fitGaussian(saux, x); + if (gaussian != null) { + //Only aknowledge beam fully inside the image and peak over 3% of min + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + yNorm = gaussian[0]; + yMean = gaussian[1]; + ySigma = gaussian[2]; + double[] fit = getFitFunction(gaussian, x); + + int[] y = new int[x.length]; + for (int i = 0; i < x.length; i++) { + y[i] = (int) ((((fit[i] + min) / width - minPlot) / rangePlot) * profileSize); + } + hgaussian = new Overlays.Polyline(penFit, y, x); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (((sum[i] / width - minPlot) / rangePlot) * profileSize); + } + hprofile = new Overlays.Polyline(renderer.getPenProfile(), p, x); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + if (xSigma != null) { + xSigma *= renderer.getCalibration().getScaleX(); + } + if (ySigma != null) { + ySigma *= renderer.getCalibration().getScaleY(); + } + if (xMean != null) { + xMean = data.getX((int) Math.round(xMean)); + } + if (yMean != null) { + yMean = data.getY((int) Math.round(yMean)); + } + } + } + final String units = (renderer.getCalibration() != null) ? "\u00B5m" : "px"; + final String fmt = "%7.1f" + units; + Overlays.Text textCom = null; + Overlay[] pOv = null, fOv = null; + Font fontInfoText = new Font(Font.MONOSPACED, 0, 14); + Point textPosition = new Point(12, 20); + if (showProfile) { + if ((xCom != null) && (yCom != null)) { + String text = String.format("com x: m=" + fmt + " \u03C3=" + fmt + "\ncom y: m=" + fmt + " \u03C3=" + fmt, xCom, xRms, yCom, yRms); + textCom = new Overlays.Text(renderer.getPenProfile(), text, fontInfoText, textPosition); + textCom.setFixed(true); + textCom.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + } + pOv = new Overlay[]{hprofile, vprofile, textCom}; + textPosition = new Point(textPosition.x, textPosition.y + 34); + } + if (showFit) { + Overlays.Crosshairs cross = null; + Overlays.Text textFit = null; + if ((xMean != null) && (yMean != null)) { + String text = String.format("fit x: m=" + fmt + " \u03C3=" + fmt + "\nfit y: m=" + fmt + " \u03C3=" + fmt, xMean, xSigma, yMean, ySigma); + textFit = new Overlays.Text(penFit, text, fontInfoText, textPosition); + textFit.setFixed(true); + textFit.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + Point center = new Point(xMean.intValue(), yMean.intValue()); + if (renderer.getCalibration() != null) { + center = renderer.getCalibration().convertToImagePosition(new PointDouble(xMean, yMean)); + xSigma /= renderer.getCalibration().getScaleX(); + ySigma /= renderer.getCalibration().getScaleY(); + } + cross = new Overlays.Crosshairs(penCross, center, new Dimension(Math.abs(2 * xSigma.intValue()), 2 * Math.abs(ySigma.intValue()))); + } + textPosition = new Point(textPosition.x, textPosition.y + 34); + fOv = new Overlay[]{hgaussian, vgaussian, cross, textFit}; + + if (goodRegion && (id != null)) { + try { + double[] x = id.gr_x_axis; + double[] y = id.gr_y_axis; + Overlays.Rect goodRegionOv = new Overlays.Rect(new Pen(penFit.getColor(), 0, Pen.LineStyle.dotted)); + goodRegionOv.setCalibration(renderer.getCalibration()); + goodRegionOv.setPosition(new Point(id.gr_pos_x, id.gr_pos_y)); + goodRegionOv.setSize(new Dimension(id.gr_x_axis.length, id.gr_y_axis.length)); + fOv = Arr.append(fOv, goodRegionOv); + + if (slicing) { + if (sliceCenters != null) { + for (PointDouble sliceCenter : sliceCenters) { + Overlays.Crosshairs center = new Overlays.Crosshairs(penSlices); + center.setCalibration(renderer.getCalibration()); + center.setAbsolutePosition(sliceCenter); + center.setSize(new Dimension(10, 10)); + fOv = Arr.append(fOv, center); + } + if (sliceCenters.length > 1) { + double[] fit = fitPolynomial(sliceCenters, 1); + double angle = Math.toDegrees(Math.atan(fit[1])); + Overlays.Text text = new Overlays.Text(penSlices, String.format("slice: \u03B8= %5.1fdeg", angle), fontInfoText, textPosition); + text.setFixed(true); + text.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + fOv = Arr.append(fOv, text); + } + } + } + } catch (Exception ex) { + } + } + + } + return new Overlay[][]{pOv, fOv}; + } + return null; + } + + class UserOverlay { + + String name; + Overlay obj; + String[] channels; + } + ArrayList userOverlayConfig; + + void parseUserOverlays() { + Properties userOverlays = new Properties(); + userOverlayConfig = new ArrayList<>(); + if (userOverlaysConfigFile != null) { + try { + try (FileInputStream in = new FileInputStream(getContext().getSetup().expandPath(userOverlaysConfigFile))) { + userOverlays.load(in); + + for (String name : userOverlays.stringPropertyNames()) { + String val = userOverlays.getProperty(name); + try { + UserOverlay uo = new UserOverlay(); + uo.name = name; + String type = val.substring(0, val.indexOf("(")).trim(); + String pars = val.substring(val.indexOf("(") + 1, val.lastIndexOf(")")).trim(); + String[] tokens = pars.split(","); + for (int i = 0; i < tokens.length; i++) { + tokens[i] = tokens[i].trim(); + } + Color color = Color.GRAY; + try { + color = (Color) Color.class.getField(tokens[tokens.length - 1].toUpperCase()).get(null); + } catch (Exception ex) { + } + Pen pen = new Pen(color); + try { + String[] penTokens = tokens[tokens.length - 1].split(":"); + color = (Color) Color.class.getField(penTokens[0].toUpperCase()).get(null); + int width = Integer.valueOf(penTokens[1]); + Pen.LineStyle style = Pen.LineStyle.valueOf(penTokens[2]); + pen = new Pen(color, width, style); + } catch (Exception ex) { + } + switch (type) { + case "Point": + uo.obj = new Overlays.Crosshairs(); + uo.obj.setSize(new Dimension(Integer.valueOf(tokens[2]), Integer.valueOf(tokens[3]))); + break; + case "Line": + uo.obj = new Overlays.Line(); + break; + case "Arrow": + uo.obj = new Overlays.Arrow(); + break; + case "Rect": + uo.obj = new Overlays.Rect(); + break; + case "Ellipse": + uo.obj = new Overlays.Ellipse(); + break; + case "Polyline": + uo.obj = new Overlays.Polyline(); + break; + } + if (type.equals("Polyline") || type.equals("Point")) { + uo.channels = new String[]{tokens[0], tokens[1]}; + } else { + uo.channels = new String[]{tokens[0], tokens[1], tokens[2], tokens[3]}; + } + uo.obj.setPen(pen); + userOverlayConfig.add(uo); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + Overlay[] getUserOverlays(Data data) { + ArrayList ret = new ArrayList<>(); + if (server != null) { + ImageData id = getFrame(data); + for (UserOverlay uo : userOverlayConfig) { + try { + Overlay ov = uo.obj; + //Overlay ov = (Overlay)uo.cls.newInstance(); + ov.setCalibration(renderer.getCalibration()); + boolean valid = false; + if (ov instanceof Overlays.Polyline) { + double[] x = (uo.channels[0].equals("null")) ? null : id.getDoubleArray(uo.channels[0]); + double[] y = (uo.channels[1].equals("null")) ? null : id.getDoubleArray(uo.channels[1]); + if ((x != null) || (y != null)) { + if (x == null) { + x = (renderer.getCalibration() == null) ? Arr.indexesDouble(y.length) : renderer.getCalibration().getAxisX(y.length); + } + if (y == null) { + y = (renderer.getCalibration() == null) ? Arr.indexesDouble(x.length) : renderer.getCalibration().getAxisY(x.length); + } + ((Overlays.Polyline) ov).updateAbsolute(x, y); + valid = true; + } + } else { + Double x = id.getDouble(uo.channels[0]); + Double y = id.getDouble(uo.channels[1]); + if ((x != null) && (y != null)) { + PointDouble position = new PointDouble(x, y); + ov.setAbsolutePosition(position); + if (!(ov instanceof Overlays.Crosshairs)) { + Double x2 = id.getDouble(uo.channels[2]); + Double y2 = id.getDouble(uo.channels[3]); + if ((x != null) && (y != null)) { + DimensionDouble size = new DimensionDouble(x2 - position.x, y2 - position.y); + ov.setAbsoluteSize(size); + valid = true; + } + } else { + valid = true; + } + } + } + if (valid) { + ret.add(ov); + } + } catch (Exception ex) { + //ex.printStackTrace(); + } + } + } + return ret.toArray(new Overlay[0]); + } + + double[] getComRms(double[] arr, double[] x) { + if (arr != null) { + double xmd = 0; + double xmd2 = 0; + double total = 0; + for (int i = 0; i < arr.length; i++) { + double v = (arr[i] * x[i]); + xmd += v; + xmd2 += (v * x[i]); + total += arr[i]; + } + if (total > 0) { + double com = xmd / total; + double com2 = xmd2 / total; + double rms = Math.sqrt(Math.abs(com2 - com * com)); + return new double[]{com, rms}; + } + } + return new double[]{Double.NaN, Double.NaN}; + } + + double[] fitGaussianScript(int[] y, int[] x) { + ScriptManager sm = Context.getInstance().getScriptManager(); + ArrayProperties pY = ArrayProperties.get(y); + sm.setVar("y", y); + sm.setVar("x", x); + InterpreterResult r = sm.eval("r = fit_gaussians(y, x, [" + pY.maxIndex + ",])"); + if (r.exception != null) { + r.exception.printStackTrace(); + } else { + List ret = (List) sm.getVar("r"); + if ((ret != null) && (ret.size() == 1) && (ret.get(0) instanceof List) && (((List) (ret.get(0))).size() == 3)) { + double norm = (Double) ((List) ret.get(0)).get(0); + double mean = (Double) ((List) ret.get(0)).get(1); + double sigma = (Double) ((List) ret.get(0)).get(2); + return new double[]{norm, mean, sigma}; + } + } + return null; + } + + double[] fitGaussian(double[] y, int[] x) { + try { + ArrayProperties pY = ArrayProperties.get(y); + GaussianCurveFitter fitter = GaussianCurveFitter.create().withStartPoint(new double[]{(pY.max - pY.min) / 2, x[pY.maxIndex], 1.0}).withMaxIterations(1000); + ArrayList values = new ArrayList<>(); + for (int i = 0; i < y.length; i++) { + values.add(new WeightedObservedPoint(1.0, x[i], y[i])); + } + return fitter.fit(values); + } catch (Exception ex) { + return null; + } + + } + + double[] fitPolynomial(PointDouble[] points, int order) { + double[] y = new double[points.length]; + double[] x = new double[points.length]; + for (int i = 0; i < points.length; i++) { + x[i] = points[i].x; + y[i] = points[i].y; + } + return fitPolynomial(y, x, order); + } + + double[] fitPolynomial(double[] y, double[] x, int order) { + try { + ArrayProperties pY = ArrayProperties.get(y); + PolynomialCurveFitter fitter = PolynomialCurveFitter.create(order).withMaxIterations(1000); + ArrayList values = new ArrayList<>(); + for (int i = 0; i < y.length; i++) { + values.add(new WeightedObservedPoint(1.0, x[i], y[i])); + } + return fitter.fit(values); + } catch (Exception ex) { + return null; + } + + } + + double[] getFitFunction(double[] pars, int[] x) { + double[] fit = new double[x.length]; + Gaussian g = new Gaussian(pars[0], pars[1], pars[2]); + for (int i = 0; i < x.length; i++) { + fit[i] = g.value(x[i]); + } + return fit; + } + + void setHistogramVisible(boolean value) { + if (value) { + if ((histogramDialog == null) || (!histogramDialog.isShowing())) { + Histogram histogram = new Histogram(true); + histogram.setRenderer(renderer); + histogramDialog = SwingUtils.showDialog(SwingUtils.getWindow(renderer), "Histogram", null, histogram); + renderer.refresh(); + } + } else { + if (histogramDialog != null) { + histogramDialog.setVisible(false); + histogramDialog = null; + } + } + } + + void setLaserState(boolean value) throws Exception { + System.out.println("Setting laser state: " + value); + Epics.putq("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", value ? 0 : 1); + Epics.putq("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1); + Thread.sleep(3000); + } + + boolean getLaserState() throws Exception { + return (Epics.get("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", Integer.class) == 0); + } + + void elog(String logbook, String title, String message, String[] attachments) throws Exception { + String domain = ""; + String category = "Info"; + String entry = ""; + StringBuffer cmd = new StringBuffer(); + + cmd.append("G_CS_ELOG_add -l \"").append(logbook).append("\" "); + cmd.append("-a \"Author=ScreenPanel\" "); + cmd.append("-a \"Type=pshell\" "); + cmd.append("-a \"Entry=").append(entry).append("\" "); + cmd.append("-a \"Title=").append(title).append("\" "); + cmd.append("-a \"Category=").append(category).append("\" "); + cmd.append("-a \"Domain=").append(domain).append("\" "); + for (String attachment : attachments) { + cmd.append("-f \"").append(attachment).append("\" "); + } + cmd.append("-n 1 "); + cmd.append("\"").append(message).append("\" "); + System.out.println(cmd.toString()); + + final Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", cmd.toString()}); + new Thread(() -> { + try { + process.waitFor(); + int bytes = process.getInputStream().available(); + byte[] arr = new byte[bytes]; + process.getInputStream().read(arr, 0, bytes); + System.out.println(new String(arr)); + bytes = process.getErrorStream().available(); + arr = new byte[bytes]; + process.getErrorStream().read(arr, 0, bytes); + System.err.println(new String(arr)); + } catch (Exception ex) { + System.err.println(ex); + } + }).start(); + } + + void centralizeRenderer() { + Point center = null; + Dimension size = renderer.getImageSize(); + double zoom = (renderer.getMode() == RendererMode.Fixed) ? 1.0 : renderer.getZoom(); + if (renderer.getCalibration() != null) { + center = renderer.getCalibration().getCenter(); + } else if (size != null) { + center = new Point(size.width / 2, size.height / 2); + } + if (center != null) { + Point topleft = new Point(Math.max((int) (center.x - renderer.getWidth() / 2 / zoom), 0), + Math.max((int) (center.y - renderer.getHeight() / 2 / zoom), 0)); + renderer.setViewPosition(topleft); + } + } + + void updatePause() { + int index = ((int) pauseSelection.getValue()) - 1; + synchronized (imageBuffer) { + if (index < imageBuffer.size()) { + Data data = imageBuffer.get(index).data; + long pid = imageBuffer.get(index).cache.getPulseId(); + BufferedImage image = camera.generateImage(data); + renderer.setImage(renderer.getOrigin(), image, data); + + String text = "PID: " + pid; + if (imagePauseOverlay == null) { + Font font = new Font("Verdana", Font.PLAIN, 12); + Dimension d = SwingUtils.getTextSize(text, renderer.getFontMetrics(font)); + imagePauseOverlay = new Text(renderer.getPenErrorText(), "", font, new Point(-20 - d.width, 42)); + imagePauseOverlay.setFixed(true); + imagePauseOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_OR_IMAGE_TOP_RIGHT); + renderer.addOverlay(imagePauseOverlay); + } + //imagePauseOverlay.update(Chrono.getTimeStr(data.getTimestamp(), "HH:mm:ss.SSS")); + imagePauseOverlay.update(text); + manageFit(image, data); + manageUserOverlays(image, data); + } + } + updateStreamData(); + } + + void removePauseOverlay() { + renderer.removeOverlay(imagePauseOverlay); + imagePauseOverlay = null; + } + + void saveSnapshot() throws Exception { + boolean paused = isPaused(); + try{ + if (!paused){ + setPaused(true); + } + String snapshotFile = null; + synchronized (imageBuffer) { + Frame frame = getCurrentFrame(); + if (frame == null) { + throw new Exception("No current image"); + } + ArrayList frames = new ArrayList<>(); + frames.add(frame); + this.saveFrames(cameraName + "_camera_snapshot", frames); + + //Enforce the same timestamp to data & image files. + snapshotFile = getContext().getExecutionPars().getPath() + ".png"; + //renderer.saveSnapshot(snapshotFile, "png", true); + ImageBuffer.saveImage(SwingUtils.createImage(renderer), snapshotFile, "png"); + } + + JPanel panel = new JPanel(); + GridBagLayout layout = new GridBagLayout(); + layout.columnWidths = new int[]{0, 180}; //Minimum width + layout.rowHeights = new int[]{30, 30, 30}; //Minimum height + panel.setLayout(layout); + JComboBox comboLogbook = new JComboBox(new String[]{"SwissFEL commissioning data", "SwissFEL commissioning"}); + JTextField textComment = new JTextField(); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Data file:"), c); + c.gridy = 1; + panel.add(new JLabel("Logbook:"), c); + c.gridy = 2; + panel.add(new JLabel("Comment:"), c); + c.fill = GridBagConstraints.HORIZONTAL; + c.gridx = 1; + panel.add(textComment, c); + c.gridy = 1; + panel.add(comboLogbook, c); + c.gridy = 0; + panel.add(new JLabel(getContext().getExecutionPars().getPath()), c); + + if (SwingUtils.showOption(getTopLevel(), "Success", panel, OptionType.OkCancel) == OptionResult.Yes) { + StringBuilder message = new StringBuilder(); + message.append("Camera: ").append(cameraName).append(" ("). + append((server != null) ? "server" : "direct").append(")").append("\n"); + message.append("Screen: ").append(String.valueOf(valueScreen.getLabel().getText())).append("\n"); + message.append("Filter: ").append(String.valueOf(valueFilter.getLabel().getText())).append("\n"); + message.append("Data file: ").append(getContext().getExecutionPars().getPath()).append("\n"); + message.append("Comment: ").append(textComment.getText()).append("\n"); + //Add slicing message + if ((fitOv != null) && (fitOv.length > 5) && (fitOv[fitOv.length - 1] instanceof Overlays.Text)) { + Overlays.Text text = (Overlays.Text) fitOv[fitOv.length - 1]; + message.append(text.getText()).append("\n"); + } + elog((String) comboLogbook.getSelectedItem(), "ScreenPanel Snapshot", message.toString(), new String[]{snapshotFile}); + } + } finally{ + if (!paused){ + setPaused(false); + } + } + } + + void saveStack() throws Exception { + synchronized (imageBuffer) { + saveFrames(cameraName + "_camera_stack", imageBuffer); + } + SwingUtils.showMessage(getTopLevel(), "Success", "Generated data file:\n" + getContext().getExecutionPars().getPath()); + } + + public static String getCameraType(String name) { + if (name == null) { + return ""; + } + for (String s : new String[]{"LCAM"}) { + if (name.contains(s)) { + return LASER_TYPE; + } + } + for (String s : new String[]{"DSCR", "DSRM", "DLAC"}) { + if (name.contains(s)) { + return ELECTRONS_TYPE; + } + } + for (String s : new String[]{"PROF", "PPRM", "PSSS", "PSCR", "PSRD"}) { + if (name.contains(s)) { + return PHOTONICS_TYPE; + } + } + return "Unknown"; + } + + public Map getProcessingParameters(StreamValue value) throws IOException { + return (Map) JsonSerializer.decode(value.getValue("processing_parameters").toString(), Map.class); + } + + void saveFrames(String name, ArrayList frames) throws IOException { + ArrayList values = new ArrayList<>(); + for (Frame frame : frames) { + values.add(frame.cache); + } + saveImages(name, values); + } + + void saveImages(String name, ArrayList images) throws IOException { + int depth = images.size(); + if (depth == 0) { + return; + } + StreamValue first = images.get(0); + String pathRoot = "/camera1/"; + String pathImage = pathRoot + "image"; + String pathPid = pathRoot + "pulse_id"; + String pathTimestampStr = pathRoot + "timestamp_str"; + Map processingPars = getProcessingParameters(first); + String camera = (String) processingPars.get("camera_name"); + String type = getCameraType(camera); + + int width = ((Number) first.getValue("width")).intValue(); + int height = ((Number) first.getValue("height")).intValue(); + Class dataType = first.getValue("image").getClass().getComponentType(); + + getContext().setExecutionPars(name); + DataManager dm = getContext().getDataManager(); + + //Create tables + dm.createDataset(pathImage, dataType, new int[]{depth, height, width}); + dm.createDataset(pathPid, Long.class, new int[]{depth}); + dm.createDataset(pathTimestampStr, String.class, new int[]{depth}); + for (String id : first.getIdentifiers()) { + Object val = first.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + Map pars = getProcessingParameters(first); + for (String key : pars.keySet()) { + if ((pars.get(key) != null) && (pars.get(key) instanceof Map)) { + for (Object k : ((Map) pars.get(key)).keySet()) { + Object v = ((Map) pars.get(key)).get(k); + dm.setAttribute(pathImage, key + " " + k, (v == null) ? "" : v); + } + } else { + Object value = pars.get(key); + if (value == null) { + value = ""; + } else if (value instanceof List) { + Class cls = (((List) value).size() > 0) ? ((List) value).get(0).getClass() : double.class; + value = Convert.toPrimitiveArray(value, cls); + //value = Convert.toDouble(value); + } + dm.setAttribute(pathImage, key, value); + } + } + } else if (val.getClass().isArray()) { + dm.createDataset(pathRoot + id, Double.class, new int[]{depth, Array.getLength(val)}); + } else { + dm.createDataset(pathRoot + id, val.getClass(), new int[]{depth}); + } + } + + //Add metadata + dm.setAttribute(pathRoot, "Camera", camera); + dm.setAttribute(pathRoot, "Images", depth); + dm.setAttribute(pathRoot, "Interval", -1); + dm.setAttribute(pathRoot, "Type", type); + if (type.equals(ELECTRONS_TYPE)) { + dm.setAttribute(pathRoot, "Screen", String.valueOf(valueScreen.getLabel().getText())); + dm.setAttribute(pathRoot, "Filter", String.valueOf(valueFilter.getLabel().getText())); + } + + //Save data + for (int index = 0; index < depth; index++) { + StreamValue streamValue = images.get(index); + dm.setItem(pathImage, streamValue.getValue("image"), new long[]{index, 0, 0}, new int[]{1, height, width}); + dm.setItem(pathPid, streamValue.getPulseId(), index); + dm.setItem(pathTimestampStr, Chrono.getTimeStr(streamValue.getTimestamp(), "YYYY-MM-dd HH:mm:ss.SSS"), index); + + for (String id : streamValue.getIdentifiers()) { + Object val = streamValue.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + } else if (val.getClass().isArray()) { + dm.setItem(pathRoot + id, val, index); + } else { + dm.setItem(pathRoot + id, val, index); + } + } + } + getContext().getDataManager().closeOutput(); + } + + StandardDialog calibrationDialolg; + + void calibrate() throws Exception { + if (server != null) { + server.resetRoi(); + calibrationDialolg = (StandardDialog) getContext().getClassByName("CameraCalibrationDialog").getConstructors()[0].newInstance(new Object[]{getTopLevel(), server.getCurrentCamera(), renderer}); + SwingUtils.centerComponent(getTopLevel(), calibrationDialolg); + calibrationDialolg.setVisible(true); + calibrationDialolg.setListener(new StandardDialogListener() { + @Override + public void onWindowOpened(StandardDialog dlg) { + } + + @Override + public void onWindowClosed(StandardDialog dlg, boolean accepted) { + if (accepted) { + //comboCamerasActionPerformed(null); + } + } + }); + } + } + + StandardDialog dataTableDialog; + DefaultTableModel dataTableModel; + JTable dataTable; + + void showStreamData() { + dataTableModel = null; + if (server != null) { + + if ((dataTableDialog != null) && (dataTableDialog.isShowing())) { + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + dataTableDialog.requestFocus(); + return; + } + dataTableModel = new DefaultTableModel(new Object[0][2], new String[]{"Name", "Value"}) { + public Class getColumnClass(int columnIndex) { + return String.class; + } + + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + }; + updateStreamData(); + StreamValue val = server.getStream().take(); + dataTable = new JTable(dataTableModel); + dataTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + dataTable.setCellSelectionEnabled(true); + dataTable.getTableHeader().setReorderingAllowed(false); + dataTable.getTableHeader().setResizingAllowed(true); + dataTableDialog = new StandardDialog(getTopLevel(), "Image Data", false); + dataTableDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setViewportView(dataTable); + scrollPane.setPreferredSize(new Dimension(300, 400)); + dataTableDialog.setContentPane(scrollPane); + dataTableDialog.pack(); + dataTableDialog.setVisible(true); + dataTableDialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + dataTableModel = null; + } + }); + dataTable.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + try { + int row = dataTable.getSelectedRow(); + int col = dataTable.getSelectedColumn(); + dataTable.setToolTipText(null); + if (row > 1) { + String id = String.valueOf(dataTable.getModel().getValueAt(row, 0)); + String locator = String.valueOf(dataTable.getModel().getValueAt(0, 1)); + String channelId = locator + " " + id; + dataTable.setToolTipText(channelId); + if ((e.getClickCount() == 2) && (!e.isPopupTrigger())) { + if (col == 0) { + SwingUtils.showMessage(dataTableDialog, "Channel Identifier", "Copied to clipboard: " + channelId); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(new StringSelection(channelId), (Clipboard clipboard1, Transferable contents) -> { + }); + } else { + Object obj = getCurrentFrame().cache.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + Map pars = getProcessingParameters(getCurrentFrame().cache); + StringBuilder sb = new StringBuilder(); + for (String key : pars.keySet()) { + sb.append(key).append(" = ").append(Str.toString(pars.get(key), 10)).append("\n"); + } + SwingUtils.showMessage(dataTableDialog, "Processing Parameters", sb.toString()); + } else if ((obj != null) && (obj.getClass().isArray() || (obj instanceof Number))) { + DeviceValueChart chart = new DeviceValueChart(); + Device dev = null; + if (obj.getClass().isArray()) { + dev = new ReadableRegisterArray(new ReadableArray() { + @Override + public Object read() throws IOException, InterruptedException { + return Convert.toDouble(getCurrentFrame().cache.getValue(id)); + } + + @Override + public int getSize() { + return Array.getLength(getCurrentFrame().cache.getValue(id)); + } + }); + } else { + dev = new ReadableRegisterNumber(new ReadableNumber() { + @Override + public Object read() throws IOException, InterruptedException { + return Convert.toDouble(getCurrentFrame().cache.getValue(id)); + } + }); + } + dev.setPolling(1000); + chart.setDevice(dev); + JDialog dlg = SwingUtils.showDialog(dataTableDialog, cameraName + " " + id, null, chart); + //TODO: + //PlotBase plot = chart.getPlot(); + //if (plot!=null){ + // plot.setPlotBackgroundColor(Color.BLACK); + //} + } + } + } + } + } catch (Exception ex) { + showException(ex); + } + } + }); + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + updateStreamData(); + } + } + + volatile boolean updatingStreamData = false; + + void updateStreamData() { + if ((dataTableDialog == null) || !dataTableDialog.isShowing() || updatingStreamData) { + return; + } + updatingStreamData = true; + SwingUtilities.invokeLater(() -> { + updatingStreamData = false; + if ((dataTableModel != null) && (server != null)) { + StreamValue value = server.getValue(); + Frame frame = getCurrentFrame(); + int[] sel_rows = (dataTable == null) ? null : dataTable.getSelectedRows(); + int[] sel_cols = (dataTable == null) ? null : dataTable.getSelectedColumns(); + List ids = (value == null) ? new ArrayList<>() : new ArrayList(value.getIdentifiers()); + if (ids.size() + 4 != dataTableModel.getRowCount()) { + dataTableModel.setNumRows(0); + try { + dataTableModel.addRow(new Object[]{"Locator", server.getUrl() + "/" + ((value == null) ? instanceName : server.getCurrentInstance())}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Locator", ex.getMessage()}); + } + try { + dataTableModel.addRow(new Object[]{"Stream", server.getStreamAddress()}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Stream", ex.getMessage()}); + } + dataTableModel.addRow(new Object[]{"PID", ""}); + dataTableModel.addRow(new Object[]{"Timestamp", ""}); + Collections.sort(ids); + for (String id : ids) { + dataTableModel.addRow(new Object[]{id, ""}); + } + } + + if ((frame != null) && (frame.cache != null)) { + dataTableModel.setValueAt(frame.cache.getPulseId(), 2, 1); //PID + dataTableModel.setValueAt(frame.cache.getTimestamp(), 3, 1); //Timestamp + for (int i = 4; i < dataTableModel.getRowCount(); i++) { + String id = String.valueOf(dataTableModel.getValueAt(i, 0)); + //Object obj = server.getValue(id); + Object obj = frame.cache.getValue(id); + if (obj != null) { + if (obj.getClass().isArray()) { + obj = obj.getClass().getComponentType().getSimpleName() + "[" + Array.getLength(obj) + "]"; + } else if (obj instanceof Double) { + obj = Convert.roundDouble((Double) obj, 1); + } else if (obj instanceof Float) { + obj = Convert.roundDouble((Float) obj, 1); + } + } + dataTableModel.setValueAt(String.valueOf(obj), i, 1); + } + } + if ((sel_rows != null) && (sel_rows.length > 0)) { + //dataTable.setRowSelectionInterval((Integer)Arr.getMin(sel_rows), (Integer)Arr.getMax(sel_rows)); + dataTable.setRowSelectionInterval(sel_rows[0], sel_rows[sel_rows.length - 1]); + } + if ((sel_cols != null) && (sel_cols.length > 0)) { + //dataTable.setColumnSelectionInterval((Integer)Arr.getMin(sel_cols), (Integer)Arr.getMax(sel_cols)); + dataTable.setColumnSelectionInterval(sel_cols[0], sel_cols[sel_cols.length - 1]); + } + } + }); + } + + ImageIcon getIcon(String name) { + ImageIcon ret = null; + try { + //Path path = Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(),"resources", name + ".png"); + String dir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "resources/"; + if (new File(dir + name + ".png").exists()) { + ret = new javax.swing.ImageIcon(dir + name + ".png"); + } else { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/" + name + ".png")); + if (MainFrame.isDark()) { + try { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/dark/" + name + ".png")); + } catch (Exception e) { + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return ret; + } + + String getIconName(JButton button) { + String ret = button.getIcon().toString(); + if (ret.indexOf(".") > 0) { + ret = ret.substring(0, ret.indexOf(".")); + } + return ret; + } + + void setPaused(boolean paused){ + removePauseOverlay(); + if (camera != null) { + synchronized (imageBuffer) { + if (paused) { + renderer.pause(); + panelCameraSelection.setVisible(false); + pauseSelection.setVisible(true); + if (imageBuffer.size() > 0) { + pauseSelection.setEnabled(true); + pauseSelection.setMaxValue(imageBuffer.size()); + pauseSelection.setValue(imageBuffer.size()); + updatePause(); + } else { + pauseSelection.setEnabled(false); + pauseSelection.setMaxValue(1); + pauseSelection.setValue(1); + } + } else { + imageBuffer.clear(); + renderer.resume(); + //renderer.clear(); + pauseSelection.setVisible(false); + panelCameraSelection.setVisible(true); + } + } + updateStreamData(); + } + } + + boolean isPaused(){ + return renderer.isPaused(); + } + + //////// + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + buttonGroup2 = new javax.swing.ButtonGroup(); + buttonGroup3 = new javax.swing.ButtonGroup(); + buttonGroup4 = new javax.swing.ButtonGroup(); + jProgressBar1 = new javax.swing.JProgressBar(); + sidePanel = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + buttonZoomFit = new javax.swing.JRadioButton(); + buttonZoomStretch = new javax.swing.JRadioButton(); + buttonZoomNormal = new javax.swing.JRadioButton(); + buttonZoom025 = new javax.swing.JRadioButton(); + buttonZoom05 = new javax.swing.JRadioButton(); + buttonZoom2 = new javax.swing.JRadioButton(); + jPanel2 = new javax.swing.JPanel(); + checkHistogram = new javax.swing.JCheckBox(); + comboColormap = new javax.swing.JComboBox(); + jLabel3 = new javax.swing.JLabel(); + jLabel4 = new javax.swing.JLabel(); + buttonFullRange = new javax.swing.JRadioButton(); + buttonManual = new javax.swing.JRadioButton(); + buttonAutomatic = new javax.swing.JRadioButton(); + labelMin = new javax.swing.JLabel(); + spinnerMin = new javax.swing.JSpinner(); + spinnerMax = new javax.swing.JSpinner(); + labelMax = new javax.swing.JLabel(); + btFixColormapRange = new javax.swing.JButton(); + jPanel5 = new javax.swing.JPanel(); + buttonServer = new javax.swing.JRadioButton(); + buttonDirect = new javax.swing.JRadioButton(); + textState = new javax.swing.JTextField(); + filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767)); + panelScreen = new javax.swing.JPanel(); + valueScreen = new ch.psi.pshell.swing.DeviceValuePanel(); + comboScreen = new javax.swing.JComboBox(); + panelFilter = new javax.swing.JPanel(); + valueFilter = new ch.psi.pshell.swing.DeviceValuePanel(); + comboFilter = new javax.swing.JComboBox(); + panelScreen2 = new javax.swing.JPanel(); + checkThreshold = new javax.swing.JCheckBox(); + spinnerThreshold = new javax.swing.JSpinner(); + checkBackground = new javax.swing.JCheckBox(); + checkGoodRegion = new javax.swing.JCheckBox(); + spinnerGrScale = new javax.swing.JSpinner(); + spinnerGrThreshold = new javax.swing.JSpinner(); + labelGrThreshold = new javax.swing.JLabel(); + labelGrScale = new javax.swing.JLabel(); + panelSlicing = new javax.swing.JPanel(); + checkSlicing = new javax.swing.JCheckBox(); + labelSlScale = new javax.swing.JLabel(); + spinnerSlScale = new javax.swing.JSpinner(); + labelSlNumber = new javax.swing.JLabel(); + spinnerSlNumber = new javax.swing.JSpinner(); + labelSlOrientation = new javax.swing.JLabel(); + spinnerSlOrientation = new javax.swing.JSpinner(); + checkRotation = new javax.swing.JCheckBox(); + spinnerRotationAngle = new javax.swing.JSpinner(); + spinnerRotationOrder = new javax.swing.JSpinner(); + labelOrder = new javax.swing.JLabel(); + labelMode = new javax.swing.JLabel(); + spinnerRotationMode = new javax.swing.JSpinner(); + labelAngle = new javax.swing.JLabel(); + labelConstant = new javax.swing.JLabel(); + spinnerRotationConstant = new javax.swing.JSpinner(); + topPanel = new javax.swing.JPanel(); + toolBar = new javax.swing.JToolBar(); + buttonSidePanel = new javax.swing.JToggleButton(); + buttonStreamData = new javax.swing.JButton(); + buttonSave = new javax.swing.JToggleButton(); + buttonGrabBackground = new javax.swing.JButton(); + buttonPause = new javax.swing.JToggleButton(); + jSeparator6 = new javax.swing.JToolBar.Separator(); + buttonMarker = new javax.swing.JToggleButton(); + buttonProfile = new javax.swing.JToggleButton(); + buttonFit = new javax.swing.JToggleButton(); + buttonReticle = new javax.swing.JToggleButton(); + buttonScale = new javax.swing.JToggleButton(); + buttonTitle = new javax.swing.JToggleButton(); + pauseSelection = new ch.psi.pshell.swing.ValueSelection(); + panelCameraSelection = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + comboCameras = new javax.swing.JComboBox(); + jLabel5 = new javax.swing.JLabel(); + comboType = new javax.swing.JComboBox(); + renderer = new ch.psi.pshell.imaging.Renderer(); + + setPreferredSize(new java.awt.Dimension(873, 600)); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Zoom")); + + buttonGroup1.add(buttonZoomFit); + buttonZoomFit.setText("Fit"); + buttonZoomFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomFitActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomStretch); + buttonZoomStretch.setText("Stretch"); + buttonZoomStretch.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomStretchActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomNormal); + buttonZoomNormal.setText("Normal"); + buttonZoomNormal.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomNormalActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom025); + buttonZoom025.setText("1/4"); + buttonZoom025.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom025ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom05); + buttonZoom05.setText("1/2"); + buttonZoom05.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom05ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom2); + buttonZoom2.setText("2"); + buttonZoom2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom2ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoomFit) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoomStretch)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoom025) + .addComponent(buttonZoom05) + .addComponent(buttonZoom2)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoom025)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomFit) + .addComponent(buttonZoom05)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomStretch) + .addComponent(buttonZoom2)) + .addContainerGap()) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Colormap")); + + checkHistogram.setText("Histogram"); + checkHistogram.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkHistogramActionPerformed(evt); + } + }); + + comboColormap.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Type:"); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Range:"); + + buttonGroup3.add(buttonFullRange); + buttonFullRange.setText("Full"); + buttonFullRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonManual); + buttonManual.setText("Manual"); + buttonManual.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonAutomatic); + buttonAutomatic.setText("Automatic"); + buttonAutomatic.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + labelMin.setText("Min:"); + + spinnerMin.setModel(new javax.swing.SpinnerNumberModel(0, 0, 65535, 1)); + spinnerMin.setEnabled(false); + spinnerMin.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMin.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + spinnerMax.setModel(new javax.swing.SpinnerNumberModel(255, 0, 65535, 1)); + spinnerMax.setEnabled(false); + spinnerMax.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMax.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + labelMax.setText("Max:"); + + btFixColormapRange.setText("Fix"); + btFixColormapRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btFixColormapRangeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel3) + .addComponent(jLabel4)) + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonAutomatic) + .addComponent(buttonFullRange) + .addComponent(buttonManual) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMax) + .addGap(2, 2, 2) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(checkHistogram, javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMin) + .addGap(2, 2, 2) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerMin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) + .addContainerGap()) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btFixColormapRange, spinnerMax, spinnerMin}); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel4}); + + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel3) + .addComponent(checkHistogram)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonAutomatic) + .addComponent(jLabel4) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(labelMin) + .addComponent(spinnerMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonFullRange)) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonManual) + .addComponent(labelMax) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Source")); + + buttonGroup4.add(buttonServer); + buttonServer.setSelected(true); + buttonServer.setText("Server"); + buttonServer.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonServerActionPerformed(evt); + } + }); + + buttonGroup4.add(buttonDirect); + buttonDirect.setText("Direct"); + buttonDirect.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonDirectActionPerformed(evt); + } + }); + + textState.setEditable(false); + textState.setHorizontalAlignment(javax.swing.JTextField.CENTER); + textState.setDisabledTextColor(new java.awt.Color(0, 0, 0)); + textState.setEnabled(false); + + javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); + jPanel5.setLayout(jPanel5Layout); + jPanel5Layout.setHorizontalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addContainerGap() + .addComponent(buttonServer) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonDirect) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(56, 56, 56)) + ); + jPanel5Layout.setVerticalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonServer) + .addComponent(buttonDirect))) + .addContainerGap()) + ); + + panelScreen.setBorder(javax.swing.BorderFactory.createTitledBorder("Screen")); + + comboScreen.setEnabled(false); + comboScreen.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboScreenActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelScreenLayout = new javax.swing.GroupLayout(panelScreen); + panelScreen.setLayout(panelScreenLayout); + panelScreenLayout.setHorizontalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboScreen, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelScreenLayout.setVerticalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreenLayout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + panelFilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Filter")); + + comboFilter.setEnabled(false); + comboFilter.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboFilterActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelFilterLayout = new javax.swing.GroupLayout(panelFilter); + panelFilter.setLayout(panelFilterLayout); + panelFilterLayout.setHorizontalGroup( + panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelFilterLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboFilter, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelFilterLayout.setVerticalGroup( + panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelFilterLayout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + panelScreen2.setBorder(javax.swing.BorderFactory.createTitledBorder("Pipeline")); + + checkThreshold.setText("Threshold"); + checkThreshold.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkThresholdActionPerformed(evt); + } + }); + + spinnerThreshold.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 99999.0d, 1.0d)); + spinnerThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerThresholdonChange(evt); + } + }); + + checkBackground.setText("Subtract Background"); + checkBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkBackgroundActionPerformed(evt); + } + }); + + checkGoodRegion.setText("Good Region"); + checkGoodRegion.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkGoodRegionActionPerformed(evt); + } + }); + + spinnerGrScale.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.01d, 99999.0d, 1.0d)); + spinnerGrScale.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + spinnerGrThreshold.setModel(new javax.swing.SpinnerNumberModel(0.5d, 0.04d, 1.0d, 0.1d)); + spinnerGrThreshold.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerGrThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + labelGrThreshold.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelGrThreshold.setText("Threshold:"); + + labelGrScale.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelGrScale.setText("Scale:"); + + checkSlicing.setText("Slicing"); + checkSlicing.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkSlicingActionPerformed(evt); + } + }); + + labelSlScale.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelSlScale.setText("Scale:"); + + spinnerSlScale.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.01d, 99999.0d, 1.0d)); + spinnerSlScale.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + labelSlNumber.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelSlNumber.setText("Slices:"); + + spinnerSlNumber.setModel(new javax.swing.SpinnerNumberModel(2, 0, 1000, 1)); + spinnerSlNumber.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerSlNumber.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + labelSlOrientation.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelSlOrientation.setText("Orientation:"); + + spinnerSlOrientation.setModel(new javax.swing.SpinnerListModel(new String[] {"vertical", "horizontal"})); + spinnerSlOrientation.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerSlOrientation.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + javax.swing.GroupLayout panelSlicingLayout = new javax.swing.GroupLayout(panelSlicing); + panelSlicing.setLayout(panelSlicingLayout); + panelSlicingLayout.setHorizontalGroup( + panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addComponent(checkSlicing) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addComponent(labelSlNumber) + .addGap(2, 2, 2) + .addComponent(spinnerSlNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addComponent(labelSlScale) + .addGap(2, 2, 2) + .addComponent(spinnerSlScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(labelSlOrientation) + .addGap(2, 2, 2) + .addComponent(spinnerSlOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + panelSlicingLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerSlNumber, spinnerSlOrientation, spinnerSlScale}); + + panelSlicingLayout.setVerticalGroup( + panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(checkSlicing) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlNumber)) + .addGap(0, 0, 0) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlScale)))) + .addGap(0, 0, 0) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlOrientation))) + ); + + panelSlicingLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {spinnerSlNumber, spinnerSlOrientation, spinnerSlScale}); + + checkRotation.setText("Rotation"); + checkRotation.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkRotationActionPerformed(evt); + } + }); + + spinnerRotationAngle.setModel(new javax.swing.SpinnerNumberModel(0.0d, -360.0d, 360.0d, 1.0d)); + spinnerRotationAngle.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + spinnerRotationOrder.setModel(new javax.swing.SpinnerNumberModel(1, 1, 5, 1)); + spinnerRotationOrder.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + labelOrder.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelOrder.setText("Order:"); + + labelMode.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelMode.setText("Mode:"); + + spinnerRotationMode.setModel(new javax.swing.SpinnerListModel(new String[] {"constant", "reflect", "nearest", "mirror", "wrap"})); + spinnerRotationMode.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + labelAngle.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelAngle.setText("Angle:"); + + labelConstant.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelConstant.setText("Constant:"); + + spinnerRotationConstant.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99999, 1)); + spinnerRotationConstant.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + javax.swing.GroupLayout panelScreen2Layout = new javax.swing.GroupLayout(panelScreen2); + panelScreen2.setLayout(panelScreen2Layout); + panelScreen2Layout.setHorizontalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addComponent(checkGoodRegion) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(labelOrder) + .addComponent(labelGrScale) + .addComponent(labelMode))) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addComponent(checkThreshold) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addComponent(checkRotation) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(labelAngle)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(labelGrThreshold, javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addComponent(labelConstant) + .addGap(3, 3, 3))))) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(spinnerGrScale) + .addComponent(spinnerThreshold) + .addComponent(spinnerRotationOrder) + .addComponent(spinnerRotationMode) + .addComponent(spinnerRotationAngle) + .addComponent(spinnerRotationConstant)) + .addContainerGap()) + .addComponent(panelSlicing, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addGap(6, 6, 6) + .addComponent(checkBackground) + .addGap(106, 106, 106)) + ); + + panelScreen2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerGrScale, spinnerGrThreshold, spinnerRotationAngle, spinnerRotationConstant, spinnerRotationMode, spinnerRotationOrder, spinnerThreshold}); + + panelScreen2Layout.setVerticalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addComponent(checkBackground) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkThreshold) + .addComponent(spinnerThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkRotation) + .addComponent(spinnerRotationAngle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelAngle)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerRotationOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelOrder)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerRotationMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelMode)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerRotationConstant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelConstant)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkGoodRegion) + .addComponent(spinnerGrScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrScale)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrThreshold)) + .addGap(2, 2, 2) + .addComponent(panelSlicing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + panelScreen2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {spinnerGrScale, spinnerGrThreshold, spinnerRotationAngle, spinnerRotationConstant, spinnerRotationMode, spinnerRotationOrder, spinnerThreshold}); + + javax.swing.GroupLayout sidePanelLayout = new javax.swing.GroupLayout(sidePanel); + sidePanel.setLayout(sidePanelLayout); + sidePanelLayout.setHorizontalGroup( + sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(sidePanelLayout.createSequentialGroup() + .addContainerGap() + .addGroup(sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + sidePanelLayout.setVerticalGroup( + sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(sidePanelLayout.createSequentialGroup() + .addGap(0, 0, 0) + .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + toolBar.setFloatable(false); + toolBar.setRollover(true); + + buttonSidePanel.setIcon(getIcon("List")); + buttonSidePanel.setSelected(true); + buttonSidePanel.setText(" "); + buttonSidePanel.setToolTipText("Show Side Panel"); + buttonSidePanel.setFocusable(false); + buttonSidePanel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonSidePanel.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSidePanelActionPerformed(evt); + } + }); + toolBar.add(buttonSidePanel); + + buttonStreamData.setIcon(getIcon("Details")); + buttonStreamData.setText(" "); + buttonStreamData.setToolTipText("Show Data Window"); + buttonStreamData.setFocusable(false); + buttonStreamData.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonStreamData.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStreamDataActionPerformed(evt); + } + }); + toolBar.add(buttonStreamData); + + buttonSave.setIcon(getIcon("Save")); + buttonSave.setText(" "); + buttonSave.setToolTipText("Save Snapshot"); + buttonSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonSave.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSaveActionPerformed(evt); + } + }); + toolBar.add(buttonSave); + + buttonGrabBackground.setIcon(getIcon("Background")); + buttonGrabBackground.setText(" "); + buttonGrabBackground.setToolTipText("Grab Background"); + buttonGrabBackground.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonGrabBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonGrabBackgroundActionPerformed(evt); + } + }); + toolBar.add(buttonGrabBackground); + + buttonPause.setIcon(getIcon("Pause")); + buttonPause.setText(" "); + buttonPause.setToolTipText("Pause"); + buttonPause.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonPause.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonPauseActionPerformed(evt); + } + }); + toolBar.add(buttonPause); + + jSeparator6.setMaximumSize(new java.awt.Dimension(20, 32767)); + jSeparator6.setPreferredSize(new java.awt.Dimension(20, 0)); + jSeparator6.setRequestFocusEnabled(false); + toolBar.add(jSeparator6); + + buttonMarker.setIcon(getIcon("Marker")); + buttonMarker.setText(" "); + buttonMarker.setToolTipText("Show Marker"); + buttonMarker.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonMarker.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMarkerActionPerformed(evt); + } + }); + toolBar.add(buttonMarker); + + buttonProfile.setIcon(getIcon("Profile" + + "")); + buttonProfile.setSelected(true); + buttonProfile.setText(" "); + buttonProfile.setToolTipText("Show Image Profile"); + buttonProfile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonProfile.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonProfileActionPerformed(evt); + } + }); + toolBar.add(buttonProfile); + + buttonFit.setIcon(getIcon("Fit")); + buttonFit.setSelected(true); + buttonFit.setText(" "); + buttonFit.setToolTipText("Show Fit"); + buttonFit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonFitActionPerformed(evt); + } + }); + toolBar.add(buttonFit); + + buttonReticle.setIcon(getIcon("Reticule")); + buttonReticle.setSelected(true); + buttonReticle.setText(" "); + buttonReticle.setToolTipText("Show Reticle"); + buttonReticle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonReticle.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonReticleActionPerformed(evt); + } + }); + toolBar.add(buttonReticle); + + buttonScale.setIcon(getIcon("Scale")); + buttonScale.setSelected(true); + buttonScale.setText(" "); + buttonScale.setToolTipText("Show Colormap Scale"); + buttonScale.setFocusable(false); + buttonScale.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonScale.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScaleActionPerformed(evt); + } + }); + toolBar.add(buttonScale); + + buttonTitle.setIcon(getIcon("Title")); + buttonTitle.setSelected(true); + buttonTitle.setText(" "); + buttonTitle.setToolTipText("Show Camera Name"); + buttonTitle.setFocusable(false); + buttonTitle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonTitle.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonTitleActionPerformed(evt); + } + }); + toolBar.add(buttonTitle); + + pauseSelection.setDecimals(0); + + jLabel1.setText("Camera:"); + + comboCameras.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N + comboCameras.setMaximumRowCount(30); + comboCameras.setMinimumSize(new java.awt.Dimension(127, 27)); + comboCameras.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboCamerasActionPerformed(evt); + } + }); + + jLabel5.setText("Type:"); + + comboType.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N + comboType.setMaximumRowCount(30); + comboType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "Laser", "Electrons", "Photonics" })); + comboType.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboTypeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelCameraSelectionLayout = new javax.swing.GroupLayout(panelCameraSelection); + panelCameraSelection.setLayout(panelCameraSelectionLayout); + panelCameraSelectionLayout.setHorizontalGroup( + panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraSelectionLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addGap(0, 0, 0) + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel5) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(comboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0)) + ); + panelCameraSelectionLayout.setVerticalGroup( + panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraSelectionLayout.createSequentialGroup() + .addGap(0, 0, 0) + .addGroup(panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(comboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel5) + .addComponent(jLabel1) + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0)) + ); + + javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel); + topPanel.setLayout(topPanelLayout); + topPanelLayout.setHorizontalGroup( + topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, topPanelLayout.createSequentialGroup() + .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(panelCameraSelection, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(18, 18, 18) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + topPanelLayout.setVerticalGroup( + topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(topPanelLayout.createSequentialGroup() + .addGap(1, 1, 1) + .addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(panelCameraSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() + .addComponent(sidePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(sidePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + ); + }// //GEN-END:initComponents + + private void buttonZoomFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomFitActionPerformed + try { + renderer.setMode(RendererMode.Fit); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomFitActionPerformed + + private void buttonZoomStretchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomStretchActionPerformed + try { + renderer.setMode(RendererMode.Stretch); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomStretchActionPerformed + + private void buttonZoomNormalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomNormalActionPerformed + try { + renderer.setMode(RendererMode.Fixed); + centralizeRenderer(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomNormalActionPerformed + + private void onChangeColormap(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onChangeColormap + try { + if ((camera != null) && (camera instanceof ColormapSource) && !updatingColormap) { + ColormapSource source = (ColormapSource) camera; + Color colorReticule = new Color(16, 16, 16); + Color colorMarker = new Color(128, 128, 128); + Colormap colormap = (Colormap) comboColormap.getSelectedItem(); + source.getConfig().colormap = (colormap == null) ? Colormap.Flame : colormap; + switch (source.getConfig().colormap) { + case Grayscale: + case Inverted: + case Red: + case Green: + case Blue: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + case Flame: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + } + + renderer.setPenReticle(new Pen(colorReticule)); + renderer.setPenProfile(new Pen(colorReticule, 0)); + renderer.setPenMarker(new Pen(colorMarker, 2)); + renderer.setShowReticle(false); + checkReticle(); + source.getConfig().colormapAutomatic = buttonAutomatic.isSelected(); + source.getConfig().colormapMin = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMin.getValue(); + source.getConfig().colormapMax = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMax.getValue(); + try { + source.getConfig().save(); + } catch (Exception ex) { + Logger.getLogger(getClass().getName()).log(Level.WARNING, null, ex); + } + source.refresh(); + if (buttonPause.isSelected()) { + updatePause(); + } + updateColormap(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_onChangeColormap + + private void onChangeColormapRange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_onChangeColormapRange + onChangeColormap(null); + }//GEN-LAST:event_onChangeColormapRange + + private void buttonZoom025ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom025ActionPerformed + renderer.setZoom(0.25); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom025ActionPerformed + + private void buttonZoom05ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom05ActionPerformed + renderer.setZoom(0.5); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom05ActionPerformed + + private void buttonServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonServerActionPerformed + if (!usingServer) { + usingServer = true; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonServerActionPerformed + + private void buttonDirectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDirectActionPerformed + if (usingServer) { + usingServer = false; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonDirectActionPerformed + + private void comboScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboScreenActionPerformed + + comboScreen.setEnabled(false); + new Thread(new Runnable() { + @Override + public void run() { + ChannelInteger setpoint = null; + try { + int index = comboScreen.getSelectedIndex(); + if (index >= 0) { + if (cameraName.contains("DSRM")) { + setpoint = new ChannelInteger(null, cameraName + ":POSITION_SP"); + } else { + setpoint = new ChannelInteger(null, cameraName + ":SET_SCREEN1_POS"); + } + setpoint.initialize(); + Integer readback = setpoint.read(); + if ((readback == null) || (setpoint.read() != index)) { + setpoint.write(index); + //Must be threaded to control the laser because of sleep in setLaserState + /* + boolean laserOn = getLaserState(); + if (laserOn) { + setLaserState(false); + } + try { + setpoint.write(index); + } finally { + if (laserOn) { + setLaserState(true); + } + } + */ + } + screen.read(); + } + } catch (Exception ex) { + showException(ex); + } finally { + comboScreen.setEnabled(true); + if (setpoint != null) { + setpoint.close(); + } + } + } + }).start(); + }//GEN-LAST:event_comboScreenActionPerformed + + private void comboFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboFilterActionPerformed + try { + String setpoint = (String) comboFilter.getSelectedItem(); + if (setpoint != null) { + if (!setpoint.equals(filter.read())) { + filter.write(setpoint); + } + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboFilterActionPerformed + + private void checkHistogramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkHistogramActionPerformed + try { + setHistogramVisible(checkHistogram.isSelected()); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_checkHistogramActionPerformed + + private void buttonZoom2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom2ActionPerformed + renderer.setZoom(2.0); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom2ActionPerformed + + private void spinnerThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setThreshold((Double) spinnerThreshold.getValue()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_spinnerThresholdonChange + + private void checkBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBackgroundActionPerformed + if (server != null) { + if (!updatingServerControls) { + try { + if (server.isStarted()) { + server.setBackgroundSubtraction(checkBackground.isSelected()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + updatingServerControls = true; + checkBackground.setSelected(false); + updatingServerControls = false; + + } + } + } else { + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + }//GEN-LAST:event_checkBackgroundActionPerformed + + private void checkThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkThresholdActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + spinnerThreshold.setVisible(checkThreshold.isSelected()); + server.setThreshold(checkThreshold.isSelected() ? (Double) spinnerThreshold.getValue() : null); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkThresholdActionPerformed + + private void checkGoodRegionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkGoodRegionActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + goodRegion = checkGoodRegion.isSelected(); + setGoodRegionOptionsVisible(goodRegion); + if (goodRegion) { + server.setGoodRegion(((Number) spinnerGrThreshold.getValue()).doubleValue(), ((Number) spinnerGrScale.getValue()).doubleValue()); + } else { + server.setGoodRegion(null); + } + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkGoodRegionActionPerformed + + private void spinnerGrThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerGrThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setGoodRegion((Double) spinnerGrThreshold.getValue(), (Double) spinnerGrScale.getValue()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_spinnerGrThresholdonChange + + private void btFixColormapRangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFixColormapRangeActionPerformed + try { + updatingColormap = true; + ArrayProperties properties = currentFrame.data.getProperties(); + spinnerMax.setValue(properties.max.intValue()); + spinnerMin.setValue(properties.min.intValue()); + buttonManual.setSelected(true); + } catch (Exception ex) { + showException(ex); + } finally { + updatingColormap = false; + onChangeColormap(null); + } + }//GEN-LAST:event_btFixColormapRangeActionPerformed + + private void checkSlicingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSlicingActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + slicing = checkSlicing.isSelected(); + setSlicingOptionsVisible(slicing); + if (slicing) { + server.setSlicing((Integer) spinnerSlNumber.getValue(), (Double) spinnerSlScale.getValue(), spinnerSlOrientation.getValue().toString()); + } else { + server.setSlicing(null); + } + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkSlicingActionPerformed + + private void spinnerSlicingChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerSlicingChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setSlicing((Integer) spinnerSlNumber.getValue(), (Double) spinnerSlScale.getValue(), spinnerSlOrientation.getValue().toString()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_spinnerSlicingChange + + private void buttonReticleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonReticleActionPerformed + try { + checkReticle(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonReticleActionPerformed + + private void buttonFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFitActionPerformed + try { + showFit = buttonFit.isSelected(); + if (showFit) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(fitOv); + fitOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonFitActionPerformed + + private void buttonProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonProfileActionPerformed + try { + showProfile = buttonProfile.isSelected(); + if (showProfile) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(profileOv); + profileOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonProfileActionPerformed + + private void buttonMarkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMarkerActionPerformed + try { + checkMarker(null); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonMarkerActionPerformed + + private void buttonPauseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPauseActionPerformed + try { + if (!updatingButtons) { + setPaused(buttonPause.isSelected()); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonPauseActionPerformed + + private void buttonGrabBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGrabBackgroundActionPerformed + try { + if (camera != null) { + boolean laserOn = getLaserState(); + OptionResult ret = null; + if (laserOn) { + ret = SwingUtils.showOption(getTopLevel(), "Capture Background", "Do you want to put laser on delay for capturing background?", OptionType.YesNoCancel); + if (ret == OptionResult.No) { + laserOn = false; + } + } else { + ret = SwingUtils.showOption(getTopLevel(), "Capture Background", "Do you want to capture background now?", OptionType.OkCancel); + } + + if (ret == OptionResult.Cancel) { + return; + } + + if (laserOn) { + setLaserState(false); + } + try { + System.out.println("Grabbing background for: " + cameraName); + if (server != null) { + server.captureBackground(5); + } else { + camera.captureBackground(5, 0); + } + } finally { + if (laserOn) { + setLaserState(true); + } + } + SwingUtils.showMessage(getTopLevel(), "Success", "Success capturing background", 5000); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonGrabBackgroundActionPerformed + + private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed + try { + saveSnapshot(); + } catch (Exception ex) { + Logger.getLogger(getClass().getName()).log(Level.WARNING, null, ex); + showException(ex); + } + }//GEN-LAST:event_buttonSaveActionPerformed + + private void buttonStreamDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStreamDataActionPerformed + try { + showStreamData(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonStreamDataActionPerformed + + private void buttonSidePanelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSidePanelActionPerformed + sidePanel.setVisible(buttonSidePanel.isSelected()); + }//GEN-LAST:event_buttonSidePanelActionPerformed + + private void comboTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboTypeActionPerformed + try { + if (!updatingCameraSelection) { + updateCameraList(); + if ((cameraName != null) && (!cameraName.equals(comboCameras.getSelectedItem()))) { + setCamera(null); + } else { + setCamera(cameraName); + } + } + + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + } + }//GEN-LAST:event_comboTypeActionPerformed + + private void comboCamerasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboCamerasActionPerformed + try { + if (!updatingCameraSelection) { + if (!comboCameras.isEnabled()) { + throw new Exception("Invalid state"); + } + comboCameras.setEnabled(false); + comboType.setEnabled(false); + buttonServer.setEnabled(false); + buttonDirect.setEnabled(false); + final String cameraName = (String) comboCameras.getSelectedItem(); + new Thread(new Runnable() { + @Override + public void run() { + if (requestCameraListUpdate) { + requestCameraListUpdate = false; + try { + updateCameraList(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + try { + setCamera(cameraName.trim().isEmpty() ? null : cameraName); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + comboCameras.setEnabled(true); + comboType.setEnabled(true); + buttonServer.setEnabled(true); + buttonDirect.setEnabled(true); + } + } + }).start(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboCamerasActionPerformed + + private void buttonTitleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTitleActionPerformed + try { + manageTitleOverlay(); + } catch (Exception ex) { + showException(ex); + } finally { + } + }//GEN-LAST:event_buttonTitleActionPerformed + + private void buttonScaleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScaleActionPerformed + try { + renderer.setShowColormapScale(buttonScale.isSelected()); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonScaleActionPerformed + + private void checkRotationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkRotationActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + boolean rotation = checkRotation.isSelected(); + setRotationOptionsVisible(rotation); + if (rotation) { + spinnerRotationAngleStateChanged(null); + } else { + server.setRotation(null); + } + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkRotationActionPerformed + + private void spinnerRotationAngleStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerRotationAngleStateChanged + try { + String mode = String.valueOf(spinnerRotationMode.getValue()); + server.setRotation(((Number) spinnerRotationAngle.getValue()).doubleValue(), + ((Number) spinnerRotationOrder.getValue()).intValue(), + mode.equals("constant") ? String.valueOf(spinnerRotationConstant.getValue()): mode); + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + }//GEN-LAST:event_spinnerRotationAngleStateChanged + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btFixColormapRange; + private javax.swing.JRadioButton buttonAutomatic; + private javax.swing.JRadioButton buttonDirect; + private javax.swing.JToggleButton buttonFit; + private javax.swing.JRadioButton buttonFullRange; + private javax.swing.JButton buttonGrabBackground; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.ButtonGroup buttonGroup2; + private javax.swing.ButtonGroup buttonGroup3; + private javax.swing.ButtonGroup buttonGroup4; + private javax.swing.JRadioButton buttonManual; + private javax.swing.JToggleButton buttonMarker; + private javax.swing.JToggleButton buttonPause; + private javax.swing.JToggleButton buttonProfile; + private javax.swing.JToggleButton buttonReticle; + private javax.swing.JToggleButton buttonSave; + private javax.swing.JToggleButton buttonScale; + private javax.swing.JRadioButton buttonServer; + private javax.swing.JToggleButton buttonSidePanel; + private javax.swing.JButton buttonStreamData; + private javax.swing.JToggleButton buttonTitle; + private javax.swing.JRadioButton buttonZoom025; + private javax.swing.JRadioButton buttonZoom05; + private javax.swing.JRadioButton buttonZoom2; + private javax.swing.JRadioButton buttonZoomFit; + private javax.swing.JRadioButton buttonZoomNormal; + private javax.swing.JRadioButton buttonZoomStretch; + private javax.swing.JCheckBox checkBackground; + private javax.swing.JCheckBox checkGoodRegion; + private javax.swing.JCheckBox checkHistogram; + private javax.swing.JCheckBox checkRotation; + private javax.swing.JCheckBox checkSlicing; + private javax.swing.JCheckBox checkThreshold; + private javax.swing.JComboBox comboCameras; + private javax.swing.JComboBox comboColormap; + private javax.swing.JComboBox comboFilter; + private javax.swing.JComboBox comboScreen; + private javax.swing.JComboBox comboType; + private javax.swing.Box.Filler filler1; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel5; + private javax.swing.JProgressBar jProgressBar1; + private javax.swing.JToolBar.Separator jSeparator6; + private javax.swing.JLabel labelAngle; + private javax.swing.JLabel labelConstant; + private javax.swing.JLabel labelGrScale; + private javax.swing.JLabel labelGrThreshold; + private javax.swing.JLabel labelMax; + private javax.swing.JLabel labelMin; + private javax.swing.JLabel labelMode; + private javax.swing.JLabel labelOrder; + private javax.swing.JLabel labelSlNumber; + private javax.swing.JLabel labelSlOrientation; + private javax.swing.JLabel labelSlScale; + private javax.swing.JPanel panelCameraSelection; + private javax.swing.JPanel panelFilter; + private javax.swing.JPanel panelScreen; + private javax.swing.JPanel panelScreen2; + private javax.swing.JPanel panelSlicing; + private ch.psi.pshell.swing.ValueSelection pauseSelection; + private ch.psi.pshell.imaging.Renderer renderer; + private javax.swing.JPanel sidePanel; + private javax.swing.JSpinner spinnerGrScale; + private javax.swing.JSpinner spinnerGrThreshold; + private javax.swing.JSpinner spinnerMax; + private javax.swing.JSpinner spinnerMin; + private javax.swing.JSpinner spinnerRotationAngle; + private javax.swing.JSpinner spinnerRotationConstant; + private javax.swing.JSpinner spinnerRotationMode; + private javax.swing.JSpinner spinnerRotationOrder; + private javax.swing.JSpinner spinnerSlNumber; + private javax.swing.JSpinner spinnerSlOrientation; + private javax.swing.JSpinner spinnerSlScale; + private javax.swing.JSpinner spinnerThreshold; + private javax.swing.JTextField textState; + private javax.swing.JToolBar toolBar; + private javax.swing.JPanel topPanel; + private ch.psi.pshell.swing.DeviceValuePanel valueFilter; + private ch.psi.pshell.swing.DeviceValuePanel valueScreen; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/ScreenPanel6.form b/plugins/ScreenPanel6.form new file mode 100755 index 0000000..8fede15 --- /dev/null +++ b/plugins/ScreenPanel6.form @@ -0,0 +1,1359 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ScreenPanel6.java b/plugins/ScreenPanel6.java new file mode 100755 index 0000000..86ca079 --- /dev/null +++ b/plugins/ScreenPanel6.java @@ -0,0 +1,4554 @@ +/* + * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved. + */ + +import ch.psi.pshell.bs.CameraServer; +import ch.psi.pshell.core.Context; +import java.io.IOException; +import java.nio.file.Paths; +import javax.swing.DefaultComboBoxModel; +import ch.psi.pshell.ui.Panel; +import ch.psi.pshell.imaging.ImageListener; +import ch.psi.utils.State; +import ch.psi.utils.Chrono; +import ch.psi.utils.swing.SwingUtils; +import ch.psi.utils.swing.TextEditor; +import ch.psi.pshell.bs.PipelineServer; +import ch.psi.pshell.bs.StreamValue; +import ch.psi.pshell.core.JsonSerializer; +import ch.psi.pshell.data.DataManager; +import ch.psi.pshell.device.Device; +import ch.psi.pshell.device.Readable.ReadableArray; +import ch.psi.pshell.device.Readable.ReadableNumber; +import ch.psi.pshell.device.ReadableRegister.ReadableRegisterArray; +import ch.psi.pshell.device.ReadableRegister.ReadableRegisterNumber; +import ch.psi.pshell.epics.ChannelInteger; +import ch.psi.pshell.epics.DiscretePositioner; +import ch.psi.pshell.epics.Epics; +import ch.psi.pshell.imaging.Colormap; +import ch.psi.pshell.imaging.ColormapSource; +import ch.psi.pshell.imaging.ColormapSource.ColormapSourceConfig; +import ch.psi.pshell.ui.App; +import ch.psi.pshell.imaging.Data; +import ch.psi.pshell.imaging.DimensionDouble; +import ch.psi.pshell.imaging.Histogram; +import ch.psi.pshell.imaging.ImageBuffer; +import ch.psi.pshell.imaging.Overlay; +import ch.psi.pshell.imaging.Overlays; +import ch.psi.pshell.imaging.Overlays.Text; +import ch.psi.pshell.imaging.Pen; +import ch.psi.pshell.imaging.PointDouble; +import ch.psi.pshell.imaging.Renderer; +import ch.psi.pshell.imaging.RendererListener; +import ch.psi.pshell.imaging.RendererMode; +import ch.psi.pshell.imaging.Source; +import ch.psi.pshell.scripting.InterpreterResult; +import ch.psi.pshell.scripting.ScriptManager; +import ch.psi.pshell.swing.DeviceValueChart; +import ch.psi.pshell.swing.ValueSelection; +import ch.psi.pshell.swing.ValueSelection.ValueSelectionListener; +import ch.psi.pshell.ui.Console; +import ch.psi.utils.Arr; +import ch.psi.utils.ArrayProperties; +import ch.psi.utils.Config; +import ch.psi.utils.Convert; +import ch.psi.utils.Str; +import ch.psi.utils.swing.Editor.EditorDialog; +import ch.psi.utils.swing.MainFrame; +import ch.psi.utils.swing.StandardDialog; +import ch.psi.utils.swing.StandardDialog.StandardDialogListener; +import ch.psi.utils.swing.SwingUtils.OptionResult; +import ch.psi.utils.swing.SwingUtils.OptionType; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.event.ActionEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileInputStream; +import java.lang.reflect.Array; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.table.DefaultTableModel; +import org.apache.commons.math3.analysis.function.Gaussian; +import org.apache.commons.math3.fitting.GaussianCurveFitter; +import org.apache.commons.math3.fitting.PolynomialCurveFitter; +import org.apache.commons.math3.fitting.WeightedObservedPoint; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; + +/** + * + */ +public class ScreenPanel6 extends Panel { + + public static final String LASER_TYPE = "Laser"; + public static final String ELECTRONS_TYPE = "Electrons"; + public static final String PHOTONICS_TYPE = "Photonics"; + + final String CAMERA_DEVICE_NAME = "CurrentCamera"; + boolean useServerStats = true; + String userOverlaysConfigFile; + ColormapSource camera; + PipelineServer server; + String cameraName; + int polling = 1000; + Overlay marker = null; + JDialog histogramDialog; + DiscretePositioner screen; + DiscretePositioner filter; + boolean showFit; + boolean showProfile; + Overlay[] userOv; + Overlay[] fitOv; + Overlay[] profileOv; + Overlay errorOverlay; + boolean requestCameraListUpdate; + boolean goodRegion; + boolean slicing; + String serverUrl; + String camServerUrl; + String instanceName; + Overlay titleOv = null; + //int integration = 0; + boolean persistCameraState; + + public class CameraState extends Config { + + public boolean valid; + public boolean showSidePanel; + //public boolean showMarker; Saved in the stream instance config + public boolean showProfile; + public boolean showFit; + public boolean showReticle; + public boolean showScale; + public boolean showTitle; + public double zoom; + public RendererMode mode; + public boolean colormapAutomatic; + public double colormapMin; + public double colormapMax; + public Colormap colormap; + public boolean colormapLogarithmic; + + String getFile() { + if (camera == null) { + return null; + } + return getContext().getSetup().expandPath("{context}/screen_panel/" + cameraName + ".properties"); + } + } + + void loadCameraState() { + if (persistCameraState) { + try { + CameraState state = new CameraState(); + state.load(state.getFile()); + if (state.valid) { + buttonSidePanel.setSelected(state.showSidePanel); + buttonSidePanelActionPerformed(null); + buttonProfile.setSelected(state.showProfile); + buttonProfileActionPerformed(null); + buttonFit.setSelected(state.showFit); + buttonFitActionPerformed(null); + buttonReticle.setSelected(state.showReticle); + buttonReticleActionPerformed(null); + buttonScale.setSelected(state.showScale); + buttonScaleActionPerformed(null); + buttonTitle.setSelected(state.showTitle); + buttonTitleActionPerformed(null); + renderer.setMode(state.mode); + renderer.setZoom(state.zoom); + if (camera instanceof ColormapSource) { + camera.getConfig().colormap = state.colormap; + camera.getConfig().colormapAutomatic = state.colormapAutomatic; + camera.getConfig().colormapLogarithmic = state.colormapLogarithmic; + camera.getConfig().colormapMax = state.colormapMax; + camera.getConfig().colormapMin = state.colormapMin; + updateColormap(); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + void saveCameraState() { + if (persistCameraState) { + try { + CameraState state = new CameraState(); + state.valid = true; + if (camera instanceof ColormapSource) { + state.colormap = camera.getConfig().colormap; + state.colormapAutomatic = camera.getConfig().colormapAutomatic; + state.colormapLogarithmic = camera.getConfig().colormapLogarithmic; + state.colormapMax = camera.getConfig().colormapMax; + state.colormapMin = camera.getConfig().colormapMin; + } + state.mode = renderer.getMode(); + state.zoom = renderer.getZoom(); + + state.showSidePanel = buttonSidePanel.isSelected(); + state.showProfile = buttonProfile.isSelected(); + state.showFit = buttonFit.isSelected(); + state.showReticle = buttonReticle.isSelected(); + state.showScale = buttonScale.isSelected(); + state.showTitle = buttonTitle.isSelected(); + + state.save(state.getFile()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + String pipelineSuffix = "_sp"; + + Double getServerDouble(String name) { + return (Double) Convert.toDouble(server.getValue(name)); + } + + double[] getServerDoubleArray(String name) { + return (double[]) Convert.toDouble(server.getValue(name)); + } + + class ImageData { + + ImageData() { + if (server != null) { + cache = server.getStream().take(); + String prefix = goodRegion ? "gr_" : ""; + x_fit_mean = getDouble(prefix + "x_fit_mean"); + y_fit_mean = getDouble(prefix + "y_fit_mean"); + x_fit_standard_deviation = getDouble(prefix + "x_fit_standard_deviation"); + y_fit_standard_deviation = getDouble(prefix + "y_fit_standard_deviation"); + x_fit_gauss_function = getDoubleArray(prefix + "x_fit_gauss_function"); + y_fit_gauss_function = getDoubleArray(prefix + "y_fit_gauss_function"); + x_profile = getDoubleArray("x_profile"); + y_profile = getDoubleArray("y_profile"); + x_center_of_mass = getDouble("x_center_of_mass"); + y_center_of_mass = getDouble("y_center_of_mass"); + x_rms = getDouble("x_rms"); + y_rms = getDouble("y_rms"); + if (goodRegion) { + double[] gX2 = new double[x_profile.length]; + Arrays.fill(gX2, Double.NaN); + try { + double[] axis = getDoubleArray("x_axis"); + gr_x_axis = getDoubleArray("gr_x_axis"); + double x = gr_x_axis[0]; + gr_size_x = x_fit_gauss_function.length; + //If gr axis values are not identical, calculate the index... + gr_pos_x = (int) ((renderer.getCalibration() != null) ? renderer.getCalibration().convertToImageX(x) : x); + //But prefer checking the value to avoid raounding errors + for (int i=0;i imageBuffer = new ArrayList(); + Frame currentFrame; + int imageBufferLenght = 1; + Text imagePauseOverlay; + final Console console; + + public ScreenPanel6() { + try { + initComponents(); + spinnerThreshold.setVisible(false); + btFixColormapRange.setVisible(false); + setGoodRegionOptionsVisible(false); + setSlicingOptionsVisible(false); + setRotationOptionsVisible(false); + setAveragingOptionsVisible(false); + JComponent editor = spinnerSlOrientation.getEditor(); + if (editor instanceof JSpinner.DefaultEditor) { + ((JSpinner.DefaultEditor) editor).getTextField().setHorizontalAlignment(JTextField.RIGHT); + } + renderer.setPersistenceFile(Paths.get(getContext().getSetup().getContextPath(), "Renderer_Cameras.bin")); + //setPersistedComponents(new Component[]{buttonServer, buttonDirect}); + setPersistedComponents(new Component[]{buttonTitle}); + comboCameras.setEnabled(false); + comboType.setEnabled(false); + + SwingUtils.setEnumCombo(comboColormap, Colormap.class); + if (App.hasArgument("poll")) { + try { + polling = Integer.valueOf(App.getArgumentValue("poll")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("zoom")) { + try { + renderer.setDefaultZoom(Double.valueOf(App.getArgumentValue("zoom"))); + renderer.resetZoom(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (App.hasArgument("buf")) { + try { + imageBufferLenght = Integer.valueOf(App.getArgumentValue("buf")); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("usr_ov")) { + try { + userOverlaysConfigFile = App.getArgumentValue("usr_ov"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (App.hasArgument("srv_url")) { + serverUrl = App.getArgumentValue("srv_url"); + } + + if (App.hasArgument("cam_srv_url")) { + camServerUrl = App.getArgumentValue("cam_srv_url"); + } + + if (App.hasArgument("calc")) { + useServerStats = false; + } + + if (App.hasArgument("persist")) { + persistCameraState = true; + } + + if (App.hasArgument("suffix")) { + pipelineSuffix = App.getArgumentValue("suffix"); + } + /* + if (App.hasArgument("integration")) { + try { + setIntegration(Integer.valueOf(App.getArgumentValue("integration"))); + if (integration != 0) { + buttonFit.setSelected(false); + buttonProfile.setSelected(false); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + */ + + renderer.setProfileNormalized(true); + renderer.setShowProfileLimits(false); + + JMenuItem menuCalibrate = new JMenuItem("Calibrate..."); + menuCalibrate.addActionListener((ActionEvent e) -> { + try { + calibrate(); + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuRendererConfig = new JMenuItem("Renderer Parameters"); + menuRendererConfig.addActionListener((ActionEvent e) -> { + try { + if (camera != null) { + this.showDeviceConfigDialog(camera, false); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuCameraConfig = new JMenuItem("Camera Configurarion"); + menuCameraConfig.addActionListener((ActionEvent e) -> { + try { + if (camera != null) { + String cameraConfigJson = null; + if (usingServer) { + String cameraServerUrl = (camServerUrl == null) ? server.getUrl().substring(0, server.getUrl().length() - 1) + "8" : camServerUrl; + try (CameraServer srv = new CameraServer("CamServer", cameraServerUrl)) { + srv.initialize(); + //TODO: replace into encodeMultiline + cameraConfigJson = JsonSerializer.encode(srv.getConfig(cameraName), true); + } + + } else { + String configFolder = (String) getContext().getClassByName("SfCamera").getMethod("getConfigFolder", new Class[]{}).invoke(null); + Path configFile = Paths.get(configFolder, cameraName + ".json"); + cameraConfigJson = configFile.toFile().exists() ? new String(Files.readAllBytes(configFile)) : null; + } + TextEditor configEditor = new TextEditor(); + configEditor.setText(cameraConfigJson); + configEditor.setReadOnly(true); + configEditor.setTitle(cameraName); + EditorDialog dlg = configEditor.getDialog(getTopLevel(), false); + dlg.setSize(480, 640); + dlg.setVisible(true); + SwingUtils.centerComponent(getTopLevel(), dlg); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSetImageBufferSize = new JMenuItem("Set Stack Size..."); + menuSetImageBufferSize.addActionListener((ActionEvent e) -> { + try { + String ret = SwingUtils.getString(getTopLevel(), "Enter size of image buffer: ", String.valueOf(imageBufferLenght)); + if (ret != null) { + this.setImageBufferSize(Integer.valueOf(ret)); + } + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSaveStack = new JMenuItem("Save Stack"); + menuSaveStack.addActionListener((ActionEvent e) -> { + try { + saveStack(); + } catch (Exception ex) { + showException(ex); + } + }); + + JMenuItem menuSetROI = new JMenuItem("Set ROI..."); + menuSetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (server != null) { + final Overlays.Rect selection = new Overlays.Rect(renderer.getPenMovingOverlay()); + renderer.addListener(new RendererListener() { + @Override + public void onSelectionFinished(Renderer renderer, Overlay overlay) { + try { + renderer.setShowReticle(false); + Rectangle roi = overlay.isFixed() ? renderer.toImageCoord(overlay.getBounds()) : overlay.getBounds(); + if (server.isRoiEnabled()) { + int[] cur = server.getRoi(); + server.setRoi(new int[]{roi.x + cur[0], roi.y + cur[1], roi.width, roi.height}); + } else { + server.setRoi(new int[]{roi.x, roi.y, roi.width, roi.height}); + } + } catch (Exception ex) { + } finally { + renderer.removeListener(this); + } + } + + @Override + public void onSelectionAborted(Renderer renderer, Overlay overlay) { + renderer.removeListener(this); + } + }); + selection.setFixed(true); + renderer.startSelection(selection); + } + }); + + JMenuItem menuResetROI = new JMenuItem("Reset ROI"); + menuResetROI.addActionListener((ActionEvent e) -> { + renderer.abortSelection(); + if (server != null) { + try { + renderer.setShowReticle(false); + server.resetRoi(); + } catch (IOException ex) { + showException(ex); + } + } + }); + /* + JCheckBoxMenuItem menuFrameIntegration = new JCheckBoxMenuItem("Multi-Frame", (integration != 0)); + menuFrameIntegration.addActionListener((ActionEvent e) -> { + if (integration == 0) { + JPanel panel = new JPanel(); + GridBagLayout layout = new GridBagLayout(); + layout.columnWidths = new int[]{150, 50}; //Minimum width + layout.rowHeights = new int[]{30, 30}; //Minimum height + panel.setLayout(layout); + JCheckBox checkContinuous = new JCheckBox(""); + checkContinuous.setSelected(true); + JTextField textFrames = new JTextField(); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Number of frames:"), c); + c.gridy = 1; + panel.add(new JLabel("Continuous:"), c); + c.fill = GridBagConstraints.HORIZONTAL; + c.gridx = 1; + panel.add(checkContinuous, c); + c.gridy = 0; + panel.add(textFrames, c); + if (SwingUtils.showOption(getTopLevel(), "Multi-Frame Integration", panel, OptionType.OkCancel) == OptionResult.Yes) { + setIntegration(checkContinuous.isSelected() ? -(Integer.valueOf(textFrames.getText())) : (Integer.valueOf(textFrames.getText()))); + } + } else { + if (SwingUtils.showOption(getTopLevel(), "Multi-Frame Integration", + "Do you want to disable " + ((integration < 0) ? "continuous " : "") + "multi-frame integration (" + Math.abs(integration) + ")?", OptionType.YesNo) == OptionResult.Yes) { + setIntegration(0); + } + } + }); + + for (Component cmp : SwingUtils.getComponentsByType(renderer.getPopupMenu(), JMenu.class)) { + JMenu menu = (JMenu) cmp; + if (menu.getText().equals("Integration")) { + menu.addSeparator(); + menu.add(menuFrameIntegration); + } + } + */ + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuRendererConfig); + renderer.getPopupMenu().add(menuCameraConfig); + renderer.getPopupMenu().add(menuSetImageBufferSize); + renderer.getPopupMenu().add(menuSaveStack); + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuCalibrate); + renderer.getPopupMenu().addSeparator(); + renderer.getPopupMenu().add(menuSetROI); + renderer.getPopupMenu().add(menuResetROI); + renderer.getPopupMenu().addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + menuResetROI.setEnabled(server != null); + menuSetROI.setEnabled(server != null); + menuCalibrate.setVisible(server != null); + menuCalibrate.setEnabled((calibrationDialolg == null) || (!calibrationDialolg.isShowing())); + menuSaveStack.setEnabled(imageBufferLenght > 0); + menuSetImageBufferSize.setEnabled(!renderer.isPaused()); + //menuFrameIntegration.setSelected(integration != 0); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + renderer.getPopupMenu().setVisible(false); + buttonScale.setSelected(renderer.getShowColormapScale()); + clearMarker(); + + showFit = buttonFit.isSelected(); + showProfile = buttonProfile.isSelected(); + + pauseSelection.setVisible(false); + pauseSelection.setMinValue(1); + pauseSelection.addListener(new ValueSelectionListener() { + @Override + public void onValueChanged(ValueSelection origin, double value, boolean editing) { + if (editing && (value >= 1) && (value <= imageBuffer.size())) { + updatePause(); + } + } + }); + renderer.addListener(new RendererListener() { + @Override + public void onMoveFinished(Renderer renderer, Overlay overlay) { + if (overlay == marker) { + try { + onMarkerChanged(); + } catch (IOException ex) { + Logger.getLogger(ScreenPanel6.class.getName()).log(Level.WARNING, null, ex); + } + } + } + }); + if (MainFrame.isDark()) { + textState.setDisabledTextColor(textState.getForeground()); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + + console = (!App.hasArgument("console")) ? null : new Console() { + /* + protected void onConsoleCommand(String name, String[] pars, String trimming) throws Exception { + switch (name) { + case "cam": + comboCameras.setSelectedItem(tokens[1]); + break; + } + }*/ + @Override + protected void onConsoleCommand(String command) { + String[] tokens = command.split(" "); + if ((tokens.length > 1) && tokens[0].equals("cam")) { + try { + if (!tokens[1].equals(comboCameras.getSelectedItem())) { + setComboTypeSelection("All"); + updateCameraList(); + comboCameras.setSelectedItem(tokens[1]); + if (!tokens[1].equals(comboCameras.getSelectedItem())) { + comboCameras.setSelectedItem(""); + throw new Exception("Invalid camera name : " + tokens[1]); + } + System.out.println("Console set camera: " + tokens[1]); + } + } catch (Exception ex) { + System.err.println(ex); + } + } else { + System.err.println("Invalid command: " + command); + } + } + }; + } + + /* + void setIntegration(int frames) { + try { + if (integration != frames) { + integration = frames; + if (camera != null) { + if (Math.abs(integration) > 1) { + renderer.setDevice(new ImageIntegrator(integration)); + } else { + renderer.setDevice(camera); + } + synchronized (imageBuffer) { + currentFrame = null; + imageBuffer.clear(); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + */ + + @Override + public void onStart() { + super.onStart(); + updateDialogTitle(); + if (App.hasArgument("ct")) { + boolean direct = App.getArgumentValue("ct").equals("0") || App.getArgumentValue("ct").equalsIgnoreCase("false"); + buttonServer.setSelected(!direct); + buttonDirect.setSelected(direct); + } + if (App.hasArgument("console")) { + console.start(); + } + } + + @Override + public void onStop() { + try { + if (camera != null) { + saveCameraState(); + camera.close(); + camera = null; + server = null; + updateButtons(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + try { + if (console != null) { + console.stop(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + super.onStop(); + } + + //Overridable callbacks + @Override + public void onInitialize(int runCount) { + comboCameras.setEnabled(false); + comboType.setEnabled(false); + if (App.hasArgument("s")) { + renderer.setDevice((Source) getDevice("image")); + renderer.setAutoScroll(true); + ((Source) getDevice("image")).addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + manageFit(bi, data); + manageUserOverlays(bi, data); + } + + @Override + public void onError(Object o, Exception ex) { + } + } + ); + + } else { + usingServer = buttonServer.isSelected(); + updateCameraList(); + comboCameras.setEnabled(true); + comboType.setEnabled(true); + setComboCameraSelection(null); + setComboTypeSelection("All"); + + if (comboCameras.getModel().getSize() > 0) { + try { + if (App.hasArgument("cam")) { + setComboCameraSelection(App.getArgumentValue("cam")); + comboCamerasActionPerformed(null); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + updateButtons(); + startTimer(1000); + } + + boolean isVisible(String camera) { + return ((comboType.getSelectedIndex() == 0) || (getCameraType(camera).equals(comboType.getSelectedItem()))); + } + + DefaultComboBoxModel getCameraList(boolean fromServer) throws Exception { + DefaultComboBoxModel model = new DefaultComboBoxModel(); + if (fromServer) { + try (PipelineServer srv = newServer()) { + srv.initialize(); + List cameras = srv.getCameras(); + Collections.sort(cameras); + for (String camera : cameras) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + + } else { + ArrayList cameras = (ArrayList) getContext().getClassByName("SfCamera").getMethod("getCameras", new Class[]{}).invoke(null); + for (String camera : cameras) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + if (App.hasArgument("cam")) { + String camera = App.getArgumentValue("cam"); + if (model.getIndexOf(camera) < 0) { + if (isVisible(camera)) { + model.addElement(camera); + } + } + } + model.addElement(""); + + return model; + } + + PipelineServer newServer() throws IOException { + if (serverUrl != null) { + System.out.println("Connecting to server: " + serverUrl); + server = new PipelineServer(CAMERA_DEVICE_NAME, serverUrl); + } else { + System.out.println("Connecting to server"); + server = new PipelineServer(CAMERA_DEVICE_NAME); + } + updateButtons(); + return server; + } + + boolean updatingCameraSelection; + + void setComboCameraSelection(Object selection) { + updatingCameraSelection = true; + try { + comboCameras.setSelectedItem(selection); + } finally { + updatingCameraSelection = false; + } + } + + void setComboTypeSelection(Object selection) { + updatingCameraSelection = true; + try { + comboType.setSelectedItem(selection); + } finally { + updatingCameraSelection = false; + } + } + boolean usingServer; + + void updateCameraList() { + try { + String selected = (String) comboCameras.getSelectedItem(); + comboCameras.setModel(getCameraList(usingServer)); + if (selected != null) { + if (((DefaultComboBoxModel) comboCameras.getModel()).getIndexOf(camera) < 0) { + setComboCameraSelection(selected); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + } + } + + final Object lockOverlays = new Object(); + + void manageFit(BufferedImage bi, Data data) { + Overlay[][] fo = null; + if ((showFit || showProfile)) { + try { + fo = getFitOverlays(data); + } catch (Exception ex) { + System.err.println(ex); + } + } + synchronized (lockOverlays) { + fo = (fo == null) ? new Overlay[][]{null, null} : fo; + renderer.updateOverlays(fo[0], profileOv); + profileOv = fo[0]; + renderer.updateOverlays(fo[1], fitOv); + fitOv = fo[1]; + } + } + + void manageUserOverlays(BufferedImage bi, Data data) { + Overlay[] fo = (bi == null) ? null : getUserOverlays(data); + synchronized (lockOverlays) { + renderer.updateOverlays(fo, userOv); + userOv = fo; + } + } + + void updateDialogTitle() { + if (App.isDetached()) { + getTopLevel().setTitle(cameraName == null ? "ScreenPanel" : cameraName); + } + } + + void manageTitleOverlay() { + Overlay to = null; + if ((buttonTitle.isSelected()) && (cameraName != null)) { + Font font = new Font("Arial", Font.PLAIN, 28); + to = new Text(renderer.getPenErrorText(), cameraName, font, new Point(-SwingUtils.getTextSize(cameraName, renderer.getGraphics().getFontMetrics(font)).width - 14, 26)); + to.setFixed(true); + to.setAnchor(Overlay.ANCHOR_VIEWPORT_OR_IMAGE_TOP_RIGHT); + } + + synchronized (lockOverlays) { + renderer.updateOverlays(to, titleOv); + titleOv = to; + } + } + + @Override + public void onStateChange(State state, State former) { + + } + + @Override + public void onExecutedFile(String fileName, Object result) { + } + + //Callback to perform update - in event thread + @Override + protected void doUpdate() { + } + + Thread devicesInitTask; + + void setCamera(String cameraName) throws IOException, InterruptedException { + System.out.println("Initializing: " + cameraName); + parseUserOverlays(); + errorOverlay = null; + lastMarkerPos = null; + lastFrame = null; + lastPipelinePars = null; + + if (dataTableDialog != null) { + dataTableDialog.dispose(); + dataTableDialog = null; + } + dataTableModel = null; + + if (calibrationDialolg != null) { + calibrationDialolg.dispose(); + calibrationDialolg = null; + } + + boolean was_server = false; + if (camera != null) { + saveCameraState(); + //camera.removeAllListeners(); + was_server = (server != null); + camera.close(); + camera = null; + server = null; + } + updateButtons(); + instanceName = null; + renderer.setDevice(null); + renderer.setShowReticle(false); + renderer.removeOverlays(fitOv); + renderer.removeOverlays(profileOv); + renderer.removeOverlays(userOv); + renderer.clear(); + renderer.resetZoom(); + + boolean changed = !String.valueOf(cameraName).equals(this.cameraName); + this.cameraName = cameraName; + + if (changed || buttonDirect.isSelected()) { + spinnerThreshold.setVisible(false); + checkThreshold.setEnabled(false); + checkRotation.setEnabled(false); + checkAveraging.setEnabled(false); + checkGoodRegion.setEnabled(false); + setGoodRegionOptionsVisible(false); + setSlicingOptionsVisible(false); + setRotationOptionsVisible(false); + setAveragingOptionsVisible(false); + } + synchronized (imageBuffer) { + currentFrame = null; + imageBuffer.clear(); + } + if (changed) { + checkBackground.setEnabled(false); + if ((devicesInitTask != null) && (devicesInitTask.isAlive())) { + devicesInitTask.interrupt(); + } + if (screen != null) { + screen.close(); + screen = null; + } + if (filter != null) { + filter.close(); + filter = null; + } + if (renderer.isPaused()) { + renderer.resume(); + removePauseOverlay(); + pauseSelection.setVisible(false); + panelCameraSelection.setVisible(true); + } + } + manageTitleOverlay(); + updateDialogTitle(); + + if (cameraName == null) { + return; + } + + System.out.println("Setting camera: " + cameraName + " [" + (buttonServer.isSelected() ? "server" : "direct") + "]"); + try { + if (buttonServer.isSelected()) { + camera = newServer(); + camera.getConfig().flipHorizontally = false; + camera.getConfig().flipVertically = false; + camera.getConfig().rotation = 0.0; + camera.getConfig().roiX = 0; + camera.getConfig().roiY = 0; + camera.getConfig().roiWidth = -1; + camera.getConfig().roiHeight = -1; + } else { + //camera = new SfCamera(CAMERA_DEVICE_NAME, cameraName); + camera = (ColormapSource) getContext().getClassByName("SfCamera").getConstructor(new Class[]{String.class, String.class}).newInstance(new Object[]{CAMERA_DEVICE_NAME, cameraName}); + } + camera.initialize(); + camera.assertInitialized(); + System.out.println("Camera initialization OK"); + loadCameraState(); + if (server != null) { + //server.start(cameraName, false); + String pipelineName = cameraName + pipelineSuffix; + instanceName = cameraName + pipelineSuffix + "1"; + if (!server.getPipelines().contains(pipelineName)) { + System.out.println("Creating pipeline: " + pipelineName); + HashMap config = new HashMap<>(); + config.put("camera_name", cameraName); + //server.createFromConfig(config, pipelineName); + server.savePipelineConfig(pipelineName, config); + } + server.start(pipelineName, instanceName); + + updatePipelineControls(); + checkThreshold.setEnabled(true); + checkRotation.setEnabled(true); + checkAveraging.setEnabled(true); + checkGoodRegion.setEnabled(true); + } else { + checkThreshold.setSelected(false); + checkRotation.setSelected(false); + checkAveraging.setSelected(false); + checkGoodRegion.setSelected(false); + if (polling <= 0) { + camera.setMonitored(true); + } else { + camera.setPolling(polling); + } + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + updateButtons(); + camera.getConfig().save(); + + //if (Math.abs(integration) > 1) { + // renderer.setDevice(new ImageIntegrator(integration)); + //} else { + renderer.setDevice(camera); + //} + + renderer.setAutoScroll(true); + //renderer.setMarker(marker); + clearMarker(); + imageSize = null; + + camera.addListener(new ImageListener() { + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + if (bi != null) { + if ((imageSize == null) || imageSize.width != bi.getWidth() || imageSize.height != bi.getHeight()) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + if ((renderer.getMode() == RendererMode.Zoom) || (renderer.getMode() == RendererMode.Fixed)) { + centralizeRenderer(); + } + checkReticle(); + } + }); + imageSize = new Dimension(bi.getWidth(), bi.getHeight()); + } + renderer.setProfileSize(Math.min(bi.getWidth(), bi.getHeight())); + } + //renderer.setCalibration(camera.getCalibration()); + if (!renderer.isPaused()) { + if (data != null) { + synchronized (imageBuffer) { + currentFrame = new Frame(data); + if (imageBufferLenght >= 1) { + imageBuffer.add(currentFrame); + if (imageBuffer.size() > imageBufferLenght) { + imageBuffer.remove(0); + setBufferFull(true); + } else { + setBufferFull(false); + } + } else { + setBufferFull(true); + } + //Update data + if (!renderer.isPaused()) { + updateStreamData(); + } + updateMarker(); + } + } + manageFit(bi, data); + manageUserOverlays(bi, data); + } + //updateImageData(); + } + + @Override + public void onError(Object o, Exception ex) { + //System.err.println(ex); + } + }); + + } catch (Exception ex) { + showException(ex); + renderer.clearOverlays(); + updatePipelineControls(); + if (renderer.getDevice() == null) { + //renderer.setZoom(1.0); + //renderer.setMode(RendererMode.Zoom); + errorOverlay = new Text(renderer.getPenErrorText(), ex.toString(), new Font("Verdana", Font.PLAIN, 12), new Point(20, 20)); + errorOverlay.setFixed(true); + errorOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + renderer.addOverlay(errorOverlay); + } + } finally { + //checkReticle(); + onTimer(); + } + onChangeColormap(null); + checkBackground.setEnabled(true); + if (changed) { + boolean electrons = getCameraType(cameraName).equals(ELECTRONS_TYPE); + comboScreen.setModel(new DefaultComboBoxModel()); + comboScreen.setEnabled(false); + comboFilter.setModel(new DefaultComboBoxModel()); + comboFilter.setEnabled(false); + panelFilter.setVisible(electrons); + panelScreen.setVisible(electrons); + if (electrons) { + //Parallelizing initialization + devicesInitTask = new Thread(() -> { + try { + if (cameraName.contains("DSRM")) { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":POSITION_SP", cameraName + ":POSITION"); + } else { + screen = new DiscretePositioner("CurrentScreen", cameraName + ":SET_SCREEN1_POS", cameraName + ":GET_SCREEN1_POS"); + } + screen.setMonitored(true); + screen.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : screen.getPositions()) { + model.addElement(pos); + } + comboScreen.setModel(model); + comboScreen.setSelectedItem(screen.read()); + + } catch (Exception ex) { + comboScreen.setModel(new DefaultComboBoxModel()); + System.err.println(ex.getMessage()); + screen = null; + } + comboScreen.setEnabled(screen != null); + valueScreen.setDevice(screen); + + try { + filter = new DiscretePositioner("CurrentFilter", cameraName + ":SET_FILTER", cameraName + ":GET_FILTER"); + filter.setMonitored(true); + filter.initialize(); + DefaultComboBoxModel model = new DefaultComboBoxModel(); + for (String pos : filter.getPositions()) { + model.addElement(pos); + } + comboFilter.setModel(model); + comboFilter.setSelectedItem(filter.read()); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + filter = null; + } + comboFilter.setEnabled(filter != null); + valueFilter.setDevice(filter); + }); + devicesInitTask.start(); + } + } + } + /* + class ImageIntegrator extends ColormapSource { + + ImageIntegrator(int num) { + super("Image Averager", camera.getConfig()); + boolean continuous = (num < 0); + final int numImages = Math.abs(num); + + camera.addListener(new ImageListener() { + final ArrayList buffer = new ArrayList(); + Data integration = null; + + @Override + public void onImage(Object o, BufferedImage bi, Data data) { + try { + if (continuous) { + buffer.add(data); + if (buffer.size() >= numImages) { + for (Data d : buffer) { + process(d); + } + } + } else { + buffer.add(null); //Just to count + process(data); + } + } catch (Exception ex) { + buffer.clear(); + integration = null; + ImageIntegrator.this.pushData(null); + ex.printStackTrace(); + return; + } + if (buffer.size() >= numImages) { + if (continuous) { + buffer.remove(0); + } else { + buffer.clear(); + } + if (integration != null) { + //integration.div(numImages); + ImageIntegrator.this.pushData(integration); + } + integration = null; + } + } + + void process(Data data) { + if (integration == null) { + integration = new Data(data); + } else { + integration.sum(data); + } + } + + @Override + public void onError(Object origin, Exception ex) { + } + }); + + } + } + */ + + boolean bufferFull = true; + + void setBufferFull(boolean value) { + if (value != bufferFull) { + SwingUtilities.invokeLater(() -> { + buttonPause.setBackground(value ? buttonSave.getBackground() : buttonSave.getBackground().brighter()); + }); + bufferFull = value; + } + } + + volatile Dimension imageSize; + + void checkReticle() { + if ((renderer.getDevice() != null) && (camera != null) && (camera.getConfig().isCalibrated()) && buttonReticle.isSelected()) { + //renderer.setCalibration(camera.getCalibration()); + renderer.configureReticle(new Dimension(800, 800), 200); + renderer.setShowReticle(true); + } else { + //renderer.setCalibration(null); + renderer.setShowReticle(false); + } + renderer.refresh(); + } + + void checkMarker(Point p) throws IOException { + if (camera != null) { + if (buttonMarker.isSelected()) { + Dimension d = renderer.getImageSize(); + if (p == null) { + p = (d == null) ? new Point(renderer.getWidth() / 2, renderer.getHeight() / 2) : new Point(d.width / 2, d.height / 2); + } + Overlay ov = null; + marker = new Overlays.Crosshairs(renderer.getPenMarker(), p, new Dimension(100, 100)); + marker.setMovable(true); + marker.setPassive(false); + } else { + marker = null; + } + renderer.setMarker(marker); + onMarkerChanged(); + } + } + + Point lastMarkerPos; + + void onMarkerChanged() throws IOException { + lastMarkerPos = getStreamMarkerPos(); + if (marker == null) { + setInstanceConfigValue("Marker", null); + } else { + setInstanceConfigValue("Marker", new int[]{marker.getPosition().x, marker.getPosition().y}); + } + } + + void updateMarker() { + try { + if (server != null) { + Point p = getStreamMarkerPos(); + if (p != null) { + //To prevent a local change being overriden by a message having the old settings. + //TODO: This is not bullet-proof, as one can have 2 changes between 2 frames... + if (!p.equals(lastMarkerPos)) { + if (p.x == Integer.MIN_VALUE) { + if (buttonMarker.isSelected()) { + buttonMarker.setSelected(false); + checkMarker(null); + } + } else { + if (!buttonMarker.isSelected()) { + buttonMarker.setSelected(true); + checkMarker(p); + } else { + if (!p.equals(marker.getPosition())) { + marker.setPosition(p); + } + } + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + Point getStreamMarkerPos() throws IOException { + //System.out.println(server.getInstanceConfig().get("Marker")); + Map pars = server.getProcessingParameters(); + if (pars != null) { + List markerPosition = (List) pars.get("Marker"); + if (markerPosition != null) { + return new Point((Integer) markerPosition.get(0), (Integer) markerPosition.get(1)); + } + return new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); + } + return null; + } + + void clearMarker() { + marker = null; + renderer.setMarker(marker); + } + + void setInstanceConfigValue(String name, Object value) throws IOException { + if (server != null) { + Map map = server.getInstanceConfig(); + map.put(name, value); + server.setInstanceConfig(map); + } + } + + void updateZoom() { + try { + buttonZoomStretch.setSelected(renderer.getMode() == RendererMode.Stretch); + buttonZoomFit.setSelected(renderer.getMode() == RendererMode.Fit); + if (renderer.getMode() == RendererMode.Fixed) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getMode() == RendererMode.Zoom) { + if (renderer.getZoom() == 1) { + buttonZoomNormal.setSelected(true); + } else if (renderer.getZoom() == 0.5) { + buttonZoom05.setSelected(true); + } else if (renderer.getZoom() == 0.25) { + buttonZoom025.setSelected(true); + } else if (renderer.getZoom() == 2.0) { + buttonZoom2.setSelected(true); + } else { + buttonGroup1.clearSelection(); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + boolean updatingColormap; + + void updateColormap() { + updatingColormap = true; + try { + if ((camera != null) && (camera instanceof ColormapSource)) { + ColormapSourceConfig config = ((ColormapSource) camera).getConfig(); + comboColormap.setSelectedItem(config.colormap); + if (config.isDefaultColormap()) { + buttonFullRange.setSelected(true); + } else if (config.colormapAutomatic) { + buttonAutomatic.setSelected(true); + } else { + buttonManual.setSelected(true); + } + btFixColormapRange.setVisible(buttonAutomatic.isSelected()); + spinnerMin.setEnabled(buttonManual.isSelected()); + spinnerMax.setEnabled(buttonManual.isSelected()); + if (!Double.isNaN(config.colormapMin)) { + spinnerMin.setValue(Math.min(Math.max((int) config.colormapMin, 0), 65535)); + } + if (!Double.isNaN(config.colormapMax)) { + spinnerMax.setValue(Math.min(Math.max((int) config.colormapMax, 0), 65535)); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + updatingColormap = false; + } + + void updatePipelineProperties() { + goodRegion = checkGoodRegion.isSelected(); + spinnerThreshold.setVisible(checkThreshold.isSelected()); + setGoodRegionOptionsVisible(goodRegion); + slicing = goodRegion && checkSlicing.isSelected(); + setSlicingOptionsVisible(slicing); + updatingServerControls = false; + boolean rotation = checkRotation.isSelected(); + setRotationOptionsVisible(rotation); + boolean averaging = checkAveraging.isSelected(); + setAveragingOptionsVisible(averaging); + } + + boolean updatingServerControls; + + void updatePipelineControls() { + if (server != null) { + updatingServerControls = true; + if (server.isStarted()) { + try { + checkBackground.setSelected(server.getBackgroundSubtraction()); + Double threshold = (server.getThreshold()); + checkThreshold.setSelected(threshold != null); + spinnerThreshold.setValue((threshold == null) ? 0 : threshold); + Map gr = (server.getGoodRegion()); + checkGoodRegion.setSelected(gr != null); + if (gr != null) { + spinnerGrThreshold.setValue(((Number) gr.get("threshold")).doubleValue()); + spinnerGrScale.setValue(((Number) gr.get("gfscale")).doubleValue()); + } + Map rotation = server.getRotation(); + checkRotation.setSelected(rotation != null); + if (rotation!=null){ + spinnerRotationAngle.setValue(((Number) rotation.get("angle")).doubleValue()); + spinnerRotationOrder.setValue(((Number) rotation.get("order")).intValue()); + String mode = (String) rotation.get("mode"); + try{ + spinnerRotationConstant.setValue(Double.valueOf(mode)); + spinnerRotationMode.setValue("constant"); + } catch (Exception ex){ + spinnerRotationConstant.setValue(0); + spinnerRotationMode.setValue(mode); + } + } + + Number averaging = (Number) server.getInstanceConfig().get("averaging"); + checkAveraging.setSelected(averaging != null); + if (averaging!=null){ + spinnerAvFrames.setValue(Math.abs(averaging.intValue())); + spinnerAvMode.setValue(averaging.intValue()<0 ? "window" : "single"); + } + + + Map slicing = (server.getSlicing()); + checkSlicing.setSelected(slicing != null); + if (slicing != null) { + spinnerSlNumber.setValue(((Number) slicing.get("number_of_slices")).intValue()); + spinnerSlScale.setValue(((Number) slicing.get("scale")).doubleValue()); + spinnerSlOrientation.setValue((String) slicing.get("orientation")); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + updatePipelineProperties(); + } + } + + boolean changedPipelinePars(Map pars1, Map pars2) { + String[] keys = new String[]{"image_background_enable", "image_threshold", "image_good_region", + "threshold", "gfscale", "image_slices", "number_of_slices", "scale", "orientation"}; + for (String key : keys) { + Object o1 = pars1.get(key); + Object o2 = pars2.get(key); + if (o1 == null) { + if (o2 != null) { + return true; + } + } else if (!o1.equals(o2)) { + return true; + } + } + return false; + } + + void updatePipelineControls(Map pars) { + if (pars != null) { + updatingServerControls = true; + try { + boolean background = (boolean) pars.get("image_background_enable"); + checkBackground.setSelected(background); + Double threshold = (Double) (pars.get("image_threshold")); + checkThreshold.setSelected(threshold != null); + spinnerThreshold.setValue((threshold == null) ? 0 : threshold); + Map gr = (Map) pars.get("image_good_region"); + checkGoodRegion.setSelected(gr != null); + if (gr != null) { + Double value = ((Number) gr.get("threshold")).doubleValue(); + spinnerGrThreshold.setValue(value); + Double scale = ((Number) gr.get("gfscale")).doubleValue(); + spinnerGrScale.setValue(scale); + } + Map slicing = (Map) (pars.get("image_slices")); + checkSlicing.setSelected(slicing != null); + if (slicing != null) { + int slices = ((Number) slicing.get("number_of_slices")).intValue(); + spinnerSlNumber.setValue(slices); + double scale = ((Number) slicing.get("scale")).doubleValue(); + spinnerSlScale.setValue(scale); + String orientation = (String) slicing.get("orientation"); + spinnerSlOrientation.setValue(orientation); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + updatePipelineProperties(); + } + } + + void setGoodRegionOptionsVisible(boolean visible) { + spinnerGrThreshold.setVisible(visible); + labelGrThreshold.setVisible(visible); + spinnerGrScale.setVisible(visible); + labelGrScale.setVisible(visible); + panelSlicing.setVisible(visible); + } + + void setSlicingOptionsVisible(boolean visible) { + spinnerSlNumber.setVisible(visible); + labelSlNumber.setVisible(visible); + spinnerSlScale.setVisible(visible); + labelSlScale.setVisible(visible); + spinnerSlOrientation.setVisible(visible); + labelSlOrientation.setVisible(visible); + } + + void setAveragingOptionsVisible(boolean visible) { + labelAvMode.setVisible(visible); + labelAvFrames.setVisible(visible); + spinnerAvMode.setVisible(visible); + spinnerAvFrames.setVisible(visible); + } + + void setRotationOptionsVisible(boolean visible) { + labelAngle.setVisible(visible); + labelOrder.setVisible(visible); + labelMode.setVisible(visible); + labelConstant.setVisible(visible); + spinnerRotationAngle.setVisible(visible); + spinnerRotationOrder.setVisible(visible); + spinnerRotationMode.setVisible(visible); + spinnerRotationConstant.setVisible(visible); + } + + boolean isCameraStopped() { + if ((server != null) && !server.isStarted()) { + return true; + } + return ((camera == null) || camera.isClosed()); + } + + boolean updatingButtons; + + void updateButtons() { + updatingButtons = true; + try { + boolean active = !isCameraStopped();//(camera != null); + buttonSave.setEnabled(active); + buttonGrabBackground.setEnabled(active); + buttonMarker.setEnabled(active); + buttonProfile.setEnabled(active); + buttonFit.setEnabled(active); + buttonReticle.setEnabled(active && camera.getConfig().isCalibrated()); + buttonStreamData.setEnabled(active && (server != null)); + buttonPause.setEnabled(active); + + if (renderer.isPaused() != buttonPause.isSelected()) { + buttonPause.setSelected(renderer.isPaused()); + buttonPauseActionPerformed(null); + } + if (renderer.getShowReticle() != buttonReticle.isSelected()) { + //buttonReticle.setSelected(renderer.getShowReticle()); + } + if ((renderer.getMarker() == null) && buttonMarker.isSelected()) { + buttonMarker.setSelected(false); + } + buttonSave.setSelected(renderer.isSnapshotDialogVisible()); + + } finally { + updatingButtons = false; + } + } + + Frame lastFrame = null; + Map lastPipelinePars = null; + + @Override + protected void onTimer() { + for (Device dev : new Device[]{screen, filter}) { + if (dev != null) { + dev.request(); + } + } + + textState.setText((camera == null) ? "" : camera.getState().toString()); + if (App.hasArgument("s")) { + try { + ((Source) getDevice("image")).initialize(); + } catch (IOException ex) { + Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); + } catch (InterruptedException ex) { + Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); + } + } + updateZoom(); + updateColormap(); + updateButtons(); + checkHistogram.setSelected((histogramDialog != null) && (histogramDialog.isShowing())); + buttonScale.setSelected(renderer.getShowColormapScale()); + try { + Frame frame = getCurrentFrame(); + if (frame != lastFrame) { + lastFrame = frame; + if (frame != null) { + Map pars = getProcessingParameters(frame.cache); + if ((lastPipelinePars == null) || changedPipelinePars(pars, lastPipelinePars)) { + //System.out.println("Update pipeline: " + pars); + lastPipelinePars = pars; + updatePipelineControls(pars); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + Pen penFit = new Pen(new Color(192, 105, 0), 0); + Pen penCross = new Pen(new Color(192, 105, 0), 0); + Pen penSlices = new Pen(Color.CYAN.darker(), 1); + + Frame getCurrentFrame() { + if ((imageBufferLenght > 1) && (renderer.isPaused())) { + int index = ((int) pauseSelection.getValue()) - 1; + synchronized (imageBuffer) { + return (index < imageBuffer.size()) ? imageBuffer.get(index) : null; + } + } + return currentFrame; + } + + Frame getFrame(Data data) { + synchronized (imageBuffer) { + for (Frame f : imageBuffer) { + if (f.data == data) { + return f; + } + } + } + return null; + } + + void setImageBufferSize(int size) { + if (renderer.isPaused()) { + throw new RuntimeException("Cannot change buffer size whn paused"); + } + synchronized (imageBuffer) { + imageBufferLenght = size; + imageBuffer.clear(); + } + + } + + Overlay[][] getFitOverlays(Data data) { + Overlays.Polyline hgaussian = null; + Overlays.Polyline vgaussian = null; + Overlays.Polyline hprofile = null; + Overlays.Polyline vprofile = null; + Double xMean = null, xSigma = null, xNorm = null, xCom = null, xRms = null; + Double yMean = null, ySigma = null, yNorm = null, yCom = null, yRms = null; + double[] pX = null, pY = null, gX = null, gY = null; + PointDouble[] sliceCenters = null; + if (data != null) { + int height = data.getHeight(); + int width = data.getWidth(); + int profileSize = renderer.getProfileSize(); + ImageData id = null; + if ((useServerStats) && (server != null)) { + try { + id = getFrame(data); + if (id == null) { + return null; + } + xMean = id.x_fit_mean; + xSigma = id.x_fit_standard_deviation; + yMean = id.y_fit_mean; + ySigma = id.y_fit_standard_deviation; + gX = id.x_fit_gauss_function; + gY = id.y_fit_gauss_function; + pX = id.x_profile; + pY = id.y_profile; + xCom = id.x_center_of_mass; + xRms = id.x_rms; + yCom = id.y_center_of_mass; + yRms = id.y_rms; + sliceCenters = id.sliceCenters; + + profileSize /= 4; + if (pX != null) { + int[] xp = Arr.indexesInt(pX.length); + int[] xg = xp; + int[] yp = new int[pX.length]; + int[] yg = new int[pX.length]; + + List l = Arrays.asList((Double[]) Convert.toWrapperArray(pX)); + double minProfile = Collections.min(l); + double maxProfile = Collections.max(l); + double rangeProfile = maxProfile - minProfile; + double minGauss = minProfile; + double rangeGauss = rangeProfile; + //If not good region, range of profile and fit are similar so save this calcultion + if (goodRegion && id.gr_size_x > 0) { + l = Arrays.asList((Double[]) Convert.toWrapperArray(Arrays.copyOfRange(gX, id.gr_pos_x, id.gr_pos_x + id.gr_size_x))); + minGauss = Collections.min(l); + rangeGauss = Collections.max(l) - minGauss; + } + + for (int i = 0; i < xp.length; i++) { + if (gX != null) { + yg[i] = (int) (height - 1 - (((gX[i] - minGauss) / rangeGauss) * profileSize)); + } + yp[i] = (int) (height - 1 - (((pX[i] - minProfile) / rangeProfile) * profileSize)); + } + + if (goodRegion && id.gr_size_x > 0) { + xg = Arrays.copyOfRange(xg, id.gr_pos_x, id.gr_pos_x + id.gr_size_x); + yg = Arrays.copyOfRange(yg, id.gr_pos_x, id.gr_pos_x + id.gr_size_x); + } + + vgaussian = new Overlays.Polyline(penFit, xg, yg); + vprofile = new Overlays.Polyline(renderer.getPenProfile(), xp, yp); + } + + if (pY != null) { + int[] xp = new int[pY.length]; + int[] xg = new int[pY.length]; + int[] yp = Arr.indexesInt(pY.length); + int[] yg = yp; + + List l = Arrays.asList((Double[]) Convert.toWrapperArray(pY)); + double minProfile = Collections.min(l); + double maxProfile = Collections.max(l); + double rangeProfile = maxProfile - minProfile; + double minGauss = minProfile; + double rangeGauss = rangeProfile; + //If not good region, range of profile and fit are similar so save this calcultion + if (goodRegion && id.gr_size_y > 0) { + l = Arrays.asList((Double[]) Convert.toWrapperArray(Arrays.copyOfRange(gY, id.gr_pos_y, id.gr_pos_y + id.gr_size_y))); + minGauss = Collections.min(l); + rangeGauss = Collections.max(l) - minGauss; + } + + for (int i = 0; i < xp.length; i++) { + if (gY != null) { + xg[i] = (int) (((gY[i] - minGauss) / rangeGauss) * profileSize); + } + xp[i] = (int) (((pY[i] - minProfile) / rangeProfile) * profileSize); + } + + if (goodRegion && id.gr_size_y > 0) { + xg = Arrays.copyOfRange(xg, id.gr_pos_y, id.gr_pos_y + id.gr_size_y); + yg = Arrays.copyOfRange(yg, id.gr_pos_y, id.gr_pos_y + id.gr_size_y); + } + hgaussian = new Overlays.Polyline(penFit, xg, yg); + hprofile = new Overlays.Polyline(renderer.getPenProfile(), xp, yp); + } + } catch (Exception ex) { + System.err.println(ex.getMessage()); + return null; + } + } else { + ArrayProperties properties = data.getProperties(); + double maxPlot = properties.max; + double minPlot = properties.min; + double rangePlot = maxPlot - minPlot; + + if (rangePlot <= 0) { + return null; + } + if (renderer.getCalibration() != null) { + try { + double[] sum = data.integrateVertically(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] x_egu = renderer.getCalibration().getAxisX(sum.length); + double[] comRms = getComRms(sum, x_egu); + xCom = comRms[0]; + xRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + if (showFit) { + double[] gaussian = fitGaussian(saux, x); + if (gaussian != null) { + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + xNorm = gaussian[0]; + xMean = gaussian[1]; + xSigma = gaussian[2]; + double[] fit = getFitFunction(gaussian, x); + int[] y = new int[x.length]; + for (int i = 0; i < x.length; i++) { + y[i] = (int) (height - 1 - ((((fit[i] + min) / height - minPlot) / rangePlot) * profileSize)); + } + vgaussian = new Overlays.Polyline(penFit, x, y); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (height - 1 - (((sum[i] / height - minPlot) / rangePlot) * profileSize)); + } + vprofile = new Overlays.Polyline(renderer.getPenProfile(), x, p); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + try { + double[] sum = data.integrateHorizontally(true); + double[] saux = new double[sum.length]; + int[] p = new int[sum.length]; + double[] y_egu = renderer.getCalibration().getAxisY(sum.length); + double[] comRms = getComRms(sum, y_egu); + yCom = comRms[0]; + yRms = comRms[1]; + int[] x = Arr.indexesInt(sum.length); + DescriptiveStatistics stats = new DescriptiveStatistics(sum); + double min = stats.getMin(); + for (int i = 0; i < sum.length; i++) { + saux[i] = sum[i] - min; + } + + if (showFit) { + double[] gaussian = fitGaussian(saux, x); + if (gaussian != null) { + //Only aknowledge beam fully inside the image and peak over 3% of min + if ((gaussian[2] < sum.length * 0.45) + && (gaussian[2] > 2) + && (gaussian[0] > min * 0.03)) { + yNorm = gaussian[0]; + yMean = gaussian[1]; + ySigma = gaussian[2]; + double[] fit = getFitFunction(gaussian, x); + + int[] y = new int[x.length]; + for (int i = 0; i < x.length; i++) { + y[i] = (int) ((((fit[i] + min) / width - minPlot) / rangePlot) * profileSize); + } + hgaussian = new Overlays.Polyline(penFit, y, x); + } + } + } + if (showProfile) { + for (int i = 0; i < x.length; i++) { + p[i] = (int) (((sum[i] / width - minPlot) / rangePlot) * profileSize); + } + hprofile = new Overlays.Polyline(renderer.getPenProfile(), p, x); + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + if (xSigma != null) { + xSigma *= renderer.getCalibration().getScaleX(); + } + if (ySigma != null) { + ySigma *= renderer.getCalibration().getScaleY(); + } + if (xMean != null) { + xMean = data.getX((int) Math.round(xMean)); + } + if (yMean != null) { + yMean = data.getY((int) Math.round(yMean)); + } + } + } + final String units = (renderer.getCalibration() != null) ? "\u00B5m" : "px"; + final String fmt = "%7.1f" + units; + Overlays.Text textCom = null; + Overlay[] pOv = null, fOv = null; + Font fontInfoText = new Font(Font.MONOSPACED, 0, 14); + Point textPosition = new Point(12, 20); + if (showProfile) { + if ((xCom != null) && (yCom != null)) { + String text = String.format("com x: m=" + fmt + " \u03C3=" + fmt + "\ncom y: m=" + fmt + " \u03C3=" + fmt, xCom, xRms, yCom, yRms); + textCom = new Overlays.Text(renderer.getPenProfile(), text, fontInfoText, textPosition); + textCom.setFixed(true); + textCom.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + } + pOv = new Overlay[]{hprofile, vprofile, textCom}; + textPosition = new Point(textPosition.x, textPosition.y + 34); + } + if (showFit) { + Overlays.Crosshairs cross = null; + Overlays.Text textFit = null; + if ((xMean != null) && (yMean != null)) { + String text = String.format("fit x: m=" + fmt + " \u03C3=" + fmt + "\nfit y: m=" + fmt + " \u03C3=" + fmt, xMean, xSigma, yMean, ySigma); + textFit = new Overlays.Text(penFit, text, fontInfoText, textPosition); + textFit.setFixed(true); + textFit.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + Point center = new Point(xMean.intValue(), yMean.intValue()); + if (renderer.getCalibration() != null) { + center = renderer.getCalibration().convertToImagePosition(new PointDouble(xMean, yMean)); + xSigma /= renderer.getCalibration().getScaleX(); + ySigma /= renderer.getCalibration().getScaleY(); + } + cross = new Overlays.Crosshairs(penCross, center, new Dimension(Math.abs(2 * xSigma.intValue()), 2 * Math.abs(ySigma.intValue()))); + } + textPosition = new Point(textPosition.x, textPosition.y + 34); + fOv = new Overlay[]{hgaussian, vgaussian, cross, textFit}; + + if (goodRegion && (id != null)) { + try { + double[] x = id.gr_x_axis; + double[] y = id.gr_y_axis; + Overlays.Rect goodRegionOv = new Overlays.Rect(new Pen(penFit.getColor(), 0, Pen.LineStyle.dotted)); + goodRegionOv.setCalibration(renderer.getCalibration()); + goodRegionOv.setPosition(new Point(id.gr_pos_x, id.gr_pos_y)); + goodRegionOv.setSize(new Dimension(id.gr_x_axis.length, id.gr_y_axis.length)); + fOv = Arr.append(fOv, goodRegionOv); + + if (slicing) { + if (sliceCenters != null) { + for (PointDouble sliceCenter : sliceCenters) { + Overlays.Crosshairs center = new Overlays.Crosshairs(penSlices); + center.setCalibration(renderer.getCalibration()); + center.setAbsolutePosition(sliceCenter); + center.setSize(new Dimension(10, 10)); + fOv = Arr.append(fOv, center); + } + if (sliceCenters.length > 1) { + double[] fit = fitPolynomial(sliceCenters, 1); + double angle = Math.toDegrees(Math.atan(fit[1])); + Overlays.Text text = new Overlays.Text(penSlices, String.format("slice: \u03B8= %5.1fdeg", angle), fontInfoText, textPosition); + text.setFixed(true); + text.setAnchor(Overlay.ANCHOR_VIEWPORT_TOP_LEFT); + fOv = Arr.append(fOv, text); + } + } + } + } catch (Exception ex) { + } + } + + } + return new Overlay[][]{pOv, fOv}; + } + return null; + } + + class UserOverlay { + + String name; + Overlay obj; + String[] channels; + } + ArrayList userOverlayConfig; + + void parseUserOverlays() { + Properties userOverlays = new Properties(); + userOverlayConfig = new ArrayList<>(); + if (userOverlaysConfigFile != null) { + try { + try (FileInputStream in = new FileInputStream(getContext().getSetup().expandPath(userOverlaysConfigFile))) { + userOverlays.load(in); + + for (String name : userOverlays.stringPropertyNames()) { + String val = userOverlays.getProperty(name); + try { + UserOverlay uo = new UserOverlay(); + uo.name = name; + String type = val.substring(0, val.indexOf("(")).trim(); + String pars = val.substring(val.indexOf("(") + 1, val.lastIndexOf(")")).trim(); + String[] tokens = pars.split(","); + for (int i = 0; i < tokens.length; i++) { + tokens[i] = tokens[i].trim(); + } + Color color = Color.GRAY; + try { + color = (Color) Color.class.getField(tokens[tokens.length - 1].toUpperCase()).get(null); + } catch (Exception ex) { + } + Pen pen = new Pen(color); + try { + String[] penTokens = tokens[tokens.length - 1].split(":"); + color = (Color) Color.class.getField(penTokens[0].toUpperCase()).get(null); + int width = Integer.valueOf(penTokens[1]); + Pen.LineStyle style = Pen.LineStyle.valueOf(penTokens[2]); + pen = new Pen(color, width, style); + } catch (Exception ex) { + } + switch (type) { + case "Point": + uo.obj = new Overlays.Crosshairs(); + uo.obj.setSize(new Dimension(Integer.valueOf(tokens[2]), Integer.valueOf(tokens[3]))); + break; + case "Line": + uo.obj = new Overlays.Line(); + break; + case "Arrow": + uo.obj = new Overlays.Arrow(); + break; + case "Rect": + uo.obj = new Overlays.Rect(); + break; + case "Ellipse": + uo.obj = new Overlays.Ellipse(); + break; + case "Polyline": + uo.obj = new Overlays.Polyline(); + break; + } + if (type.equals("Polyline") || type.equals("Point")) { + uo.channels = new String[]{tokens[0], tokens[1]}; + } else { + uo.channels = new String[]{tokens[0], tokens[1], tokens[2], tokens[3]}; + } + uo.obj.setPen(pen); + userOverlayConfig.add(uo); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + Overlay[] getUserOverlays(Data data) { + ArrayList ret = new ArrayList<>(); + if (server != null) { + ImageData id = getFrame(data); + for (UserOverlay uo : userOverlayConfig) { + try { + Overlay ov = uo.obj; + //Overlay ov = (Overlay)uo.cls.newInstance(); + ov.setCalibration(renderer.getCalibration()); + boolean valid = false; + if (ov instanceof Overlays.Polyline) { + double[] x = (uo.channels[0].equals("null")) ? null : id.getDoubleArray(uo.channels[0]); + double[] y = (uo.channels[1].equals("null")) ? null : id.getDoubleArray(uo.channels[1]); + if ((x != null) || (y != null)) { + if (x == null) { + x = (renderer.getCalibration() == null) ? Arr.indexesDouble(y.length) : renderer.getCalibration().getAxisX(y.length); + } + if (y == null) { + y = (renderer.getCalibration() == null) ? Arr.indexesDouble(x.length) : renderer.getCalibration().getAxisY(x.length); + } + ((Overlays.Polyline) ov).updateAbsolute(x, y); + valid = true; + } + } else { + Double x = id.getDouble(uo.channels[0]); + Double y = id.getDouble(uo.channels[1]); + if ((x != null) && (y != null)) { + PointDouble position = new PointDouble(x, y); + ov.setAbsolutePosition(position); + if (!(ov instanceof Overlays.Crosshairs)) { + Double x2 = id.getDouble(uo.channels[2]); + Double y2 = id.getDouble(uo.channels[3]); + if ((x != null) && (y != null)) { + DimensionDouble size = new DimensionDouble(x2 - position.x, y2 - position.y); + ov.setAbsoluteSize(size); + valid = true; + } + } else { + valid = true; + } + } + } + if (valid) { + ret.add(ov); + } + } catch (Exception ex) { + //ex.printStackTrace(); + } + } + } + return ret.toArray(new Overlay[0]); + } + + double[] getComRms(double[] arr, double[] x) { + if (arr != null) { + double xmd = 0; + double xmd2 = 0; + double total = 0; + for (int i = 0; i < arr.length; i++) { + double v = (arr[i] * x[i]); + xmd += v; + xmd2 += (v * x[i]); + total += arr[i]; + } + if (total > 0) { + double com = xmd / total; + double com2 = xmd2 / total; + double rms = Math.sqrt(Math.abs(com2 - com * com)); + return new double[]{com, rms}; + } + } + return new double[]{Double.NaN, Double.NaN}; + } + + double[] fitGaussianScript(int[] y, int[] x) { + ScriptManager sm = Context.getInstance().getScriptManager(); + ArrayProperties pY = ArrayProperties.get(y); + sm.setVar("y", y); + sm.setVar("x", x); + InterpreterResult r = sm.eval("r = fit_gaussians(y, x, [" + pY.maxIndex + ",])"); + if (r.exception != null) { + r.exception.printStackTrace(); + } else { + List ret = (List) sm.getVar("r"); + if ((ret != null) && (ret.size() == 1) && (ret.get(0) instanceof List) && (((List) (ret.get(0))).size() == 3)) { + double norm = (Double) ((List) ret.get(0)).get(0); + double mean = (Double) ((List) ret.get(0)).get(1); + double sigma = (Double) ((List) ret.get(0)).get(2); + return new double[]{norm, mean, sigma}; + } + } + return null; + } + + double[] fitGaussian(double[] y, int[] x) { + try { + ArrayProperties pY = ArrayProperties.get(y); + GaussianCurveFitter fitter = GaussianCurveFitter.create().withStartPoint(new double[]{(pY.max - pY.min) / 2, x[pY.maxIndex], 1.0}).withMaxIterations(1000); + ArrayList values = new ArrayList<>(); + for (int i = 0; i < y.length; i++) { + values.add(new WeightedObservedPoint(1.0, x[i], y[i])); + } + return fitter.fit(values); + } catch (Exception ex) { + return null; + } + + } + + double[] fitPolynomial(PointDouble[] points, int order) { + double[] y = new double[points.length]; + double[] x = new double[points.length]; + for (int i = 0; i < points.length; i++) { + x[i] = points[i].x; + y[i] = points[i].y; + } + return fitPolynomial(y, x, order); + } + + double[] fitPolynomial(double[] y, double[] x, int order) { + try { + ArrayProperties pY = ArrayProperties.get(y); + PolynomialCurveFitter fitter = PolynomialCurveFitter.create(order).withMaxIterations(1000); + ArrayList values = new ArrayList<>(); + for (int i = 0; i < y.length; i++) { + values.add(new WeightedObservedPoint(1.0, x[i], y[i])); + } + return fitter.fit(values); + } catch (Exception ex) { + return null; + } + + } + + double[] getFitFunction(double[] pars, int[] x) { + double[] fit = new double[x.length]; + Gaussian g = new Gaussian(pars[0], pars[1], pars[2]); + for (int i = 0; i < x.length; i++) { + fit[i] = g.value(x[i]); + } + return fit; + } + + void setHistogramVisible(boolean value) { + if (value) { + if ((histogramDialog == null) || (!histogramDialog.isShowing())) { + Histogram histogram = new Histogram(true); + histogram.setRenderer(renderer); + histogramDialog = SwingUtils.showDialog(SwingUtils.getWindow(renderer), "Histogram", null, histogram); + renderer.refresh(); + } + } else { + if (histogramDialog != null) { + histogramDialog.setVisible(false); + histogramDialog = null; + } + } + } + + void setLaserState(int bunch, boolean value) throws Exception { + System.out.println("Setting laser state: " + value + " - bunch" + bunch); + //Epics.putq("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", value ? 0 : 1); + if ((bunch<=0) || (bunch==1)){ + Epics.putq("SIN-TIMAST-TMA:Bunch-1-OnDelay-Sel", value ? 0 : 1); + } + if ((bunch<=0) || (bunch==2)){ + Epics.putq("SIN-TIMAST-TMA:Bunch-2-OnDelay-Sel", value ? 0 : 1); + } + + Epics.putq("SIN-TIMAST-TMA:Beam-Apply-Cmd.PROC", 1); + Thread.sleep(3000); + } + + boolean getLaserState(int bunch) throws Exception { + //return (Epics.get("SIN-TIMAST-TMA:Beam-Las-Delay-Sel", Integer.class) == 0); + if (bunch<=0){ + return getLaserState(1) && getLaserState(2); + } + if (bunch==2){ + return (Epics.get("SWISSFEL-STATUS:Bunch-2-OnDelay-Sel", Integer.class) == 0); + } + return (Epics.get("SWISSFEL-STATUS:Bunch-1-OnDelay-Sel", Integer.class) == 0); + } + + void elog(String logbook, String title, String message, String[] attachments) throws Exception { + String domain = ""; + String category = "Info"; + String entry = ""; + StringBuffer cmd = new StringBuffer(); + + cmd.append("G_CS_ELOG_add -l \"").append(logbook).append("\" "); + cmd.append("-a \"Author=ScreenPanel\" "); + cmd.append("-a \"Type=pshell\" "); + cmd.append("-a \"Entry=").append(entry).append("\" "); + cmd.append("-a \"Title=").append(title).append("\" "); + cmd.append("-a \"Category=").append(category).append("\" "); + cmd.append("-a \"Domain=").append(domain).append("\" "); + for (String attachment : attachments) { + cmd.append("-f \"").append(attachment).append("\" "); + } + cmd.append("-n 1 "); + cmd.append("\"").append(message).append("\" "); + System.out.println(cmd.toString()); + + final Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", cmd.toString()}); + new Thread(() -> { + try { + process.waitFor(); + int bytes = process.getInputStream().available(); + byte[] arr = new byte[bytes]; + process.getInputStream().read(arr, 0, bytes); + System.out.println(new String(arr)); + bytes = process.getErrorStream().available(); + arr = new byte[bytes]; + process.getErrorStream().read(arr, 0, bytes); + System.err.println(new String(arr)); + } catch (Exception ex) { + System.err.println(ex); + } + }).start(); + } + + void centralizeRenderer() { + Point center = null; + Dimension size = renderer.getImageSize(); + double zoom = (renderer.getMode() == RendererMode.Fixed) ? 1.0 : renderer.getZoom(); + if (renderer.getCalibration() != null) { + center = renderer.getCalibration().getCenter(); + } else if (size != null) { + center = new Point(size.width / 2, size.height / 2); + } + if (center != null) { + Point topleft = new Point(Math.max((int) (center.x - renderer.getWidth() / 2 / zoom), 0), + Math.max((int) (center.y - renderer.getHeight() / 2 / zoom), 0)); + renderer.setViewPosition(topleft); + } + } + + void updatePause() { + int index = ((int) pauseSelection.getValue()) - 1; + synchronized (imageBuffer) { + if (index < imageBuffer.size()) { + Data data = imageBuffer.get(index).data; + long pid = imageBuffer.get(index).cache.getPulseId(); + BufferedImage image = camera.generateImage(data); + renderer.setImage(renderer.getOrigin(), image, data); + + String text = "PID: " + pid; + if (imagePauseOverlay == null) { + Font font = new Font("Verdana", Font.PLAIN, 12); + Dimension d = SwingUtils.getTextSize(text, renderer.getFontMetrics(font)); + imagePauseOverlay = new Text(renderer.getPenErrorText(), "", font, new Point(-20 - d.width, 42)); + imagePauseOverlay.setFixed(true); + imagePauseOverlay.setAnchor(Overlay.ANCHOR_VIEWPORT_OR_IMAGE_TOP_RIGHT); + renderer.addOverlay(imagePauseOverlay); + } + //imagePauseOverlay.update(Chrono.getTimeStr(data.getTimestamp(), "HH:mm:ss.SSS")); + imagePauseOverlay.update(text); + manageFit(image, data); + manageUserOverlays(image, data); + } + } + updateStreamData(); + } + + void removePauseOverlay() { + renderer.removeOverlay(imagePauseOverlay); + imagePauseOverlay = null; + } + + void saveSnapshot() throws Exception { + boolean paused = isPaused(); + try{ + if (!paused){ + setPaused(true); + } + String snapshotFile = null; + synchronized (imageBuffer) { + Frame frame = getCurrentFrame(); + if (frame == null) { + throw new Exception("No current image"); + } + ArrayList frames = new ArrayList<>(); + frames.add(frame); + this.saveFrames(cameraName + "_camera_snapshot", frames); + + //Enforce the same timestamp to data & image files. + snapshotFile = getContext().getExecutionPars().getPath() + ".png"; + //renderer.saveSnapshot(snapshotFile, "png", true); + ImageBuffer.saveImage(SwingUtils.createImage(renderer), snapshotFile, "png"); + } + + JPanel panel = new JPanel(); + GridBagLayout layout = new GridBagLayout(); + layout.columnWidths = new int[]{0, 180}; //Minimum width + layout.rowHeights = new int[]{30, 30, 30}; //Minimum height + panel.setLayout(layout); + JComboBox comboLogbook = new JComboBox(new String[]{"SwissFEL commissioning data", "SwissFEL commissioning"}); + JTextField textComment = new JTextField(); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Data file:"), c); + c.gridy = 1; + panel.add(new JLabel("Logbook:"), c); + c.gridy = 2; + panel.add(new JLabel("Comment:"), c); + c.fill = GridBagConstraints.HORIZONTAL; + c.gridx = 1; + panel.add(textComment, c); + c.gridy = 1; + panel.add(comboLogbook, c); + c.gridy = 0; + panel.add(new JLabel(getContext().getExecutionPars().getPath()), c); + + if (SwingUtils.showOption(getTopLevel(), "Success", panel, OptionType.OkCancel) == OptionResult.Yes) { + StringBuilder message = new StringBuilder(); + message.append("Camera: ").append(cameraName).append(" ("). + append((server != null) ? "server" : "direct").append(")").append("\n"); + message.append("Screen: ").append(String.valueOf(valueScreen.getLabel().getText())).append("\n"); + message.append("Filter: ").append(String.valueOf(valueFilter.getLabel().getText())).append("\n"); + message.append("Data file: ").append(getContext().getExecutionPars().getPath()).append("\n"); + message.append("Comment: ").append(textComment.getText()).append("\n"); + //Add slicing message + if ((fitOv != null) && (fitOv.length > 5) && (fitOv[fitOv.length - 1] instanceof Overlays.Text)) { + Overlays.Text text = (Overlays.Text) fitOv[fitOv.length - 1]; + message.append(text.getText()).append("\n"); + } + elog((String) comboLogbook.getSelectedItem(), "ScreenPanel Snapshot", message.toString(), new String[]{snapshotFile}); + } + } finally{ + if (!paused){ + setPaused(false); + } + } + } + + void saveStack() throws Exception { + synchronized (imageBuffer) { + saveFrames(cameraName + "_camera_stack", imageBuffer); + } + SwingUtils.showMessage(getTopLevel(), "Success", "Generated data file:\n" + getContext().getExecutionPars().getPath()); + } + + public static String getCameraType(String name) { + if (name == null) { + return ""; + } + for (String s : new String[]{"LCAM"}) { + if (name.contains(s)) { + return LASER_TYPE; + } + } + for (String s : new String[]{"DSCR", "DSRM", "DLAC"}) { + if (name.contains(s)) { + return ELECTRONS_TYPE; + } + } + for (String s : new String[]{"PROF", "PPRM", "PSSS", "PSCR", "PSRD"}) { + if (name.contains(s)) { + return PHOTONICS_TYPE; + } + } + return "Unknown"; + } + + public Map getProcessingParameters(StreamValue value) throws IOException { + return (Map) JsonSerializer.decode(value.getValue("processing_parameters").toString(), Map.class); + } + + void saveFrames(String name, ArrayList frames) throws IOException { + ArrayList values = new ArrayList<>(); + for (Frame frame : frames) { + values.add(frame.cache); + } + saveImages(name, values); + } + + void saveImages(String name, ArrayList images) throws IOException { + int depth = images.size(); + if (depth == 0) { + return; + } + StreamValue first = images.get(0); + String pathRoot = "/camera1/"; + String pathImage = pathRoot + "image"; + String pathPid = pathRoot + "pulse_id"; + String pathTimestampStr = pathRoot + "timestamp_str"; + Map processingPars = getProcessingParameters(first); + String camera = (String) processingPars.get("camera_name"); + String type = getCameraType(camera); + + int width = ((Number) first.getValue("width")).intValue(); + int height = ((Number) first.getValue("height")).intValue(); + Class dataType = first.getValue("image").getClass().getComponentType(); + + getContext().setExecutionPars(name); + DataManager dm = getContext().getDataManager(); + + //Create tables + dm.createDataset(pathImage, dataType, new int[]{depth, height, width}); + dm.createDataset(pathPid, Long.class, new int[]{depth}); + dm.createDataset(pathTimestampStr, String.class, new int[]{depth}); + for (String id : first.getIdentifiers()) { + Object val = first.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + Map pars = getProcessingParameters(first); + for (String key : pars.keySet()) { + if ((pars.get(key) != null) && (pars.get(key) instanceof Map)) { + for (Object k : ((Map) pars.get(key)).keySet()) { + Object v = ((Map) pars.get(key)).get(k); + dm.setAttribute(pathImage, key + " " + k, (v == null) ? "" : v); + } + } else { + Object value = pars.get(key); + if (value == null) { + value = ""; + } else if (value instanceof List) { + Class cls = (((List) value).size() > 0) ? ((List) value).get(0).getClass() : double.class; + value = Convert.toPrimitiveArray(value, cls); + //value = Convert.toDouble(value); + } + dm.setAttribute(pathImage, key, value); + } + } + } else if (val.getClass().isArray()) { + dm.createDataset(pathRoot + id, Double.class, new int[]{depth, Array.getLength(val)}); + } else { + dm.createDataset(pathRoot + id, val.getClass(), new int[]{depth}); + } + } + + //Add metadata + dm.setAttribute(pathRoot, "Camera", camera); + dm.setAttribute(pathRoot, "Images", depth); + dm.setAttribute(pathRoot, "Interval", -1); + dm.setAttribute(pathRoot, "Type", type); + if (type.equals(ELECTRONS_TYPE)) { + dm.setAttribute(pathRoot, "Screen", String.valueOf(valueScreen.getLabel().getText())); + dm.setAttribute(pathRoot, "Filter", String.valueOf(valueFilter.getLabel().getText())); + } + + //Save data + for (int index = 0; index < depth; index++) { + StreamValue streamValue = images.get(index); + dm.setItem(pathImage, streamValue.getValue("image"), new long[]{index, 0, 0}, new int[]{1, height, width}); + dm.setItem(pathPid, streamValue.getPulseId(), index); + dm.setItem(pathTimestampStr, Chrono.getTimeStr(streamValue.getTimestamp(), "YYYY-MM-dd HH:mm:ss.SSS"), index); + + for (String id : streamValue.getIdentifiers()) { + Object val = streamValue.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + } else if (val.getClass().isArray()) { + dm.setItem(pathRoot + id, val, index); + } else { + dm.setItem(pathRoot + id, val, index); + } + } + } + getContext().getDataManager().closeOutput(); + } + + StandardDialog calibrationDialolg; + + void calibrate() throws Exception { + if (server != null) { + server.resetRoi(); + calibrationDialolg = (StandardDialog) getContext().getClassByName("CameraCalibrationDialog").getConstructors()[0].newInstance(new Object[]{getTopLevel(), server.getCurrentCamera(), renderer}); + SwingUtils.centerComponent(getTopLevel(), calibrationDialolg); + calibrationDialolg.setVisible(true); + calibrationDialolg.setListener(new StandardDialogListener() { + @Override + public void onWindowOpened(StandardDialog dlg) { + } + + @Override + public void onWindowClosed(StandardDialog dlg, boolean accepted) { + if (accepted) { + //comboCamerasActionPerformed(null); + } + } + }); + } + } + + StandardDialog dataTableDialog; + DefaultTableModel dataTableModel; + JTable dataTable; + + void showStreamData() { + dataTableModel = null; + if (server != null) { + + if ((dataTableDialog != null) && (dataTableDialog.isShowing())) { + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + dataTableDialog.requestFocus(); + return; + } + dataTableModel = new DefaultTableModel(new Object[0][2], new String[]{"Name", "Value"}) { + public Class getColumnClass(int columnIndex) { + return String.class; + } + + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + }; + updateStreamData(); + StreamValue val = server.getStream().take(); + dataTable = new JTable(dataTableModel); + dataTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + dataTable.setCellSelectionEnabled(true); + dataTable.getTableHeader().setReorderingAllowed(false); + dataTable.getTableHeader().setResizingAllowed(true); + dataTableDialog = new StandardDialog(getTopLevel(), "Image Data", false); + dataTableDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setViewportView(dataTable); + scrollPane.setPreferredSize(new Dimension(300, 400)); + dataTableDialog.setContentPane(scrollPane); + dataTableDialog.pack(); + dataTableDialog.setVisible(true); + dataTableDialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + dataTableModel = null; + } + }); + dataTable.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + try { + int row = dataTable.getSelectedRow(); + int col = dataTable.getSelectedColumn(); + dataTable.setToolTipText(null); + if (row > 1) { + String id = String.valueOf(dataTable.getModel().getValueAt(row, 0)); + String locator = String.valueOf(dataTable.getModel().getValueAt(0, 1)); + String channelId = locator + " " + id; + dataTable.setToolTipText(channelId); + if ((e.getClickCount() == 2) && (!e.isPopupTrigger())) { + if (col == 0) { + SwingUtils.showMessage(dataTableDialog, "Channel Identifier", "Copied to clipboard: " + channelId); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(new StringSelection(channelId), (Clipboard clipboard1, Transferable contents) -> { + }); + } else { + Object obj = getCurrentFrame().cache.getValue(id); + if (id.equals("image")) { + } else if (id.equals("processing_parameters")) { + Map pars = getProcessingParameters(getCurrentFrame().cache); + StringBuilder sb = new StringBuilder(); + for (String key : pars.keySet()) { + sb.append(key).append(" = ").append(Str.toString(pars.get(key), 10)).append("\n"); + } + SwingUtils.showMessage(dataTableDialog, "Processing Parameters", sb.toString()); + } else if ((obj != null) && (obj.getClass().isArray() || (obj instanceof Number))) { + DeviceValueChart chart = new DeviceValueChart(); + Device dev = null; + if (obj.getClass().isArray()) { + dev = new ReadableRegisterArray(new ReadableArray() { + @Override + public Object read() throws IOException, InterruptedException { + return Convert.toDouble(getCurrentFrame().cache.getValue(id)); + } + + @Override + public int getSize() { + return Array.getLength(getCurrentFrame().cache.getValue(id)); + } + }); + } else { + dev = new ReadableRegisterNumber(new ReadableNumber() { + @Override + public Object read() throws IOException, InterruptedException { + return Convert.toDouble(getCurrentFrame().cache.getValue(id)); + } + }); + } + dev.setPolling(1000); + chart.setDevice(dev); + JDialog dlg = SwingUtils.showDialog(dataTableDialog, cameraName + " " + id, null, chart); + //TODO: + //PlotBase plot = chart.getPlot(); + //if (plot!=null){ + // plot.setPlotBackgroundColor(Color.BLACK); + //} + } + } + } + } + } catch (Exception ex) { + showException(ex); + } + } + }); + SwingUtils.centerComponent(getTopLevel(), dataTableDialog); + updateStreamData(); + } + } + + volatile boolean updatingStreamData = false; + + void updateStreamData() { + if ((dataTableDialog == null) || !dataTableDialog.isShowing() || updatingStreamData) { + return; + } + updatingStreamData = true; + SwingUtilities.invokeLater(() -> { + updatingStreamData = false; + if ((dataTableModel != null) && (server != null)) { + StreamValue value = server.getValue(); + Frame frame = getCurrentFrame(); + int[] sel_rows = (dataTable == null) ? null : dataTable.getSelectedRows(); + int[] sel_cols = (dataTable == null) ? null : dataTable.getSelectedColumns(); + List ids = (value == null) ? new ArrayList<>() : new ArrayList(value.getIdentifiers()); + if (ids.size() + 4 != dataTableModel.getRowCount()) { + dataTableModel.setNumRows(0); + try { + dataTableModel.addRow(new Object[]{"Locator", server.getUrl() + "/" + ((value == null) ? instanceName : server.getCurrentInstance())}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Locator", ex.getMessage()}); + } + try { + dataTableModel.addRow(new Object[]{"Stream", server.getStreamAddress()}); + } catch (Exception ex) { + dataTableModel.addRow(new Object[]{"Stream", ex.getMessage()}); + } + dataTableModel.addRow(new Object[]{"PID", ""}); + dataTableModel.addRow(new Object[]{"Timestamp", ""}); + Collections.sort(ids); + for (String id : ids) { + dataTableModel.addRow(new Object[]{id, ""}); + } + } + + if ((frame != null) && (frame.cache != null)) { + dataTableModel.setValueAt(frame.cache.getPulseId(), 2, 1); //PID + dataTableModel.setValueAt(frame.cache.getTimestamp(), 3, 1); //Timestamp + for (int i = 4; i < dataTableModel.getRowCount(); i++) { + String id = String.valueOf(dataTableModel.getValueAt(i, 0)); + //Object obj = server.getValue(id); + Object obj = frame.cache.getValue(id); + if (obj != null) { + if (obj.getClass().isArray()) { + obj = obj.getClass().getComponentType().getSimpleName() + "[" + Array.getLength(obj) + "]"; + } else if (obj instanceof Double) { + obj = Convert.roundDouble((Double) obj, 1); + } else if (obj instanceof Float) { + obj = Convert.roundDouble((Float) obj, 1); + } + } + dataTableModel.setValueAt(String.valueOf(obj), i, 1); + } + } + if ((sel_rows != null) && (sel_rows.length > 0)) { + //dataTable.setRowSelectionInterval((Integer)Arr.getMin(sel_rows), (Integer)Arr.getMax(sel_rows)); + dataTable.setRowSelectionInterval(sel_rows[0], sel_rows[sel_rows.length - 1]); + } + if ((sel_cols != null) && (sel_cols.length > 0)) { + //dataTable.setColumnSelectionInterval((Integer)Arr.getMin(sel_cols), (Integer)Arr.getMax(sel_cols)); + dataTable.setColumnSelectionInterval(sel_cols[0], sel_cols[sel_cols.length - 1]); + } + } + }); + } + + ImageIcon getIcon(String name) { + ImageIcon ret = null; + try { + //Path path = Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().getPath(),"resources", name + ".png"); + String dir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "resources/"; + if (new File(dir + name + ".png").exists()) { + ret = new javax.swing.ImageIcon(dir + name + ".png"); + } else { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/" + name + ".png")); + if (MainFrame.isDark()) { + try { + ret = new ImageIcon(ch.psi.pshell.ui.App.class.getResource("/ch/psi/pshell/ui/dark/" + name + ".png")); + } catch (Exception e) { + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return ret; + } + + String getIconName(JButton button) { + String ret = button.getIcon().toString(); + if (ret.indexOf(".") > 0) { + ret = ret.substring(0, ret.indexOf(".")); + } + return ret; + } + + void setPaused(boolean paused){ + removePauseOverlay(); + if (camera != null) { + synchronized (imageBuffer) { + if (paused) { + renderer.pause(); + panelCameraSelection.setVisible(false); + pauseSelection.setVisible(true); + if (imageBuffer.size() > 0) { + pauseSelection.setEnabled(true); + pauseSelection.setMaxValue(imageBuffer.size()); + pauseSelection.setValue(imageBuffer.size()); + updatePause(); + } else { + pauseSelection.setEnabled(false); + pauseSelection.setMaxValue(1); + pauseSelection.setValue(1); + } + } else { + imageBuffer.clear(); + renderer.resume(); + //renderer.clear(); + pauseSelection.setVisible(false); + panelCameraSelection.setVisible(true); + } + } + updateStreamData(); + } + } + + boolean isPaused(){ + return renderer.isPaused(); + } + + //////// + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + buttonGroup2 = new javax.swing.ButtonGroup(); + buttonGroup3 = new javax.swing.ButtonGroup(); + buttonGroup4 = new javax.swing.ButtonGroup(); + jProgressBar1 = new javax.swing.JProgressBar(); + sidePanel = new javax.swing.JPanel(); + jPanel3 = new javax.swing.JPanel(); + buttonZoomFit = new javax.swing.JRadioButton(); + buttonZoomStretch = new javax.swing.JRadioButton(); + buttonZoomNormal = new javax.swing.JRadioButton(); + buttonZoom025 = new javax.swing.JRadioButton(); + buttonZoom05 = new javax.swing.JRadioButton(); + buttonZoom2 = new javax.swing.JRadioButton(); + jPanel2 = new javax.swing.JPanel(); + checkHistogram = new javax.swing.JCheckBox(); + comboColormap = new javax.swing.JComboBox(); + jLabel3 = new javax.swing.JLabel(); + jLabel4 = new javax.swing.JLabel(); + buttonFullRange = new javax.swing.JRadioButton(); + buttonManual = new javax.swing.JRadioButton(); + buttonAutomatic = new javax.swing.JRadioButton(); + labelMin = new javax.swing.JLabel(); + spinnerMin = new javax.swing.JSpinner(); + spinnerMax = new javax.swing.JSpinner(); + labelMax = new javax.swing.JLabel(); + btFixColormapRange = new javax.swing.JButton(); + jPanel5 = new javax.swing.JPanel(); + buttonServer = new javax.swing.JRadioButton(); + buttonDirect = new javax.swing.JRadioButton(); + textState = new javax.swing.JTextField(); + filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767)); + panelScreen = new javax.swing.JPanel(); + valueScreen = new ch.psi.pshell.swing.DeviceValuePanel(); + comboScreen = new javax.swing.JComboBox(); + panelFilter = new javax.swing.JPanel(); + valueFilter = new ch.psi.pshell.swing.DeviceValuePanel(); + comboFilter = new javax.swing.JComboBox(); + panelScreen2 = new javax.swing.JPanel(); + checkThreshold = new javax.swing.JCheckBox(); + spinnerThreshold = new javax.swing.JSpinner(); + checkBackground = new javax.swing.JCheckBox(); + checkGoodRegion = new javax.swing.JCheckBox(); + spinnerGrScale = new javax.swing.JSpinner(); + spinnerGrThreshold = new javax.swing.JSpinner(); + labelGrThreshold = new javax.swing.JLabel(); + labelGrScale = new javax.swing.JLabel(); + panelSlicing = new javax.swing.JPanel(); + checkSlicing = new javax.swing.JCheckBox(); + labelSlScale = new javax.swing.JLabel(); + spinnerSlScale = new javax.swing.JSpinner(); + labelSlNumber = new javax.swing.JLabel(); + spinnerSlNumber = new javax.swing.JSpinner(); + labelSlOrientation = new javax.swing.JLabel(); + spinnerSlOrientation = new javax.swing.JSpinner(); + checkRotation = new javax.swing.JCheckBox(); + spinnerRotationAngle = new javax.swing.JSpinner(); + spinnerRotationOrder = new javax.swing.JSpinner(); + labelOrder = new javax.swing.JLabel(); + labelMode = new javax.swing.JLabel(); + spinnerRotationMode = new javax.swing.JSpinner(); + labelAngle = new javax.swing.JLabel(); + labelConstant = new javax.swing.JLabel(); + spinnerRotationConstant = new javax.swing.JSpinner(); + checkAveraging = new javax.swing.JCheckBox(); + spinnerAvFrames = new javax.swing.JSpinner(); + labelAvFrames = new javax.swing.JLabel(); + labelAvMode = new javax.swing.JLabel(); + spinnerAvMode = new javax.swing.JSpinner(); + topPanel = new javax.swing.JPanel(); + toolBar = new javax.swing.JToolBar(); + buttonSidePanel = new javax.swing.JToggleButton(); + buttonStreamData = new javax.swing.JButton(); + buttonSave = new javax.swing.JToggleButton(); + buttonGrabBackground = new javax.swing.JButton(); + buttonPause = new javax.swing.JToggleButton(); + jSeparator6 = new javax.swing.JToolBar.Separator(); + buttonMarker = new javax.swing.JToggleButton(); + buttonProfile = new javax.swing.JToggleButton(); + buttonFit = new javax.swing.JToggleButton(); + buttonReticle = new javax.swing.JToggleButton(); + buttonScale = new javax.swing.JToggleButton(); + buttonTitle = new javax.swing.JToggleButton(); + pauseSelection = new ch.psi.pshell.swing.ValueSelection(); + panelCameraSelection = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + comboCameras = new javax.swing.JComboBox(); + jLabel5 = new javax.swing.JLabel(); + comboType = new javax.swing.JComboBox(); + renderer = new ch.psi.pshell.imaging.Renderer(); + + setPreferredSize(new java.awt.Dimension(873, 600)); + + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Zoom")); + + buttonGroup1.add(buttonZoomFit); + buttonZoomFit.setText("Fit"); + buttonZoomFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomFitActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomStretch); + buttonZoomStretch.setText("Stretch"); + buttonZoomStretch.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomStretchActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoomNormal); + buttonZoomNormal.setText("Normal"); + buttonZoomNormal.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoomNormalActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom025); + buttonZoom025.setText("1/4"); + buttonZoom025.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom025ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom05); + buttonZoom05.setText("1/2"); + buttonZoom05.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom05ActionPerformed(evt); + } + }); + + buttonGroup1.add(buttonZoom2); + buttonZoom2.setText("2"); + buttonZoom2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonZoom2ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); + jPanel3.setLayout(jPanel3Layout); + jPanel3Layout.setHorizontalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoomFit) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoomStretch)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonZoom025) + .addComponent(buttonZoom05) + .addComponent(buttonZoom2)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + jPanel3Layout.setVerticalGroup( + jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel3Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomNormal) + .addComponent(buttonZoom025)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomFit) + .addComponent(buttonZoom05)) + .addGap(0, 0, 0) + .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonZoomStretch) + .addComponent(buttonZoom2)) + .addContainerGap()) + ); + + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Colormap")); + + checkHistogram.setText("Histogram"); + checkHistogram.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkHistogramActionPerformed(evt); + } + }); + + comboColormap.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel3.setText("Type:"); + + jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + jLabel4.setText("Range:"); + + buttonGroup3.add(buttonFullRange); + buttonFullRange.setText("Full"); + buttonFullRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonManual); + buttonManual.setText("Manual"); + buttonManual.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + buttonGroup3.add(buttonAutomatic); + buttonAutomatic.setText("Automatic"); + buttonAutomatic.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + onChangeColormap(evt); + } + }); + + labelMin.setText("Min:"); + + spinnerMin.setModel(new javax.swing.SpinnerNumberModel(0, 0, 65535, 1)); + spinnerMin.setEnabled(false); + spinnerMin.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMin.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + spinnerMax.setModel(new javax.swing.SpinnerNumberModel(255, 0, 65535, 1)); + spinnerMax.setEnabled(false); + spinnerMax.setPreferredSize(new java.awt.Dimension(77, 20)); + spinnerMax.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + onChangeColormapRange(evt); + } + }); + + labelMax.setText("Max:"); + + btFixColormapRange.setText("Fix"); + btFixColormapRange.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + btFixColormapRangeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel3) + .addComponent(jLabel4)) + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(buttonAutomatic) + .addComponent(buttonFullRange) + .addComponent(buttonManual) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMax) + .addGap(2, 2, 2) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(checkHistogram, javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addComponent(labelMin) + .addGap(2, 2, 2) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(spinnerMin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) + .addContainerGap()) + ); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btFixColormapRange, spinnerMax, spinnerMin}); + + jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel4}); + + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(comboColormap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel3) + .addComponent(checkHistogram)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonAutomatic) + .addComponent(jLabel4) + .addComponent(btFixColormapRange, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(labelMin) + .addComponent(spinnerMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(buttonFullRange)) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(buttonManual) + .addComponent(labelMax) + .addComponent(spinnerMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Source")); + + buttonGroup4.add(buttonServer); + buttonServer.setSelected(true); + buttonServer.setText("Server"); + buttonServer.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonServerActionPerformed(evt); + } + }); + + buttonGroup4.add(buttonDirect); + buttonDirect.setText("Direct"); + buttonDirect.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonDirectActionPerformed(evt); + } + }); + + textState.setEditable(false); + textState.setHorizontalAlignment(javax.swing.JTextField.CENTER); + textState.setDisabledTextColor(new java.awt.Color(0, 0, 0)); + textState.setEnabled(false); + + javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); + jPanel5.setLayout(jPanel5Layout); + jPanel5Layout.setHorizontalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addContainerGap() + .addComponent(buttonServer) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonDirect) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(56, 56, 56)) + ); + jPanel5Layout.setVerticalGroup( + jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addGap(4, 4, 4) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel5Layout.createSequentialGroup() + .addComponent(textState, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(buttonServer) + .addComponent(buttonDirect))) + .addContainerGap()) + ); + + panelScreen.setBorder(javax.swing.BorderFactory.createTitledBorder("Screen")); + + comboScreen.setEnabled(false); + comboScreen.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboScreenActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelScreenLayout = new javax.swing.GroupLayout(panelScreen); + panelScreen.setLayout(panelScreenLayout); + panelScreenLayout.setHorizontalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboScreen, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelScreenLayout.setVerticalGroup( + panelScreenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreenLayout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + panelFilter.setBorder(javax.swing.BorderFactory.createTitledBorder("Filter")); + + comboFilter.setEnabled(false); + comboFilter.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboFilterActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelFilterLayout = new javax.swing.GroupLayout(panelFilter); + panelFilter.setLayout(panelFilterLayout); + panelFilterLayout.setHorizontalGroup( + panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelFilterLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(valueFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(comboFilter, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + panelFilterLayout.setVerticalGroup( + panelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelFilterLayout.createSequentialGroup() + .addGap(4, 4, 4) + .addComponent(comboFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(valueFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + panelScreen2.setBorder(javax.swing.BorderFactory.createTitledBorder("Pipeline")); + + checkThreshold.setText("Threshold"); + checkThreshold.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkThresholdActionPerformed(evt); + } + }); + + spinnerThreshold.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 99999.0d, 1.0d)); + spinnerThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerThresholdonChange(evt); + } + }); + + checkBackground.setText("Subtract Background"); + checkBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkBackgroundActionPerformed(evt); + } + }); + + checkGoodRegion.setText("Good Region"); + checkGoodRegion.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkGoodRegionActionPerformed(evt); + } + }); + + spinnerGrScale.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.01d, 99999.0d, 1.0d)); + spinnerGrScale.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + spinnerGrThreshold.setModel(new javax.swing.SpinnerNumberModel(0.5d, 0.04d, 1.0d, 0.1d)); + spinnerGrThreshold.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerGrThreshold.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerGrThresholdonChange(evt); + } + }); + + labelGrThreshold.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelGrThreshold.setText("Threshold:"); + + labelGrScale.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelGrScale.setText("Scale:"); + + checkSlicing.setText("Slicing"); + checkSlicing.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkSlicingActionPerformed(evt); + } + }); + + labelSlScale.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelSlScale.setText("Scale:"); + + spinnerSlScale.setModel(new javax.swing.SpinnerNumberModel(3.0d, 0.01d, 99999.0d, 1.0d)); + spinnerSlScale.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + labelSlNumber.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelSlNumber.setText("Slices:"); + + spinnerSlNumber.setModel(new javax.swing.SpinnerNumberModel(2, 0, 1000, 1)); + spinnerSlNumber.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerSlNumber.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + labelSlOrientation.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelSlOrientation.setText("Orientation:"); + + spinnerSlOrientation.setModel(new javax.swing.SpinnerListModel(new String[] {"vertical", "horizontal"})); + spinnerSlOrientation.setPreferredSize(new java.awt.Dimension(92, 20)); + spinnerSlOrientation.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerSlicingChange(evt); + } + }); + + javax.swing.GroupLayout panelSlicingLayout = new javax.swing.GroupLayout(panelSlicing); + panelSlicing.setLayout(panelSlicingLayout); + panelSlicingLayout.setHorizontalGroup( + panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addContainerGap() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addComponent(checkSlicing) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addComponent(labelSlNumber) + .addGap(2, 2, 2) + .addComponent(spinnerSlNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addComponent(labelSlScale) + .addGap(2, 2, 2) + .addComponent(spinnerSlScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSlicingLayout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(labelSlOrientation) + .addGap(2, 2, 2) + .addComponent(spinnerSlOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + panelSlicingLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerSlNumber, spinnerSlOrientation, spinnerSlScale}); + + panelSlicingLayout.setVerticalGroup( + panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(checkSlicing) + .addGroup(panelSlicingLayout.createSequentialGroup() + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlNumber)) + .addGap(0, 0, 0) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlScale)))) + .addGap(0, 0, 0) + .addGroup(panelSlicingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerSlOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelSlOrientation))) + ); + + panelSlicingLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {spinnerSlNumber, spinnerSlOrientation, spinnerSlScale}); + + checkRotation.setText("Rotation"); + checkRotation.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkRotationActionPerformed(evt); + } + }); + + spinnerRotationAngle.setModel(new javax.swing.SpinnerNumberModel(0.0d, -360.0d, 360.0d, 1.0d)); + spinnerRotationAngle.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + spinnerRotationOrder.setModel(new javax.swing.SpinnerNumberModel(1, 1, 5, 1)); + spinnerRotationOrder.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + labelOrder.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelOrder.setText("Order:"); + + labelMode.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelMode.setText("Mode:"); + + spinnerRotationMode.setModel(new javax.swing.SpinnerListModel(new String[] {"constant", "reflect", "nearest", "mirror", "wrap"})); + spinnerRotationMode.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + labelAngle.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelAngle.setText("Angle:"); + + labelConstant.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelConstant.setText("Constant:"); + + spinnerRotationConstant.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99999, 1)); + spinnerRotationConstant.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerRotationAngleStateChanged(evt); + } + }); + + checkAveraging.setText("Averaging"); + checkAveraging.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + checkAveragingActionPerformed(evt); + } + }); + + spinnerAvFrames.setModel(new javax.swing.SpinnerNumberModel(1, 1, 1000, 1)); + spinnerAvFrames.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerAvFramesStateChanged(evt); + } + }); + + labelAvFrames.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelAvFrames.setText("Frames:"); + + labelAvMode.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + labelAvMode.setText("Mode:"); + + spinnerAvMode.setModel(new javax.swing.SpinnerListModel(new String[] {"single", "window"})); + spinnerAvMode.addChangeListener(new javax.swing.event.ChangeListener() { + public void stateChanged(javax.swing.event.ChangeEvent evt) { + spinnerAvModeonChange(evt); + } + }); + + javax.swing.GroupLayout panelScreen2Layout = new javax.swing.GroupLayout(panelScreen2); + panelScreen2.setLayout(panelScreen2Layout); + panelScreen2Layout.setHorizontalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addComponent(checkAveraging) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(labelAvFrames, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(labelAvMode, javax.swing.GroupLayout.Alignment.TRAILING))) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(checkGoodRegion) + .addComponent(checkRotation) + .addComponent(checkThreshold)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(labelOrder, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(labelAngle, javax.swing.GroupLayout.Alignment.TRAILING)) + .addComponent(labelGrScale, javax.swing.GroupLayout.Alignment.TRAILING))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelScreen2Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(labelConstant, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(labelMode, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(labelGrThreshold, javax.swing.GroupLayout.Alignment.TRAILING)))) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(spinnerGrScale) + .addComponent(spinnerThreshold) + .addComponent(spinnerRotationOrder) + .addComponent(spinnerRotationMode) + .addComponent(spinnerRotationAngle) + .addComponent(spinnerRotationConstant) + .addComponent(spinnerAvFrames) + .addComponent(spinnerAvMode)) + .addContainerGap()) + .addComponent(panelSlicing, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addComponent(checkBackground) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + panelScreen2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {spinnerAvFrames, spinnerAvMode, spinnerGrScale, spinnerGrThreshold, spinnerRotationAngle, spinnerRotationConstant, spinnerRotationMode, spinnerRotationOrder, spinnerThreshold}); + + panelScreen2Layout.setVerticalGroup( + panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelScreen2Layout.createSequentialGroup() + .addContainerGap() + .addComponent(checkBackground) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkThreshold) + .addComponent(spinnerThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkAveraging) + .addComponent(spinnerAvFrames, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelAvFrames)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerAvMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelAvMode)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkRotation) + .addComponent(spinnerRotationAngle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelAngle)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerRotationOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelOrder)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerRotationMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelMode)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerRotationConstant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelConstant)) + .addGap(2, 2, 2) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(checkGoodRegion) + .addComponent(spinnerGrScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrScale)) + .addGap(0, 0, 0) + .addGroup(panelScreen2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(spinnerGrThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(labelGrThreshold)) + .addGap(2, 2, 2) + .addComponent(panelSlicing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + panelScreen2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {spinnerGrScale, spinnerGrThreshold, spinnerRotationAngle, spinnerRotationConstant, spinnerRotationMode, spinnerRotationOrder, spinnerThreshold}); + + javax.swing.GroupLayout sidePanelLayout = new javax.swing.GroupLayout(sidePanel); + sidePanel.setLayout(sidePanelLayout); + sidePanelLayout.setHorizontalGroup( + sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(sidePanelLayout.createSequentialGroup() + .addContainerGap() + .addGroup(sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelScreen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panelFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + sidePanelLayout.setVerticalGroup( + sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(sidePanelLayout.createSequentialGroup() + .addGap(0, 0, 0) + .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelScreen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(panelFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + toolBar.setFloatable(false); + toolBar.setRollover(true); + + buttonSidePanel.setIcon(getIcon("List")); + buttonSidePanel.setSelected(true); + buttonSidePanel.setText(" "); + buttonSidePanel.setToolTipText("Show Side Panel"); + buttonSidePanel.setFocusable(false); + buttonSidePanel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonSidePanel.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSidePanelActionPerformed(evt); + } + }); + toolBar.add(buttonSidePanel); + + buttonStreamData.setIcon(getIcon("Details")); + buttonStreamData.setText(" "); + buttonStreamData.setToolTipText("Show Data Window"); + buttonStreamData.setFocusable(false); + buttonStreamData.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonStreamData.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonStreamDataActionPerformed(evt); + } + }); + toolBar.add(buttonStreamData); + + buttonSave.setIcon(getIcon("Save")); + buttonSave.setText(" "); + buttonSave.setToolTipText("Save Snapshot"); + buttonSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonSave.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonSaveActionPerformed(evt); + } + }); + toolBar.add(buttonSave); + + buttonGrabBackground.setIcon(getIcon("Background")); + buttonGrabBackground.setText(" "); + buttonGrabBackground.setToolTipText("Grab Background"); + buttonGrabBackground.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonGrabBackground.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonGrabBackgroundActionPerformed(evt); + } + }); + toolBar.add(buttonGrabBackground); + + buttonPause.setIcon(getIcon("Pause")); + buttonPause.setText(" "); + buttonPause.setToolTipText("Pause"); + buttonPause.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonPause.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonPauseActionPerformed(evt); + } + }); + toolBar.add(buttonPause); + + jSeparator6.setMaximumSize(new java.awt.Dimension(20, 32767)); + jSeparator6.setPreferredSize(new java.awt.Dimension(20, 0)); + jSeparator6.setRequestFocusEnabled(false); + toolBar.add(jSeparator6); + + buttonMarker.setIcon(getIcon("Marker")); + buttonMarker.setText(" "); + buttonMarker.setToolTipText("Show Marker"); + buttonMarker.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonMarker.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonMarkerActionPerformed(evt); + } + }); + toolBar.add(buttonMarker); + + buttonProfile.setIcon(getIcon("Profile" + + "")); + buttonProfile.setSelected(true); + buttonProfile.setText(" "); + buttonProfile.setToolTipText("Show Image Profile"); + buttonProfile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonProfile.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonProfileActionPerformed(evt); + } + }); + toolBar.add(buttonProfile); + + buttonFit.setIcon(getIcon("Fit")); + buttonFit.setSelected(true); + buttonFit.setText(" "); + buttonFit.setToolTipText("Show Fit"); + buttonFit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonFit.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonFitActionPerformed(evt); + } + }); + toolBar.add(buttonFit); + + buttonReticle.setIcon(getIcon("Reticule")); + buttonReticle.setSelected(true); + buttonReticle.setText(" "); + buttonReticle.setToolTipText("Show Reticle"); + buttonReticle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonReticle.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonReticleActionPerformed(evt); + } + }); + toolBar.add(buttonReticle); + + buttonScale.setIcon(getIcon("Scale")); + buttonScale.setSelected(true); + buttonScale.setText(" "); + buttonScale.setToolTipText("Show Colormap Scale"); + buttonScale.setFocusable(false); + buttonScale.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonScale.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonScaleActionPerformed(evt); + } + }); + toolBar.add(buttonScale); + + buttonTitle.setIcon(getIcon("Title")); + buttonTitle.setSelected(true); + buttonTitle.setText(" "); + buttonTitle.setToolTipText("Show Camera Name"); + buttonTitle.setFocusable(false); + buttonTitle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + buttonTitle.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + buttonTitleActionPerformed(evt); + } + }); + toolBar.add(buttonTitle); + + pauseSelection.setDecimals(0); + + jLabel1.setText("Camera:"); + + comboCameras.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N + comboCameras.setMaximumRowCount(30); + comboCameras.setMinimumSize(new java.awt.Dimension(127, 27)); + comboCameras.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboCamerasActionPerformed(evt); + } + }); + + jLabel5.setText("Type:"); + + comboType.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N + comboType.setMaximumRowCount(30); + comboType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "Laser", "Electrons", "Photonics" })); + comboType.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + comboTypeActionPerformed(evt); + } + }); + + javax.swing.GroupLayout panelCameraSelectionLayout = new javax.swing.GroupLayout(panelCameraSelection); + panelCameraSelection.setLayout(panelCameraSelectionLayout); + panelCameraSelectionLayout.setHorizontalGroup( + panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraSelectionLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addGap(0, 0, 0) + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel5) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(comboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0)) + ); + panelCameraSelectionLayout.setVerticalGroup( + panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(panelCameraSelectionLayout.createSequentialGroup() + .addGap(0, 0, 0) + .addGroup(panelCameraSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(comboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel5) + .addComponent(jLabel1) + .addComponent(comboCameras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(0, 0, 0)) + ); + + javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel); + topPanel.setLayout(topPanelLayout); + topPanelLayout.setHorizontalGroup( + topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, topPanelLayout.createSequentialGroup() + .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(panelCameraSelection, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGap(18, 18, 18) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + topPanelLayout.setVerticalGroup( + topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(topPanelLayout.createSequentialGroup() + .addGap(1, 1, 1) + .addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(pauseSelection, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(panelCameraSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() + .addComponent(sidePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(sidePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(renderer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + ); + }// //GEN-END:initComponents + + private void buttonZoomFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomFitActionPerformed + try { + renderer.setMode(RendererMode.Fit); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomFitActionPerformed + + private void buttonZoomStretchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomStretchActionPerformed + try { + renderer.setMode(RendererMode.Stretch); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomStretchActionPerformed + + private void buttonZoomNormalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomNormalActionPerformed + try { + renderer.setMode(RendererMode.Fixed); + centralizeRenderer(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonZoomNormalActionPerformed + + private void onChangeColormap(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onChangeColormap + try { + if ((camera != null) && (camera instanceof ColormapSource) && !updatingColormap) { + ColormapSource source = (ColormapSource) camera; + Color colorReticule = new Color(16, 16, 16); + Color colorMarker = new Color(128, 128, 128); + Colormap colormap = (Colormap) comboColormap.getSelectedItem(); + source.getConfig().colormap = (colormap == null) ? Colormap.Flame : colormap; + switch (source.getConfig().colormap) { + case Grayscale: + case Inverted: + case Red: + case Green: + case Blue: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + case Flame: + colorReticule = new Color(0, 192, 0); + colorMarker = new Color(64, 255, 64); + break; + } + + renderer.setPenReticle(new Pen(colorReticule)); + renderer.setPenProfile(new Pen(colorReticule, 0)); + renderer.setPenMarker(new Pen(colorMarker, 2)); + renderer.setShowReticle(false); + checkReticle(); + source.getConfig().colormapAutomatic = buttonAutomatic.isSelected(); + source.getConfig().colormapMin = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMin.getValue(); + source.getConfig().colormapMax = buttonFullRange.isSelected() ? Double.NaN : (Integer) spinnerMax.getValue(); + try { + source.getConfig().save(); + } catch (Exception ex) { + Logger.getLogger(getClass().getName()).log(Level.WARNING, null, ex); + } + source.refresh(); + if (buttonPause.isSelected()) { + updatePause(); + } + updateColormap(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_onChangeColormap + + private void onChangeColormapRange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_onChangeColormapRange + onChangeColormap(null); + }//GEN-LAST:event_onChangeColormapRange + + private void buttonZoom025ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom025ActionPerformed + renderer.setZoom(0.25); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom025ActionPerformed + + private void buttonZoom05ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom05ActionPerformed + renderer.setZoom(0.5); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom05ActionPerformed + + private void buttonServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonServerActionPerformed + if (!usingServer) { + usingServer = true; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonServerActionPerformed + + private void buttonDirectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDirectActionPerformed + if (usingServer) { + usingServer = false; + requestCameraListUpdate = true; + } + comboCamerasActionPerformed(null); + }//GEN-LAST:event_buttonDirectActionPerformed + + private void comboScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboScreenActionPerformed + + comboScreen.setEnabled(false); + new Thread(new Runnable() { + @Override + public void run() { + ChannelInteger setpoint = null; + try { + int index = comboScreen.getSelectedIndex(); + if (index >= 0) { + if (cameraName.contains("DSRM")) { + setpoint = new ChannelInteger(null, cameraName + ":POSITION_SP"); + } else { + setpoint = new ChannelInteger(null, cameraName + ":SET_SCREEN1_POS"); + } + setpoint.initialize(); + Integer readback = setpoint.read(); + if ((readback == null) || (setpoint.read() != index)) { + setpoint.write(index); + //Must be threaded to control the laser because of sleep in setLaserState + /* + boolean laserOn = getLaserState(); + if (laserOn) { + setLaserState(false); + } + try { + setpoint.write(index); + } finally { + if (laserOn) { + setLaserState(true); + } + } + */ + } + screen.read(); + } + } catch (Exception ex) { + showException(ex); + } finally { + comboScreen.setEnabled(true); + if (setpoint != null) { + setpoint.close(); + } + } + } + }).start(); + }//GEN-LAST:event_comboScreenActionPerformed + + private void comboFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboFilterActionPerformed + try { + String setpoint = (String) comboFilter.getSelectedItem(); + if (setpoint != null) { + if (!setpoint.equals(filter.read())) { + filter.write(setpoint); + } + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboFilterActionPerformed + + private void checkHistogramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkHistogramActionPerformed + try { + setHistogramVisible(checkHistogram.isSelected()); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_checkHistogramActionPerformed + + private void buttonZoom2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoom2ActionPerformed + renderer.setZoom(2.0); + renderer.setMode(RendererMode.Zoom); + centralizeRenderer(); + }//GEN-LAST:event_buttonZoom2ActionPerformed + + private void spinnerThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setThreshold((Double) spinnerThreshold.getValue()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_spinnerThresholdonChange + + private void checkBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBackgroundActionPerformed + if (server != null) { + if (!updatingServerControls) { + try { + if (server.isStarted()) { + server.setBackgroundSubtraction(checkBackground.isSelected()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + updatingServerControls = true; + checkBackground.setSelected(false); + updatingServerControls = false; + + } + } + } else { + camera.setBackgroundEnabled(checkBackground.isSelected()); + } + }//GEN-LAST:event_checkBackgroundActionPerformed + + private void checkThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkThresholdActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + spinnerThreshold.setVisible(checkThreshold.isSelected()); + server.setThreshold(checkThreshold.isSelected() ? (Double) spinnerThreshold.getValue() : null); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkThresholdActionPerformed + + private void checkGoodRegionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkGoodRegionActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + goodRegion = checkGoodRegion.isSelected(); + setGoodRegionOptionsVisible(goodRegion); + if (goodRegion) { + server.setGoodRegion(((Number) spinnerGrThreshold.getValue()).doubleValue(), ((Number) spinnerGrScale.getValue()).doubleValue()); + } else { + server.setGoodRegion(null); + } + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkGoodRegionActionPerformed + + private void spinnerGrThresholdonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerGrThresholdonChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setGoodRegion((Double) spinnerGrThreshold.getValue(), (Double) spinnerGrScale.getValue()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_spinnerGrThresholdonChange + + private void btFixColormapRangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFixColormapRangeActionPerformed + try { + updatingColormap = true; + ArrayProperties properties = currentFrame.data.getProperties(); + spinnerMax.setValue(properties.max.intValue()); + spinnerMin.setValue(properties.min.intValue()); + buttonManual.setSelected(true); + } catch (Exception ex) { + showException(ex); + } finally { + updatingColormap = false; + onChangeColormap(null); + } + }//GEN-LAST:event_btFixColormapRangeActionPerformed + + private void checkSlicingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSlicingActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + slicing = checkSlicing.isSelected(); + setSlicingOptionsVisible(slicing); + if (slicing) { + server.setSlicing((Integer) spinnerSlNumber.getValue(), (Double) spinnerSlScale.getValue(), spinnerSlOrientation.getValue().toString()); + } else { + server.setSlicing(null); + } + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkSlicingActionPerformed + + private void spinnerSlicingChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerSlicingChange + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + server.setSlicing((Integer) spinnerSlNumber.getValue(), (Double) spinnerSlScale.getValue(), spinnerSlOrientation.getValue().toString()); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_spinnerSlicingChange + + private void buttonReticleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonReticleActionPerformed + try { + checkReticle(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonReticleActionPerformed + + private void buttonFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFitActionPerformed + try { + showFit = buttonFit.isSelected(); + if (showFit) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(fitOv); + fitOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonFitActionPerformed + + private void buttonProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonProfileActionPerformed + try { + showProfile = buttonProfile.isSelected(); + if (showProfile) { + renderer.setProfile(Renderer.Profile.None); + } else { + renderer.removeOverlays(profileOv); + profileOv = null; + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonProfileActionPerformed + + private void buttonMarkerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonMarkerActionPerformed + try { + checkMarker(null); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonMarkerActionPerformed + + private void buttonPauseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPauseActionPerformed + try { + if (!updatingButtons) { + setPaused(buttonPause.isSelected()); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonPauseActionPerformed + + private void buttonGrabBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGrabBackgroundActionPerformed + try { + if (camera != null) { + boolean laserOn1 = getLaserState(1); + boolean laserOn2 = getLaserState(2); + OptionResult ret = null; + if (laserOn1 || laserOn2) { + if (laserOn1){ + ret = SwingUtils.showOption(getTopLevel(), "Capture Background", "Do you want to put Bunch 1 laser on delay for capturing background?", OptionType.YesNoCancel); + if (ret == OptionResult.No) { + laserOn1 = false; + } + if (ret == OptionResult.Cancel) { + return; + } + } + if (laserOn2){ + ret = SwingUtils.showOption(getTopLevel(), "Capture Background", "Do you want to put Bunch 2 laser on delay for capturing background?", OptionType.YesNoCancel); + if (ret == OptionResult.No) { + laserOn2= false; + } + if (ret == OptionResult.Cancel) { + return; + } + } + } else { + ret = SwingUtils.showOption(getTopLevel(), "Capture Background", "Do you want to capture background now?", OptionType.OkCancel); + } + + if (ret == OptionResult.Cancel) { + return; + } + + if (laserOn1) { + setLaserState(1,false); + } + if (laserOn2) { + setLaserState(2,false); + } + try { + System.out.println("Grabbing background for: " + cameraName); + if (server != null) { + server.captureBackground(5); + } else { + camera.captureBackground(5, 0); + } + } finally { + if (laserOn1) { + setLaserState(1,true); + } + if (laserOn2) { + setLaserState(2,true); + } + } + SwingUtils.showMessage(getTopLevel(), "Success", "Success capturing background", 5000); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonGrabBackgroundActionPerformed + + private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed + try { + saveSnapshot(); + } catch (Exception ex) { + Logger.getLogger(getClass().getName()).log(Level.WARNING, null, ex); + showException(ex); + } + }//GEN-LAST:event_buttonSaveActionPerformed + + private void buttonStreamDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStreamDataActionPerformed + try { + showStreamData(); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonStreamDataActionPerformed + + private void buttonSidePanelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSidePanelActionPerformed + sidePanel.setVisible(buttonSidePanel.isSelected()); + }//GEN-LAST:event_buttonSidePanelActionPerformed + + private void comboTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboTypeActionPerformed + try { + if (!updatingCameraSelection) { + updateCameraList(); + if ((cameraName != null) && (!cameraName.equals(comboCameras.getSelectedItem()))) { + setCamera(null); + } else { + setCamera(cameraName); + } + } + + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + } + }//GEN-LAST:event_comboTypeActionPerformed + + private void comboCamerasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboCamerasActionPerformed + try { + if (!updatingCameraSelection) { + if (!comboCameras.isEnabled()) { + throw new Exception("Invalid state"); + } + comboCameras.setEnabled(false); + comboType.setEnabled(false); + buttonServer.setEnabled(false); + buttonDirect.setEnabled(false); + final String cameraName = (String) comboCameras.getSelectedItem(); + new Thread(new Runnable() { + @Override + public void run() { + if (requestCameraListUpdate) { + requestCameraListUpdate = false; + try { + updateCameraList(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + try { + setCamera(cameraName.trim().isEmpty() ? null : cameraName); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + updateButtons(); + comboCameras.setEnabled(true); + comboType.setEnabled(true); + buttonServer.setEnabled(true); + buttonDirect.setEnabled(true); + } + } + }).start(); + } + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_comboCamerasActionPerformed + + private void buttonTitleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonTitleActionPerformed + try { + manageTitleOverlay(); + } catch (Exception ex) { + showException(ex); + } finally { + } + }//GEN-LAST:event_buttonTitleActionPerformed + + private void buttonScaleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonScaleActionPerformed + try { + renderer.setShowColormapScale(buttonScale.isSelected()); + } catch (Exception ex) { + showException(ex); + } + }//GEN-LAST:event_buttonScaleActionPerformed + + private void checkRotationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkRotationActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + boolean rotation = checkRotation.isSelected(); + setRotationOptionsVisible(rotation); + if (rotation) { + spinnerRotationAngleStateChanged(null); + } else { + server.setRotation(null); + } + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkRotationActionPerformed + + private void spinnerRotationAngleStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerRotationAngleStateChanged + try { + String mode = String.valueOf(spinnerRotationMode.getValue()); + server.setRotation(((Number) spinnerRotationAngle.getValue()).doubleValue(), + ((Number) spinnerRotationOrder.getValue()).intValue(), + mode.equals("constant") ? String.valueOf(spinnerRotationConstant.getValue()): mode); + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + }//GEN-LAST:event_spinnerRotationAngleStateChanged + + private void checkAveragingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkAveragingActionPerformed + if (!updatingServerControls) { + try { + if ((server != null) && (server.isStarted())) { + setAveragingOptionsVisible(checkAveraging.isSelected()); + Integer av = spinnerAvMode.getValue().equals("window") ? - (Integer)spinnerAvFrames.getValue() : (Integer)spinnerAvFrames.getValue(); + setInstanceConfigValue("averaging", checkAveraging.isSelected() ? av : null); + } + } catch (Exception ex) { + showException(ex); + updatePipelineControls(); + } + } + }//GEN-LAST:event_checkAveragingActionPerformed + + private void spinnerAvModeonChange(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerAvModeonChange + checkAveragingActionPerformed(null); + }//GEN-LAST:event_spinnerAvModeonChange + + private void spinnerAvFramesStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerAvFramesStateChanged + checkAveragingActionPerformed(null); + }//GEN-LAST:event_spinnerAvFramesStateChanged + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btFixColormapRange; + private javax.swing.JRadioButton buttonAutomatic; + private javax.swing.JRadioButton buttonDirect; + private javax.swing.JToggleButton buttonFit; + private javax.swing.JRadioButton buttonFullRange; + private javax.swing.JButton buttonGrabBackground; + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.ButtonGroup buttonGroup2; + private javax.swing.ButtonGroup buttonGroup3; + private javax.swing.ButtonGroup buttonGroup4; + private javax.swing.JRadioButton buttonManual; + private javax.swing.JToggleButton buttonMarker; + private javax.swing.JToggleButton buttonPause; + private javax.swing.JToggleButton buttonProfile; + private javax.swing.JToggleButton buttonReticle; + private javax.swing.JToggleButton buttonSave; + private javax.swing.JToggleButton buttonScale; + private javax.swing.JRadioButton buttonServer; + private javax.swing.JToggleButton buttonSidePanel; + private javax.swing.JButton buttonStreamData; + private javax.swing.JToggleButton buttonTitle; + private javax.swing.JRadioButton buttonZoom025; + private javax.swing.JRadioButton buttonZoom05; + private javax.swing.JRadioButton buttonZoom2; + private javax.swing.JRadioButton buttonZoomFit; + private javax.swing.JRadioButton buttonZoomNormal; + private javax.swing.JRadioButton buttonZoomStretch; + private javax.swing.JCheckBox checkAveraging; + private javax.swing.JCheckBox checkBackground; + private javax.swing.JCheckBox checkGoodRegion; + private javax.swing.JCheckBox checkHistogram; + private javax.swing.JCheckBox checkRotation; + private javax.swing.JCheckBox checkSlicing; + private javax.swing.JCheckBox checkThreshold; + private javax.swing.JComboBox comboCameras; + private javax.swing.JComboBox comboColormap; + private javax.swing.JComboBox comboFilter; + private javax.swing.JComboBox comboScreen; + private javax.swing.JComboBox comboType; + private javax.swing.Box.Filler filler1; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel5; + private javax.swing.JProgressBar jProgressBar1; + private javax.swing.JToolBar.Separator jSeparator6; + private javax.swing.JLabel labelAngle; + private javax.swing.JLabel labelAvFrames; + private javax.swing.JLabel labelAvMode; + private javax.swing.JLabel labelConstant; + private javax.swing.JLabel labelGrScale; + private javax.swing.JLabel labelGrThreshold; + private javax.swing.JLabel labelMax; + private javax.swing.JLabel labelMin; + private javax.swing.JLabel labelMode; + private javax.swing.JLabel labelOrder; + private javax.swing.JLabel labelSlNumber; + private javax.swing.JLabel labelSlOrientation; + private javax.swing.JLabel labelSlScale; + private javax.swing.JPanel panelCameraSelection; + private javax.swing.JPanel panelFilter; + private javax.swing.JPanel panelScreen; + private javax.swing.JPanel panelScreen2; + private javax.swing.JPanel panelSlicing; + private ch.psi.pshell.swing.ValueSelection pauseSelection; + private ch.psi.pshell.imaging.Renderer renderer; + private javax.swing.JPanel sidePanel; + private javax.swing.JSpinner spinnerAvFrames; + private javax.swing.JSpinner spinnerAvMode; + private javax.swing.JSpinner spinnerGrScale; + private javax.swing.JSpinner spinnerGrThreshold; + private javax.swing.JSpinner spinnerMax; + private javax.swing.JSpinner spinnerMin; + private javax.swing.JSpinner spinnerRotationAngle; + private javax.swing.JSpinner spinnerRotationConstant; + private javax.swing.JSpinner spinnerRotationMode; + private javax.swing.JSpinner spinnerRotationOrder; + private javax.swing.JSpinner spinnerSlNumber; + private javax.swing.JSpinner spinnerSlOrientation; + private javax.swing.JSpinner spinnerSlScale; + private javax.swing.JSpinner spinnerThreshold; + private javax.swing.JTextField textState; + private javax.swing.JToolBar toolBar; + private javax.swing.JPanel topPanel; + private ch.psi.pshell.swing.DeviceValuePanel valueFilter; + private ch.psi.pshell.swing.DeviceValuePanel valueScreen; + // End of variables declaration//GEN-END:variables +} diff --git a/plugins/SfCamera.java b/plugins/SfCamera.java new file mode 120000 index 0000000..fd4d791 --- /dev/null +++ b/plugins/SfCamera.java @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/SfCamera.java \ No newline at end of file diff --git a/plugins/resources b/plugins/resources new file mode 120000 index 0000000..657e199 --- /dev/null +++ b/plugins/resources @@ -0,0 +1 @@ +/afs/psi.ch/intranet/SF/Applications/config/pshell_op/plugins/resources \ No newline at end of file diff --git a/plugins/resources_back/Background.png b/plugins/resources_back/Background.png new file mode 100755 index 0000000..a168169 Binary files /dev/null and b/plugins/resources_back/Background.png differ diff --git a/plugins/resources_back/Fit.png b/plugins/resources_back/Fit.png new file mode 100755 index 0000000..44f80c6 Binary files /dev/null and b/plugins/resources_back/Fit.png differ diff --git a/plugins/resources_back/Marker.png b/plugins/resources_back/Marker.png new file mode 100755 index 0000000..d097a02 Binary files /dev/null and b/plugins/resources_back/Marker.png differ diff --git a/plugins/resources_back/Profile.png b/plugins/resources_back/Profile.png new file mode 100755 index 0000000..8a8209b Binary files /dev/null and b/plugins/resources_back/Profile.png differ diff --git a/plugins/resources_back/Reticule.png b/plugins/resources_back/Reticule.png new file mode 100755 index 0000000..762f01f Binary files /dev/null and b/plugins/resources_back/Reticule.png differ diff --git a/plugins/resources_back/Save.png b/plugins/resources_back/Save.png new file mode 100755 index 0000000..d1480a0 Binary files /dev/null and b/plugins/resources_back/Save.png differ diff --git a/plugins/resources_back/Sidebar.png b/plugins/resources_back/Sidebar.png new file mode 100755 index 0000000..8328264 Binary files /dev/null and b/plugins/resources_back/Sidebar.png differ diff --git a/plugins/resources_back/Title.png b/plugins/resources_back/Title.png new file mode 100755 index 0000000..d07dc34 Binary files /dev/null and b/plugins/resources_back/Title.png differ diff --git a/script/Correlation/Correlation2.py b/script/Correlation/Correlation2.py new file mode 100755 index 0000000..0efe6b9 --- /dev/null +++ b/script/Correlation/Correlation2.py @@ -0,0 +1,196 @@ +import math +import sys, traceback +from mathutils import fit_polynomial, PolynomialFunction +from plotutils import plot_line, plot_function +from ch.psi.pshell.swing.Shell import STDOUT_COLOR +import org.apache.commons.math3.stat.correlation.PearsonsCorrelation as PearsonsCorrelation +import ch.psi.pshell.bs.PipelineServer as PipelineServer + + +TYPE_CHANNEL = 0 +TYPE_STREAM = 1 +TYPE_CAMERA= 2 + +if get_exec_pars().source == CommandSource.ui: + dx = "SINDI01-RLLE-STA:SLAVE1-CPUTIMER" + #dx = "SLG-LCAM-C042 x_rms" + dxtype = TYPE_STREAM + dxtype = TYPE_CHANNEL + #dxtype = TYPE_CAMERA + #dy = "SINDI01-RLLE-STA:SLAVE1-DLTIMER" + dy = "SLG-LCAM-C042 y_rms" + dytype = TYPE_STREAM + dytype = TYPE_CHANNEL + dytype = TYPE_CAMERA + interval = 0.10 + window = 40 + p = plot(None)[0] + linear_fit = True + quadratic_fit = True +#print dx, dxtype +#print dy, dytype + +corr = None +pars_lin = None +pars_quad = None + + + +bs = TYPE_STREAM in [dxtype, dytype] + + +for s in p.getAllSeries(): + p.removeSeries(s) + +_stream = None +_camname = None + +instances = [] + +def _get_device(d, type): + global _stream, _camname + egu = None + if isinstance(d, basestring): + name = d.strip() + d = None + try: + d = get_device(name) + if d is None: + d = eval(name) + #print name + if d is not None: + if not isinstance(r, Device): + d = None + else: + try: + egu = d.unit + except: + pass + except: + pass + if d is None: + offset = 0 + + if type==TYPE_STREAM: + if " " in name: + tokens = name.split(" ") + name = tokens[0] + offset = int(tokens[1]) + if _stream == None: + _stream = Stream("corr_stream", dispatcher) + instances.append(_stream) + d = _stream.addScalar(name, name, int(interval*100), offset) + elif type==TYPE_CHANNEL: + d = Channel(name) + d.set_monitored(True) + elif type==TYPE_CAMERA: + tokens = name.split(" ") + _camname = tokens[0] + field = tokens[1] + return field, "" + else: + raise Exception("Invalid type: " + str(type)) + if not isinstance(d, basestring): + instances.append(d) + try: + egu = caget(name+".EGU",'s') + except: + pass + else: + try: + egu = d.unit + except: + pass + return d, egu + +dx, egux = _get_device(dx, dxtype) +dy, eguy = _get_device(dy, dytype) + +p.getAxis(p.AxisId.X).setLabel(egux) +p.getAxis(p.AxisId.Y).setLabel(eguy) + + +try: + if _stream != None: + _stream.initialize() + _stream.start(True) + if _camname != None: + shared = _camname.endswith("_sp1") + print "Camera: " , _camname, " shared: ", shared + cam_server.start(_camname, shared ) + cam_server.stream.waitCacheChange(10000); + if dxtype==TYPE_CAMERA: + dx=cam_server.stream.getChild(dx) + if dytype==TYPE_CAMERA: + dy=cam_server.stream.getChild(dy) + + p.addSeries(LinePlotSeries("Data")) + sd=p.getSeries(0) + sd.setLinesVisible(False) + + sd.setPointSize(4) + + if get_exec_pars().source == CommandSource.ui: + if globals().has_key("marker"): + p.removeMarker(marker) + marker=None + + + while(True): + #Sample and plot data + if bs == True: + _stream.waitValueNot(_stream.take(), 10000) + bsdata = list(_stream.take().values) + + if dxtype==TYPE_CHANNEL: + x=dx.read() + elif dxtype==TYPE_STREAM: + x=bsdata.pop(0) + elif dxtype==TYPE_CAMERA: + x=dx.read() + + if dytype==TYPE_CHANNEL: + y=dy.read() + elif dytype==TYPE_STREAM: + y=bsdata.pop(0) + elif dytype==TYPE_CAMERA: + y=dy.read() + + sd.appendData(x, y) + if len(sd.x) > window: + #Remove First Element + sd.token.remove(0) + ax = sd.x + ay = sd.y + if len(ax)>2: + x1, x2 = min(ax), max(ax) + res = (x2-x1)/100 + if x1!=x2: + #Display correlation + corr= PearsonsCorrelation().correlation(to_array(ax,'d'), to_array(ay,'d')) + s = "Correlation=" + str(round(corr,4)) + #print s + if get_exec_pars().source == CommandSource.ui: + if marker is not None: + p.removeMarker(marker) + marker = p.addMarker(x2+res, p.AxisId.X, s, p.getBackground()) + marker.setLabelPaint(STDOUT_COLOR) + if linear_fit: + #Calculate, print and plot linear fit + pars_lin = (a0,a1) = fit_polynomial(ay, ax, 1) + #print "Fit lin a1:" , a1, " a0:",a0 + y1 = poly(x1, pars_lin) + y2 = poly(x2, pars_lin) + plot_line(p, x1, y1, x2, y2, width = 2, color = Color.BLUE, name = "Fit Linear") + if quadratic_fit: + #Calculate, print and plot quadratic fit + pars_quad = (a0,a1,a2) = fit_polynomial(ay, ax, 2) + #print "Fit quad a2:" , a2, "a1:" , a1, " a0:",a0 + fitted_quad_function = PolynomialFunction(pars_quad) + ax = frange(x1, x2, res, True) + plot_function(p, fitted_quad_function, "Fit Quadratic", ax, color=Color.GREEN) + if bs != True: + time.sleep(interval) +finally: + for dev in instances: + dev.close() \ No newline at end of file diff --git a/script/ErrorPlot.py b/script/ErrorPlot.py new file mode 100755 index 0000000..33415e3 --- /dev/null +++ b/script/ErrorPlot.py @@ -0,0 +1,54 @@ +################################################################################################### +# Example creating error plots +################################################################################################### + + +[py, px, pxy]=plot([None,None,None],["y","x", "xy"]) + +#Y error plot +py.setStyle(py.Style.ErrorY) +py.setLegendVisible(True) + +sy1 = LinePlotErrorSeries("F1") +py.addSeries(sy1) +sy1.appendData(1.0, 10.0, 9.0, 11.0) +sy1.appendData(10.0, 6.1, 4.34, 7.54) +sy1.appendData(17.8, 4.5, 3.1, 5.8) +#One can define error instead of min/max (appendData(x, y, error)) +sy2 = LinePlotErrorSeries("F2") +py.addSeries(sy2) +sy2.setLinesVisible(False) +sy2.appendData(3.0, 7.0, 2.0); +sy2.appendData(13.0, 13.0, 2.0); +sy2.appendData(24.0, 16.1, 1.0); + +#X error plot +px.setStyle(px.Style.ErrorX) +px.setLegendVisible(True) +sx = LinePlotErrorSeries("F3") +px.addSeries(sx) +sx.appendData(1.0, 10.0, 0.5, 1.5) +sx.appendData(10.0, 6.1, 9.0, 10.3) +sx.appendData(17.8, 4.5, 17.0, 18.0) +#One can define error instead of min/max (appendData(x, y, error)) +sx2 = LinePlotErrorSeries("F4") +px.addSeries(sx2) +sx2.setLinesVisible(False) +sx2.appendData(1.0, 3.0, 1.0) +sx2.appendData(10.0, 5.1, 1.0) +sx2.appendData(17.8, 7.5, 0.5) + +#XY error plot +pxy.setStyle(pxy.Style.ErrorXY) +pxy.setLegendVisible(True) +sxy = LinePlotErrorSeries("F5") +pxy.addSeries(sxy) +sxy.appendData(1.0,0.5,1.5, 10.0, 9.0, 11.0) +sxy.appendData(10.0,9.0, 11.0, 6.1, 4.34, 7.54) +sxy.appendData(17.8, 17.0, 18.0, 4.5, 3.1, 5.8) +#One can define error instead of min/max (appendData(x, y, errorX, errorY)) +sxy2 = LinePlotErrorSeries("F6") +pxy.addSeries(sxy2) +sxy2.appendData(3.0, 7.0, 0.5, 4.0); +sxy2.appendData(13.0, 13.0, 0.5, 3.0); +sxy2.appendData(24.0, 16.1, 0.2, 2.0); \ No newline at end of file diff --git a/script/Motion_Control.scan b/script/Motion_Control.scan new file mode 100755 index 0000000..30e3356 --- /dev/null +++ b/script/Motion_Control.scan @@ -0,0 +1 @@ +[ "Linear", [ [ "Channel", "SLAAR21-LMOT-M552:MOT.VAL", 322.0, 323.0, 0.1 ] ], [ [ "Channel", "ELCOMAT:X ", 100, 0, "Enabled" ], [ "Channel", "ELCOMAT:Y", 100, 0, "Enabled" ] ], false, [ ], "", 1, 1.0, 0.0, false, false, true, true, "global_delay-stage", "", " ", "h5", 0, null, null, "Positioner", false, true ] \ No newline at end of file diff --git a/script/NewFolder/Hardware_scan.py b/script/NewFolder/Hardware_scan.py new file mode 100755 index 0000000..813efc5 --- /dev/null +++ b/script/NewFolder/Hardware_scan.py @@ -0,0 +1,39 @@ +################################################################################################### +# Use of HardwareScan +################################################################################################### + +import ch.psi.pshell.crlogic.CrlogicPositioner as CrlogicPositioner +import ch.psi.pshell.crlogic.CrlogicSensor as CrlogicSensor + +#sc1.stop() +#sc1.setOneShot() +#sc1.channels[0].setPreset(False) +#sc1.channels[0].setPresetValue(0) +#sc1.start() + +config = {} +config["class"] = "ch.psi.pshell.crlogic.CrlogicScan" +config["prefix"] = "MTEST-HW3-CRL" +config["ioc"] = "MTEST-VME-HW3.psi.ch" +config["integrationTime"] = 0.01 +config["additionalBacklash"] = 0.0 + +pos = CrlogicPositioner("CrlogicPositioner", "MTEST-HW3:MOT1", None); + +sensors = [ + CrlogicSensor("Trigger0", "TRIGGER0"), + CrlogicSensor("Trigger1", "TRIGGER1"), + CrlogicSensor("Scaler0", "SCALER0", True), + CrlogicSensor("Scaler1", "SCALER1", True), + CrlogicSensor("Timestamp", "TIMESTAMP"), + ] + + + +pos.initialize() +pos.move(0.0) +try: + r1 = hscan(config, pos, sensors,0.0, 10.0, 0.1,1, False) +finally: + pos.close() + \ No newline at end of file diff --git a/script/NewFolder/LineScan.py b/script/NewFolder/LineScan.py new file mode 100755 index 0000000..4b12b43 --- /dev/null +++ b/script/NewFolder/LineScan.py @@ -0,0 +1,13 @@ +################################################################################################### +# Demonstrate the use of Line Scan: one or multiple positioners move together linearly. +################################################################################################### + + +#Execute the scan: 100 steps, a1 from 0 to 40 +r1 = lscan(ao1, (ai1,ai2,wf1), 0, 40, 100, 0.01) + +#Steps of size 1.0, a1 from 0 to 40 +#r2 = lscan(ao1, (ai1,ai2,wf1), 0, 40, 1.0, 0.01) + +#2 positioners moving together in 10 steps. Also sampling an image: +#r3 = lscan((ao1,ao2), (ai1,ai2,wf1,im1), (0, 0), (40, 100), 4, 0.01) diff --git a/script/NewFolder/MonitorScan.py b/script/NewFolder/MonitorScan.py new file mode 100755 index 0000000..c69d34f --- /dev/null +++ b/script/NewFolder/MonitorScan.py @@ -0,0 +1,50 @@ +################################################################################################### +# Demonstrate the use of Monitor Scan: sampling based on device change event +################################################################################################### + + +#Simulating async devices: +ai1.setPolling(50) +ai2.setPolling(50) + + +#Execute the scan: 25 samples +r1 = mscan(ai1, [ai1], 25) + +#Execute the scan: 50 samples, with a timeout of 2s, including a second device, which cache is sampled +r2 = mscan(ai1, [ai1, ai2], 50, 2.0) + +#Execute the scan: sampling for 5s, an undefined number of sample +r3 = mscan(ai1, [ai1, ai2], -1, 5.0) + +#If a non-cached sensor access is needed, scan must be started in sync mode, but records may then be lost. +#In this example ai1 is cached (the trigger always is), wf1 is not, and ai2 is. +r4 = mscan(ai1, [ai1, wf1, ai2.cache], -1, 5.0, async = False) + + +# Scanning a set of sensors based on a software trigger, using mscan +import random + +class Trigger(ReadonlyRegisterBase): + def doRead(self): + return None + +trigger = Trigger() +trigger.initialize() + +def scan(): + mscan(trigger, [ai1, ai2], 10) + +scan_task = fork(scan) + +time.sleep(0.5) +for i in range(10): + trigger.update() + time.sleep(random.random()/5) + +ret = join(scan_task) + + +#Restoring the device state +ai1.setPolling(0) +ai2.setPolling(0) \ No newline at end of file diff --git a/script/NewFolder/PSSS/xstal_bender_y.py b/script/NewFolder/PSSS/xstal_bender_y.py new file mode 100755 index 0000000..ba4d75a --- /dev/null +++ b/script/NewFolder/PSSS/xstal_bender_y.py @@ -0,0 +1,43 @@ +scan_from = -1.7 +scan_to = -1.0 +steps = 10 + +motor = 'ca://SARFE10-PSSS059:MOTOR_Y3.VAL' +title = "PSSS crystal height scan" +size = caget('SARFE10-PSSS059:SPECTRUM_X.NORD','i') +sx = caget('SARFE10-PSSS059:SPECTRUM_X', size = size) +sy = create_device('ca://SARFE10-PSSS059:SPECTRUM_Y?samples=10&interval=10&size='+str(size)) + +class SpectrumY(ReadableArray, ReadableCalibratedArray): + def read(self): + return sy.read() + def getSize(self): + return size + def getCalibration(self): + return ArrayCalibration((sx[-1]-sx[0])/max(len(sx), 1), sx[0]) +calibrated_sensor = SpectrumY() + +r1 = lscan(motor, calibrated_sensor, start =scan_from, end = scan_to ,steps = steps, title=title) + +#def getCrystal(crystal): +# xstal = crystal.read() +# if xstal == "None": +# Crystal_type = "None" +# elseif xstal == "Si(111)R155 4-5.5 keV" +# Crystal_type = "Si(220)R145" +# 2 Si(220)R75 5.5-8 keV +# 3 Si(220)R145 8-10.25 keV +# 4 Si(220)R200 10.25-13 keV +# 5 Si(333)R155 +# return xstal + +#print(getCrystal(crystal)) + +#motor = 'ca://SARFE10-PSSS059:MOTOR_Y3.VAL' +#title = "PSSS crystal height scan" +#sensor = ['ca://SARFE10-PSSS059:SPECTRUM_Y?samples=10&interval=10'] +#scan_from = -1.7 +#scan_to = -1.0 +#steps = 10 +#r1 = lscan(motor, sensor, start =scan_from, end = scan_to, [0.01], title=title) +#r1 = lscan(motor, sensor, start =scan_from, end = scan_to ,steps = steps, title=title) diff --git a/script/NewFolder/SimulatedDevices.py b/script/NewFolder/SimulatedDevices.py new file mode 100755 index 0000000..055d45e --- /dev/null +++ b/script/NewFolder/SimulatedDevices.py @@ -0,0 +1,186 @@ +import random + +#################################################################################################### +# Simulated Devices +#################################################################################################### + +class AnalogOutput(RegisterBase): + def doRead(self): + return self.val if hasattr(self, 'val') else 0.0 + + def doWrite(self, val): + self.val = val + +class AnalogInput(ReadonlyRegisterBase): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + +class Waveform(ReadonlyRegisterBase, ReadonlyRegisterArray): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + +class Image(ReadonlyRegisterBase, ReadonlyRegisterMatrix): + def doRead(self): + time.sleep(0.001) + self.val = to_array(self.calc(), 'd') + return self.val + + def getWidth(self): + return len(self.take(-1)[0]) + + def getHeight(self): + return len(self.take(-1)) + + + +class Random(AnalogInput): + def calc(self): + return random.random() + + +class SinusoidSample(AnalogInput): + def calc(self): + self.x = self.x + 0.1 if hasattr(self, 'x') else 0.0 + noise = (random.random() - 0.5) / 10.0 + return math.sin(self.x) + noise + +class SinusoidTime(AnalogInput): + def calc(self): + noise = (random.random() - 0.5) / 10.0 + return math.sin(time.time()) + noise + + +class SinusoidWaveform(Waveform): + def calc(self): + ret = [] + x = random.random() + for i in range (20): + ret.append(math.sin(x)) + x = x + 0.1 + return ret + +class SinusoidImage(Image): + def calc(self): + (width, height) = (200, 100) + ret = [] + x = random.random(); + base = [] + for i in range (width): + base.append( math.sin(x)) + x = x + 0.05 + for i in range (height): + noise = (random.random() - 0.5)/5.0 + ret.append([x+noise for x in base]) + return ret + + +#Defintion +add_device(DummyMotor("m1"), True) +add_device(DummyMotor("m2"), True) +add_device(DummyRegister("reg1",3), True) +add_device(AnalogOutput("ao1"), True) +add_device(AnalogOutput("ao2"), True) +add_device(SinusoidSample("ai1"), True) +add_device(SinusoidTime("ai2"), True) +add_device(Random("ai3"), True) +add_device(SinusoidWaveform("wf1"), True) +add_device(SinusoidImage("im1"), True) +add_device(DummyPositioner("p1"),True) +add_device(MotorGroupBase("mg1", m1, m2), True) +add_device(MotorGroupDiscretePositioner("dp1", mg1), True) + + + +#Initial Configuration +if p1.config.unit is None: + p1.config.minValue = 0.0 #Not persisted + p1.config.maxValue = 1000.0 + p1.config.unit = "mm" + p1.config.save() + p1.initialize() + +if dp1.config.positions is None: + dp1.config.positions = ["Park","Ready","Out","Clear"] + dp1.config.motor1 = ["0.0","4.0","8.0" ,"0.0"] + dp1.config.motor2 = ["0.0","5.0","3.0" ,"NaN"] + dp1.config.save() + dp1.initialize() + + + +#Update +m1.setMonitored(True) +m2.setMonitored(True) + + + + +#################################################################################################### +# Simple Readable / Writable objects can be created and used in scans +#################################################################################################### +class WritableScalar(Writable): + def write(self, value): + pass + +class ReadableScalar(Readable): + def read(self): + return random.random() + + +class ReadableWaveform(ReadableArray): + def getSize(self): + return 20 + + def read(self): + ret = [] + for i in range (self.getSize()): + ret.append(random.random()) + return ret + +class ReadableImage(ReadableMatrix): + def read(self): + ret = [] + for i in range (self.getHeight()): + ret.append([random.random()] * self.getWidth()) + return to_array(ret, 'd') + + def getWidth(self): + return 80 + + def getHeight(self): + return 40 + + + +ws1 = WritableScalar() +rs1 = ReadableScalar() +rw1 = ReadableWaveform() +ri1 = ReadableImage() + + +#################################################################################################### +# Imaging +#################################################################################################### + +configured = os.path.exists(Device.getConfigFileName("src1")) + +add_device(RegisterMatrixSource("src1", im1), True) +add_device(RegisterMatrixSource("src2", ri1), True) + +src1.polling = 100 +src2.polling = 100 + +#Some configuration for so the imaging will work out of the box +if not configured: + import ch.psi.pshell.imaging.Colormap + src1.config.colormapAutomatic = True + src1.config.colormap = ch.psi.pshell.imaging.Colormap.Temperature + src1.config.save() + src2.config.colormapAutomatic = True + src2.config.save() + + diff --git a/script/Stage_check.py b/script/Stage_check.py new file mode 100755 index 0000000..20f0746 --- /dev/null +++ b/script/Stage_check.py @@ -0,0 +1 @@ +lscan(['ca://SLAAR21-LMOT-M523:MOTOR_1.VAL'], ['ca://ELCOMAT:X?monitored=true&samples=10', 'ca://ELCOMAT:Y?monitored=true&samples=10'], [180.0], [270.0], [0.1], latency=0.0, relative=False, passes=1, zigzag=False, keep=False, name='global_delay_stage_long', provider='h5') \ No newline at end of file diff --git a/script/bbp b/script/bbp new file mode 100755 index 0000000..608ea08 --- /dev/null +++ b/script/bbp @@ -0,0 +1 @@ +[ "Linear", [ [ "Channel", "SLAAR21-LMOT-M521:MOTOR_1.VAL", 165.0, 167.0, 0.25 ] ], [ [ "Channel", "SLAAR21-LSCP1-FNS:CH5:VAL_GET", 400, 0.04, "Enabled" ] ], false, [ ], "", 1, 1.0, 0.0, false, false, true, true, "/photonics/home/gac-bernina/BBOtest/EnergyScan002", "", " ", " ", 0, null, null, "Positioner", false, true ] \ No newline at end of file diff --git a/script/beam_jitter_measurements/demo_histogram.py b/script/beam_jitter_measurements/demo_histogram.py new file mode 100755 index 0000000..63bb3bb --- /dev/null +++ b/script/beam_jitter_measurements/demo_histogram.py @@ -0,0 +1,25 @@ +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator + +CAMERA_NAME = "SARES20-PROF141-M1" +CHANNEL = "intensity" + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) + + +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 diff --git a/script/beam_jitter_measurements/prof_att_histogram.py b/script/beam_jitter_measurements/prof_att_histogram.py new file mode 100755 index 0000000..38bb32a --- /dev/null +++ b/script/beam_jitter_measurements/prof_att_histogram.py @@ -0,0 +1,65 @@ +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator + +CAMERA_NAME = "SAROP21-PPRM138" + + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) + + + +CHANNEL = "intensity" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 + + +CHANNEL = "x_fit_mean" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 + + +CHANNEL = "y_fit_mean" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 \ No newline at end of file diff --git a/script/beam_jitter_measurements/prof_monitor_statistics.py b/script/beam_jitter_measurements/prof_monitor_statistics.py new file mode 100755 index 0000000..aa134ad --- /dev/null +++ b/script/beam_jitter_measurements/prof_monitor_statistics.py @@ -0,0 +1,45 @@ +import ch.psi.utils.swing.SwingUtils as SwingUtils +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator +import ch.psi.pshell.swing.HistogramGeneratorPanel as HistogramGeneratorPanel +from collections import OrderedDict +import javax.swing.border.TitledBorder as TitledBorder +import javax.swing.JPanel as JPanel +import javax.swing.BoxLayout as BoxLayout +import java.awt.Dimension as Dimension + +CHANNELS = ["intensity", + "x_fit_mean", + "y_fit_mean", + "x_fit_standard_deviation", + "y_fit_standard_deviation", + ] + +samples = 2000 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +panels = OrderedDict() + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) + +for channel in CHANNELS: + dev = cam_server.stream.getChild(channel) + hist = HistogramGenerator(CAMERA_NAME + ":" + channel, dev, samples, range_min, range_max, bins) + hist.monitored=True + add_device(hist, True) + pn = HistogramGeneratorPanel() + pn.border=TitledBorder(hist.name) + pn.setShowTitle(True) + pn.setDevice(hist) + pn.setPreferredSize(Dimension(800,150)) + panels[hist.name]=pn + +pn = JPanel() +pn.layout = BoxLayout(pn, BoxLayout.Y_AXIS) +for k in panels.keys(): + pn.add(panels[k]) + +dlg = SwingUtils.showDialog(None, CAMERA_NAME , None, pn) +while(True): + time.sleep(1) diff --git a/script/beam_jitter_measurements/prof_monitor_statistics_debug.py b/script/beam_jitter_measurements/prof_monitor_statistics_debug.py new file mode 100755 index 0000000..25db623 --- /dev/null +++ b/script/beam_jitter_measurements/prof_monitor_statistics_debug.py @@ -0,0 +1,47 @@ +import ch.psi.utils.swing.SwingUtils as SwingUtils +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator +import ch.psi.pshell.swing.HistogramGeneratorPanel as HistogramGeneratorPanel +from collections import OrderedDict +import javax.swing.border.TitledBorder as TitledBorder +import javax.swing.JPanel as JPanel +import javax.swing.BoxLayout as BoxLayout +import java.awt.Dimension as Dimension + +CHANNELS = ["intensity", + "x_fit_mean", + "y_fit_mean", + "x_fit_standard_deviation", + "y_fit_standard_deviation", + ] + +samples = 2000 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +panels = OrderedDict() + +CAMERA_NAME='SAROP21-PPRM138' + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) + +for channel in CHANNELS: + dev = cam_server.stream.getChild(channel) + hist = HistogramGenerator(CAMERA_NAME + ":" + channel, dev, samples, range_min, range_max, bins) + hist.monitored=True + add_device(hist, True) + pn = HistogramGeneratorPanel() + pn.border=TitledBorder(hist.name) + pn.setShowTitle(True) + pn.setDevice(hist) + pn.setPreferredSize(Dimension(800,150)) + panels[hist.name]=pn + +pn = JPanel() +pn.layout = BoxLayout(pn, BoxLayout.Y_AXIS) +for k in panels.keys(): + pn.add(panels[k]) + +dlg = SwingUtils.showDialog(None, CAMERA_NAME , None, pn) +while(True): + time.sleep(1) diff --git a/script/beam_jitter_measurements/prof_mono_histogram.py b/script/beam_jitter_measurements/prof_mono_histogram.py new file mode 100755 index 0000000..64da2d4 --- /dev/null +++ b/script/beam_jitter_measurements/prof_mono_histogram.py @@ -0,0 +1,65 @@ +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator + +#CAMERA_NAME = "SAROP21-PPRM102" +CAMERA_NAME = "SAROP21-PPRM138" + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) + + + +CHANNEL = "intensity" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 + + +CHANNEL = "x_fit_mean" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 + + +CHANNEL = "y_fit_mean" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 \ No newline at end of file diff --git a/script/beam_jitter_measurements/xeye.py b/script/beam_jitter_measurements/xeye.py new file mode 100755 index 0000000..ca3f3e5 --- /dev/null +++ b/script/beam_jitter_measurements/xeye.py @@ -0,0 +1,46 @@ +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator + +CAMERA_NAME = "SARES20-PROF142-M1" + + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) + + + +CHANNEL = "x_fit_standard_deviation" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 + + +CHANNEL = "y_fit_standard_deviation" +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 1000 \ No newline at end of file diff --git a/script/cpython/psss.py b/script/cpython/psss.py new file mode 100755 index 0000000..f92aa4d --- /dev/null +++ b/script/cpython/psss.py @@ -0,0 +1,41 @@ +import numpy as np +from scipy.optimize import curve_fit +import sys + + +def gaus(x, a, x0, sigma, offset): + return offset + a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) + +#Return [amp, mean_val, sigma, offset] +def fit_energy(e_from, e_to, steps, num_shots, data): + energy_range = np.linspace(e_from, e_to, steps) + energy_range_fit = np.linspace(energy_range[0], energy_range[-1], len(energy_range)*10) + centre_line_out = data[:,:,int(data.shape[2]/2)].mean(axis=1) + try: + popt,pcov = curve_fit(gaus,energy_range,centre_line_out,p0=[1,energy_range[np.argmax(centre_line_out)],energy_range.mean()*1e-3,1e3*num_shots]) + except: + raise Exception('Fit failed: spectrum might not be near scan range center \n' + str(sys.exc_info()[1])) + #print('Fit failed: spectrum might not be near scan range center') + #return None + return popt, centre_line_out + + +#Return [amp, mean_val, sigma, offset] +def fit_crystal_height(xstal_from, xstal_to, steps, data): + xstal_range = np.linspace(xstal_from, xstal_to, steps) + projection = data.mean(axis=1).mean(axis=1) + signal_centre = xstal_range[np.argmax(projection)] + xstal_range_fit = np.linspace(xstal_range[0], xstal_range[-1], len(xstal_range)*10) + try: + popt,pcov = curve_fit(gaus,xstal_range,projection,p0=[100,signal_centre,-0.2,100]) + except: + raise Exception('Fit failed: spectrum might not be near scan range center \n' + str(sys.exc_info()[1])) + #print('Fit failed: spectrum might not be near scan range center') + #return None + return popt, projection + + +def get_signal_centre(data, data_range): + projection = data.mean(axis=1).mean(axis=1) + signal_centre = data_range[np.argmax(projection)] + return signal_centre, projection diff --git a/script/cpython/psss_plot.py b/script/cpython/psss_plot.py new file mode 100755 index 0000000..27080e2 --- /dev/null +++ b/script/cpython/psss_plot.py @@ -0,0 +1,32 @@ +import numpy as np +import matplotlib.pyplot as plt + + +def gaus(x, a, x0, sigma, offset): + return offset + a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) + +def plot_energy(E_from, E_to, steps, Scan_spec, popt, measured_offset): + Energy_range = np.linspace(E_from, E_to, steps) + centre_line_out = Scan_spec[:,:,int(Scan_spec.shape[2]/2)].mean(axis=1) + Energy_range_fit = np.linspace(Energy_range[0], Energy_range[-1], len(Energy_range)*10) + + + plt.figure(figsize=[10,5]) + plt.subplot(121) + plt.title('PSSS scan of set photon energy') + plt.pcolormesh(np.arange(0,Scan_spec.shape[2]), Energy_range, Scan_spec.mean(axis=1),cmap='CMRmap') + plt.vlines(int(Scan_spec.shape[2]/2), Energy_range[0], Energy_range[-1],linestyles='--', colors='orange') + plt.xlim([0,Scan_spec.shape[2]]) + plt.xlabel('Camera pixel') + plt.ylabel('Set PSSS energy [eV] \n SARFE10-PSSS059:ENERGY') + + plt.subplot(122) + plt.title('At camera centre pixel %1i \nCalibrated energy = %.1f [eV]\n Offset from machine = %.1f [eV]'%(int(Scan_spec.shape[2]/2),popt[1],measured_offset)) + plt.plot(centre_line_out,Energy_range,linewidth = 2, color = 'orange',label ='measured') + try: + plt.plot(gaus(Energy_range_fit,*popt),Energy_range_fit,'r:',label='fit') + except: + pass + plt.xticks([]) + plt.legend() + plt.grid(True) \ No newline at end of file diff --git a/script/cpython/wrapper.py b/script/cpython/wrapper.py new file mode 100755 index 0000000..5aa4031 --- /dev/null +++ b/script/cpython/wrapper.py @@ -0,0 +1,36 @@ +from jeputils import * + +RELOAD_CPYTHON = not App.isDetached() + +def fit_energy(e_from, e_to, steps, num_shots, data): + data = to_array(data, 'd') + dims = [len(data), len(data[0]), len(data[0][0])] + data = Convert.flatten(data) + arr = to_npa(data, dims) + popt, centre_line_out = call_jep("cpython/psss", "fit_energy", [e_from, e_to, steps, num_shots, arr], reload=RELOAD_CPYTHON) + return popt.getData(), centre_line_out.getData() + +def fit_crystal_height(xstal_from, xstal_to, steps, data): + data = to_array(data, 'd') + dims = [len(data), len(data[0]), len(data[0][0])] + data = Convert.flatten(data) + arr = to_npa(data, dims) + popt, projection = call_jep("cpython/psss", "fit_crystal_height", [xstal_from, xstal_to, steps, arr], reload=RELOAD_CPYTHON) + return popt.getData(), projection.getData() + +def get_signal_centre(data, data_range): + data = to_array(data, 'd') + dims = [len(data), len(data[0]), len(data[0][0])] + data = Convert.flatten(data) + arr = to_npa(data, dims) + data_range = to_npa(to_array(data_range, 'd')) + signal_centre, projection = call_jep("cpython/psss", "get_signal_centre", [arr, data_range], reload=RELOAD_CPYTHON) + return signal_centre, projection.getData() + +def plot_energy(e_from, e_to, steps, data, popt, measured_offset): + data = to_array(data, 'd') + dims = [len(data), len(data[0]), len(data[0][0])] + data = Convert.flatten(data) + arr = to_npa(data, dims) + ret = call_jep("cpython/psss_plot", "plot_energy", [e_from, e_to, steps, arr, popt, measured_offset], reload=RELOAD_CPYTHON) + return ret diff --git a/script/devices/axis.py b/script/devices/axis.py new file mode 100755 index 0000000..d5f6fd6 --- /dev/null +++ b/script/devices/axis.py @@ -0,0 +1,27 @@ +import requests + +def axis_exec(camera, cmd): + if is_string(camera): + camera = get_device(camera) + url = camera.url + s="axis-cgi/" + ctrl_url = url[0:url.find(s) + len(s)] + "com/ptz.cgi?" + cmd_url=ctrl_url+cmd + response = requests.get(url=cmd_url) + if 200<=response.status_code<300: + return response.text.strip() + raise Exception(response.text) + + +def axis_move(camera, direction): + direction=str(direction) + if direction not in ("home", "up", "down", "left", "right", "upleft", "upright", "downleft", "downright", "stop"): + raise Exception("Invalid direction: " + direction) + return axis_exec(camera, "move="+direction) + +def axis_rzoom(camera, steps): + steps= int(steps) + if steps<-9999 or steps>9999: + raise Exception("Invalid relative zoom steps: " + str(steps)) + return axis_exec(camera, "rzoom="+str(steps)) + diff --git a/script/local.groovy b/script/local.groovy new file mode 100755 index 0000000..6cd1527 --- /dev/null +++ b/script/local.groovy @@ -0,0 +1,3 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Deployment specific global definitions - executed after startup.groovy +/////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/script/local.js b/script/local.js new file mode 100755 index 0000000..17db863 --- /dev/null +++ b/script/local.js @@ -0,0 +1,4 @@ +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Deployment specific global definitions - executed after startup.js +/////////////////////////////////////////////////////////////////////////////////////////////////// + diff --git a/script/local.py b/script/local.py new file mode 100755 index 0000000..bf95a49 --- /dev/null +++ b/script/local.py @@ -0,0 +1,222 @@ +################################################################################################### +# Deployment specific global definitions - executed after startup.py +################################################################################################### + +from mathutils import estimate_peak_indexes, fit_gaussians, create_fit_point_list +from mathutils import fit_polynomial,fit_gaussian, fit_harmonic, calculate_peaks, fit_gaussian_offset +from mathutils import PolynomialFunction, Gaussian, HarmonicOscillator, GaussianOffset +from plotutils import plot_function, plot_data + +import java.awt.Color as Color +run("psss/psss") + +################################################################################################### +# DRY RUN +################################################################################################### + +def set_dry_run(value): + global dry_run + dry_run = value + +def is_dry_run(): + if "dry_run" in globals(): + return True if dry_run else False + return False + + +################################################################################################### +# Machine utilities +################################################################################################### + +def is_laser_on(): + return (caget ("SIN-TIMAST-TMA:Beam-Las-Delay-Sel",'d') == 0 ) + +def is_timing_ok(): + return caget("SIN-TIMAST-TMA:SOS-COUNT-CHECK") == 0 + +def get_repetition_rate(): + return caget("SIN-TIMAST-TMA:Evt-15-Freq-I") + + +################################################################################################### +# Shortcut to maths utilities +################################################################################################### + +def gfit(ydata, xdata = None): + """ + Gaussian fit + """ + if xdata is None: + xdata = frange(0, len(ydata), 1) + #ydata = to_list(ydata) + #xdata = to_list(xdata) + max_y= max(ydata) + index_max = ydata.index(max_y) + max_x= xdata[index_max] + print "Max index:" + str(index_max), + print " x:" + str(max_x), + print " y:" + str(max_y) + gaussians = fit_gaussians(ydata, xdata, [index_max,]) + (norm, mean, sigma) = gaussians[0] + p = plot([ydata],["data"],[xdata], title="Fit" )[0] + fitted_gaussian_function = Gaussian(norm, mean, sigma) + scale_x = [float(min(xdata)), float(max(xdata)) ] + points = max((len(xdata)+1), 100) + resolution = (scale_x[1]-scale_x[0]) / points + fit_y = [] + fit_x = frange(scale_x[0],scale_x[1],resolution, True) + for x in fit_x: + fit_y.append(fitted_gaussian_function.value(x)) + p.addSeries(LinePlotSeries("fit")) + p.getSeries(1).setData(fit_x, fit_y) + + if abs(mean - xdata[index_max]) < ((scale_x[0] + scale_x[1])/2): + print "Mean -> " + str(mean) + p.addMarker(mean, None, "Mean="+str(round(norm,2)), Color.MAGENTA.darker()) + return (norm, mean, sigma) + else: + p.addMarker(max_x, None, "Max="+str(round(max_x,2)), Color.GRAY) + print "Invalid gaussian fit: " + str(mean) + return (None, None, None) + + +def hfit(ydata, xdata = None): + """ + Harmonic fit + """ + if xdata is None: + xdata = frange(0, len(ydata), 1) + + max_y= max(ydata) + index_max = ydata.index(max_y) + max_x= xdata[index_max] + + start,end = min(xdata), max(xdata) + (amplitude, angular_frequency, phase) = fit_harmonic(ydata, xdata) + fitted_harmonic_function = HarmonicOscillator(amplitude, angular_frequency, phase) + + print "amplitude = ", amplitude + print "angular frequency = ", angular_frequency + print "phase = ", phase + + f = angular_frequency/ (2* math.pi) + print "frequency = ", f + + resolution = 4.00 # 1.00 + fit_y = [] + for x in frange(start,end,resolution, True): + fit_y.append(fitted_harmonic_function.value(x)) + fit_x = frange(start, end+resolution, resolution) + + p = plot(ydata,"data", xdata, title="HFit")[0] + p.addSeries(LinePlotSeries("fit")) + p.getSeries(1).setData(fit_x, fit_y) + + #m = (phase + math.pi)/ angular_frequency + m = -phase / angular_frequency + if (m timeout/1000: + raise Exception("Timeout waiting for camera server background: " + str(background)) + time.sleep(0.01) + + diff --git a/script/psss/CameraScan.py b/script/psss/CameraScan.py new file mode 100755 index 0000000..7555237 --- /dev/null +++ b/script/psss/CameraScan.py @@ -0,0 +1,63 @@ +#Scan the PSSS camera position +#Purpose: +#To set or confirm the camera is positioned with the measured spectrum in the centre of the spectral integration window + +#If running from editor +if get_exec_pars().source == CommandSource.ui: +#User inputs - define travel range of camera + RANGE_FROM = -17 + RANGE_TO = -11 + STEPS = 20 + NUM_SHOTS= 10 #100 + PLOT=None +p = plot(None, title="Data")[0] if (PLOT is None) else PLOT +p.clear() +p.setLegendVisible(True) + +run("cpython/wrapper") + +if not is_dry_run(): + cam_x=Channel("SARFE10-PSSS059:MOTOR_X5.VAL", name="cam_x") +else: + cam_x=DummyRegister("cam_x") + +av = create_averager(psss_spectrum_y, NUM_SHOTS, interval=-1, name="spectrum_average") +av_samples = av.samples +av_samples.alias = "spectrum_samples" + +#Scan and take data +r = lscan(cam_x, (av, av_samples), RANGE_FROM, RANGE_TO, STEPS, latency=0.0, save=False ) +average, samples, cam_range = r.getReadable(0), r.getReadable(1), r.getPositions(0) + +signal_centre, projection = get_signal_centre(samples, cam_range) + +#Set max position +cam_x.write(signal_centre) +cam_x.close() + + + +""" +plt.figure(figsize=[10,5]) +plt.subplot(121) +plt.title('PSSS scan of camera position') +plt.pcolormesh(np.arange(0,Scan_spec.shape[2]), Cam_range, Scan_spec.mean(axis=1),cmap='CMRmap') +plt.xlim([0,Scan_spec.shape[2]]) +plt.xlabel('Camera pixel dispersive direction') +plt.ylabel('Set PSSS cam_x _pos [mm] \n'+PSSS_cam_x_PV_name[0:-4]) +plt.subplot(122) +plt.plot(projection,Cam_range,linewidth = 2, color = 'orange',label ='projected signal') +plt.title('Spectrum centred at %.1f [mm] (from signal max) \n trace should have hard edges'%signal_centre) +plt.xticks([]) +plt.legend() +plt.grid(True) +""" +#PLOT.clear() +#plot_data(PLOT, projection, "Data", xdata=cam_range, show_points = True, color=Color.BLUE) +#p,pars = plot_gauss_fit(cam_range, projection, gauss_pars=None, p=PLOT, title = "Data") + +plot_data(p, projection, "Projection", xdata=cam_range, show_points = True, color=Color.BLUE) +p.addMarker(signal_centre, None, "Signal Centre=" + str(round(signal_centre,2)), Color.LIGHT_GRAY) + + +set_return(signal_centre) \ No newline at end of file diff --git a/script/psss/CrystalHeightScan.py b/script/psss/CrystalHeightScan.py new file mode 100755 index 0000000..6c3ac73 --- /dev/null +++ b/script/psss/CrystalHeightScan.py @@ -0,0 +1,72 @@ +############################################################################### +#Scan the PSSS crystal height +#Purpose: +#The PSSS signal level is very sensitive to the crystal height. This script will scan the height and set the position to the maximum signal + +if get_exec_pars().source == CommandSource.ui: +#User inputs - define travel range of camera + RANGE_FROM = -0.8 + RANGE_TO = -1.7 + STEPS = 10 #20 + NUM_SHOTS= 10 # 100 + PLOT=None + +if PLOT: + PLOT.clear() + + +run("cpython/wrapper") + + +#Setup and functions setup¶ +if not is_dry_run(): + xstal_height=Channel("ARFE10-PSSS059:MOTOR_Y3.VAL", name="xstal_height") +else: + xstal_height=DummyRegister("xstal_height") + +av = create_averager(psss_spectrum_y, NUM_SHOTS, interval=-1, name="spectrum_average") +av_samples = av.samples +av_samples.alias = "spectrum_samples" + +#Scan and take data +r = lscan(xstal_height, (av, av_samples), RANGE_FROM, RANGE_TO, STEPS, latency=2.0, save=False ) +#User inputs - define travel range of crystal +#It is unlikely these values need to be changed +average, samples, xstal_range = r.getReadable(0), r.getReadable(1), r.getPositions(0) + +#return maxium position +[amp, mean_val, sigma, offset], projection = fit_crystal_height(RANGE_FROM, RANGE_TO, STEPS+1, samples) + + +if not (RANGE_FROM < mean_val < RANGE_TO or RANGE_TO < mean_val < RANGE_FROM): + raise Exception ("Invalid fit mean: " + str(mean_val)) + + +#Set max position +#Cell below will push the maximum position to the xstal height +xstal_height.write(mean_val) +xstal_height.close() + +#Plots +""" +plt.figure(figsize=[10,5]) +plt.subplot(121) +plt.title('PSSS scan of crystal height') +plt.pcolormesh(energy_axis, xstal_range, Scan_spec.mean(axis=1),cmap='CMRmap') +plt.xlim([energy_axis[0],energy_axis[-1]]) +plt.ylim([xstal_range[0], xstal_range[-1]]) +plt.xlabel('PSSS energy axis') +plt.ylabel('Set crystal position [mm] \n'+PSSS_xstal_height_name[0:-4]) +plt.subplot(122) +plt.plot(projection,xstal_range,linewidth = 2, color = 'orange',label ='projected signal') +plt.plot(gaus(xstal_range_fit,*popt),xstal_range_fit,'r:',label='fit') +plt.ylim([xstal_range[0], xstal_range[-1]]) +plt.title('Signal max at %.3f [mm] (from fit)'%popt[1]) +plt.xticks([]) +plt.legend() +plt.grid(True) +""" +plot_gauss_fit(xstal_range, projection, gauss_pars=(offset, amp, mean_val, sigma), p=PLOT, title = "Data") + + +set_return(mean_val) diff --git a/script/psss/EnergyScan.py b/script/psss/EnergyScan.py new file mode 100755 index 0000000..b07ee8d --- /dev/null +++ b/script/psss/EnergyScan.py @@ -0,0 +1,89 @@ +############################################################################### +#Scan the PSSS photon energy +#Purpose: To find and centre the PSSS photon energy so the measured spectrum is centred on the camera chip + +#PARAMETERS +#User inputs - define energy range to scan below by running the appropiate cell +#Below is for a large scan range assuming offset from machine upto $\pm$ 300 eV + +#If running from editor +if get_exec_pars().source == CommandSource.ui: + RANGE_OFF = None + RANGE_FROM = 11100 + RANGE_TO = 11300 + STEPS = 5 #60 + NUM_SHOTS= 10 #100 + PLOT=None + +if RANGE_OFF is not None: + RANGE_FROM = energy_machine.read()-RANGE_OFF + RANGE_TO = energy_machine.read()+RANGE_OFF + +run("cpython/wrapper") + +if PLOT: + PLOT.clear() + + +#Scan and take data +class PSSS_energy(Writable): + def write(self, value): + if not is_dry_run(): + psss_energy.write(value) + exec_cpython("/ioc/modules/qt/PSSS_motion.py", args = ["-m1", "SARFE10-PSSS059"]) + # python / ioc / modules / qt / PSSS_motion.py - m1 SARFE10 - PSSS059 + time.sleep(1) + print(value) + +en = PSSS_energy() +en.alias = "energy" + +av = create_averager(psss_spectrum_y, NUM_SHOTS, interval=-1, name="spectrum_average") +av_samples = av.samples +av_samples.alias = "spectrum_samples" + +r = lscan(en, (av, av_samples), RANGE_FROM, RANGE_TO, STEPS, latency=0.0, save=False ) +average, samples, energy_range = r.getReadable(0), r.getReadable(1), r.getPositions(0) + +[amp, mean_val, sigma, offset],centre_line_out = fit_energy(RANGE_FROM, RANGE_TO, STEPS+1, NUM_SHOTS, samples) + +if not (RANGE_FROM < mean_val < RANGE_TO or RANGE_TO < mean_val < RANGE_FROM): + raise Exception ("Invalid fit mean: " + str(mean_val)) + + +measured_offset = energy_machine.read() - mean_val +#Set fitted energy +print "measured offset", measured_offset + +en.write(mean_val) + + +#Plot +""" +plt.figure(figsize=[10,5]) +plt.subplot(121) +plt.title('PSSS scan of set photon energy') +plt.pcolormesh(np.arange(0,Scan_spec.shape[2]), Energy_range, Scan_spec.mean(axis=1),cmap='CMRmap') +plt.vlines(int(Scan_spec.shape[2]/2), Energy_range[0], Energy_range[-1],linestyles='--', colors='orange') +plt.xlim([0,Scan_spec.shape[2]]) +plt.xlabel('Camera pixel') +plt.ylabel('Set PSSS energy [eV] \n SARFE10-PSSS059:ENERGY') + +plt.subplot(122) +plt.title('At camera centre pixel %1i \nCalibrated energy = %.1f [eV]\n Offset from machine = %.1f [eV]'%(int(Scan_spec.shape[2]/2),popt[1],measured_offset)) +plt.plot(centre_line_out,Energy_range,linewidth = 2, color = 'orange',label ='measured') +plt.plot(gaus(Energy_range_fit,*popt),Energy_range_fit,'r:',label='fit') +plt.xticks([]) +plt.legend() +plt.grid(True) +""" +plot_gauss_fit(energy_range, centre_line_out, gauss_pars=(offset, amp, mean_val, sigma), p=PLOT, title = "Data") + + +set_return(mean_val) + + + + + + diff --git a/script/psss/psss.py b/script/psss/psss.py new file mode 100755 index 0000000..eb80ff9 --- /dev/null +++ b/script/psss/psss.py @@ -0,0 +1,149 @@ +import org.jfree.ui.RectangleAnchor as RectangleAnchor +import org.jfree.ui.TextAnchor as TextAnchor +import ch.psi.pshell.imaging.Overlay as Overlay +import ch.psi.pshell.plot.RangeSelectionPlot as RangeSelectionPlot + + +PSSS_CAMERA_NAME = "SARFE10-PSSS059"; + +def integrate_arrays(arrays): + if arrays is None or (len(arrays)==0): + return None + ret = arrays[0] + for a in arrays[1:]: + ret=arradd(ret, a) + return ret + +def average_arrays(arrays): + ret = integrate_arrays(arrays) + if ret is not None: + s=len(arrays) + ret = [x/s for x in ret] + return ret + +def get_psss_data(average=1): + ax,ay,ac,af=[],[],[],[] + x = psss_spectrum_x.take() + for i in range(average): + y = psss_spectrum_y.take() + center,fwhm = psss_center.take(), psss_fwhm.take() + if average==1: + return x,y,center,fwhm + #ax.append(x) + ay.append(y) + ac.append(center) + af.append(fwhm) + if i < (average-1): + psss_spectrum_y.waitCacheChange(2000) + #psss_center.waitCacheChange(1) + #psss_fwhm.waitCacheChange(1) + #x=average_arrays(ax) + y=average_arrays(ay) + center=mean(ac) + fwhm=mean(af) + return x,y,center,fwhm + +def plot_psss(p, h=None, average = 1): + """ + if len(p.getMarkers())==0: + m1=p.addMarker(0,None,"",Color.WHITE) + m2=p.addMarker(0,None,"",Color.WHITE) + m2.setLabelAnchor(RectangleAnchor.TOP) + else: + m1,m2 = p.getMarkers() + """ + + #Manipulate axis (use PSSS_PLOT for the global object): + #p.getAxis(LinePlot.AxisId.X). + + + if p.getNumberOfSeries()==0: + p.addSeries(LinePlotSeries("spectrum")) + p.addSeries(LinePlotSeries("average")) + p.setLegendVisible(True) + if len(p.getMarkers())==0: + paint = RangeSelectionPlot().getSelectionColor() #p.chart.getBackgroundPaint() + m=p.addIntervalMarker(0,0, None,"", paint) + m.setLabelAnchor(RectangleAnchor.BOTTOM) + m.alpha=0.2 + m.setLabelPaint(Color.WHITE) + else: + m = p.getMarkers()[0] + + x,y, center,fwhm = get_psss_data(average) + if (x is None) or (y is None): + p.getSeries(1).clear() + else: + p.getSeries(1).setData(x,y) + + x,y, _,_ = get_psss_data(1) + if (x is None) or (y is None): + p.getSeries(0).clear() + else: + p.getSeries(0).setData(x,y) + + if (center!= None) and (fwhm!=None): + m.startValue, m.endValue = center - fwhm, center + fwhm + m.label = str(center) + + if h: + if h.getNumberOfSeries()==0: + h.addSeries(TimePlotSeries("center")) + h.addSeries(TimePlotSeries("fwhm",2)) + h.setLegendVisible(True) + h.setTimeAxisLabel("") + h.getSeries(0).appendData(center) + h.getSeries(1).appendData(fwhm) + return center,fwhm + +ovmin, ovmax, ovavg = None, None, None + +def update_psss_image(renderer): + global ovmin, ovmax + #if ovmin: ovmin.update(Point(0,psss_roi_min.take())) + #if ovmax: ovmax.update(Point(0,psss_roi_max.take())) + + + width=psss_spectrum_x.size + if ovmin: ovmin.update(Point(0,psss_roi_min.take()), Point(width, psss_roi_min.take())) + if ovmax: ovmax.update(Point(0,psss_roi_max.take()), Point(width, psss_roi_max.take())) + try: + data = renderer.data + av = "%1.2f" %(data.integrate(False)/data.width/data.height) + except: + av = "" + if ovavg: ovavg.update(av) + +def enable_psss_image(enabled, renderer): + global ovmin, ovmax, ovavg + try: + if (enabled): + #Start or connect to ScreenPanel pipeline + renderer.setDevice(cam_server) + renderer.setProfile(renderer.Profile.Both) + renderer.setShowProfileLimits(False) + + #Changing colormap + #print Colormap.values() #Check values + cam_server.config.colormap=Colormap.Temperature + + + cam_server.start(PSSS_CAMERA_NAME + "_sp", PSSS_CAMERA_NAME + "_sp1") + #ovmin, ovmax= Overlays.Crosshairs(renderer.getPenMarker(), Dimension(-1,1)), \ + # Overlays.Crosshairs(renderer.getPenMarker(), Dimension(-1,1)) + ovmin, ovmax= Overlays.Line(renderer.getPenMarker()), Overlays.Line(renderer.getPenMarker()) + + ovavg = Overlays.Text(Pen(java.awt.Color.GREEN.darker()), "", \ + java.awt.Font("Verdana", java.awt.Font.PLAIN, 12), java.awt.Point(-50,20)) + ovavg.fixed=True + ovavg.anchor=Overlay.ANCHOR_IMAGE_TOP_RIGHT + renderer.addOverlays([ovmin, ovmax, ovavg]) + update_psss_image(renderer) + else: + ovmin, ovmax, ovavg = None, None, None + renderer.setDevice(None) + renderer.clearOverlays() + cam_server.stop() + except: + log(sys.exc_info()[1]) + \ No newline at end of file diff --git a/script/test/demo_histogram.py b/script/test/demo_histogram.py new file mode 100755 index 0000000..a6c5520 --- /dev/null +++ b/script/test/demo_histogram.py @@ -0,0 +1,25 @@ +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator + +CAMERA_NAME = "SARES20-PROF141-M1" +CHANNEL = "intensity" + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) +dev = cam_server.stream.getChild(CHANNEL) +add_device(dev, True) #To see it in Device panel + + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +hist = HistogramGenerator(CAMERA_NAME + "_" + CHANNEL + "_histogram", dev, samples, range_min, range_max, bins) +hist.monitored=True +add_device(hist, True) +show_panel(hist) + + +hist.config.bins = 100 +hist.config.min = float('nan') +hist.config.max = float('nan') +hist.config.numberOfSamples = 100 diff --git a/script/test/demo_histogram2.py b/script/test/demo_histogram2.py new file mode 100755 index 0000000..f3f531c --- /dev/null +++ b/script/test/demo_histogram2.py @@ -0,0 +1,23 @@ +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator + +CAMERA_NAMES = ["SARES20-PROF141-M1"] +CHANNELS = ["intensity", "x_center_of_mass"] + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +for camera_name in CAMERA_NAMES: + cam_server.start(camera_name + "_sp", camera_name + "_sp1") #Start or connect to ScreenPanel pipeline + cam_server.stream.waitCacheChange(2000) + + for channel in CHANNELS: + dev = cam_server.stream.getChild(channel) + hist = HistogramGenerator(camera_name + "_" + channel + "_histogram", dev, samples, range_min, range_max, bins) + hist.monitored=True + add_device(hist, True) + show_panel(hist) + + +while(True): + time.sleep(1) diff --git a/script/test/demo_histogram3.py b/script/test/demo_histogram3.py new file mode 100755 index 0000000..3c971c4 --- /dev/null +++ b/script/test/demo_histogram3.py @@ -0,0 +1,50 @@ +import ch.psi.utils.swing.SwingUtils as SwingUtils +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator +import ch.psi.pshell.swing.HistogramGeneratorPanel as HistogramGeneratorPanel +from collections import OrderedDict +import javax.swing.border.TitledBorder as TitledBorder +import javax.swing.JPanel as JPanel +import javax.swing.BoxLayout as BoxLayout +import java.awt.Dimension as Dimension + +CAMERA_NAMES = ["SARES20-PROF141-M1"] +CHANNELS = ["intensity", + "x_center_of_mass", + "x_fwhm", + "x_rms", + "x_fit_amplitude", + "x_fit_mean", + "x_fit_offset", + "x_fit_standard_deviation", + "x_profile" + ] + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +panels = OrderedDict() +for camera_name in CAMERA_NAMES: + cam_server.start(camera_name + "_sp", camera_name + "_sp1") #Start or connect to ScreenPanel pipeline + cam_server.stream.waitCacheChange(2000) + + for channel in CHANNELS: + dev = cam_server.stream.getChild(channel) + hist = HistogramGenerator(camera_name + ":" + channel, dev, samples, range_min, range_max, bins) + hist.monitored=True + add_device(hist, True) + pn = HistogramGeneratorPanel() + pn.border=TitledBorder(hist.name) + pn.setShowTitle(True) + pn.setDevice(hist) + pn.setPreferredSize(Dimension(800,150)) + panels[hist.name]=pn + +pn = JPanel() +pn.layout = BoxLayout(pn, BoxLayout.Y_AXIS) +for k in panels.keys(): + pn.add(panels[k]) + +dlg = SwingUtils.showDialog(None, "Histograms", None, pn) +while(True): + time.sleep(1) diff --git a/script/test/demo_histogram4.py b/script/test/demo_histogram4.py new file mode 100755 index 0000000..6509edd --- /dev/null +++ b/script/test/demo_histogram4.py @@ -0,0 +1,49 @@ +import ch.psi.utils.swing.SwingUtils as SwingUtils +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator +import ch.psi.pshell.swing.HistogramGeneratorPanel as HistogramGeneratorPanel +from collections import OrderedDict +import javax.swing.border.TitledBorder as TitledBorder +import javax.swing.JPanel as JPanel +import javax.swing.BoxLayout as BoxLayout +import java.awt.Dimension as Dimension + +CHANNELS = ["intensity", + "x_center_of_mass", + "x_fwhm", + "x_rms", + "x_fit_amplitude", + "x_fit_mean", + "x_fit_offset", + "x_fit_standard_deviation", + "x_profile" + ] + +samples = 100 +range_min, range_max = float('nan'),float('nan') +bins = 100 + +panels = OrderedDict() + +cam_server.start(CAMERA_NAME + "_sp", CAMERA_NAME + "_sp1") #Start or connect to ScreenPanel pipeline +cam_server.stream.waitCacheChange(2000) + +for channel in CHANNELS: + dev = cam_server.stream.getChild(channel) + hist = HistogramGenerator(CAMERA_NAME + ":" + channel, dev, samples, range_min, range_max, bins) + hist.monitored=True + add_device(hist, True) + pn = HistogramGeneratorPanel() + pn.border=TitledBorder(hist.name) + pn.setShowTitle(True) + pn.setDevice(hist) + pn.setPreferredSize(Dimension(800,150)) + panels[hist.name]=pn + +pn = JPanel() +pn.layout = BoxLayout(pn, BoxLayout.Y_AXIS) +for k in panels.keys(): + pn.add(panels[k]) + +dlg = SwingUtils.showDialog(None, CAMERA_NAME , None, pn) +while(True): + time.sleep(1) diff --git a/script/test/edwin.py b/script/test/edwin.py new file mode 100755 index 0000000..5c6daaf --- /dev/null +++ b/script/test/edwin.py @@ -0,0 +1,143 @@ +""" +""" +if get_exec_pars().source == CommandSource.ui: + PREFIX = "SLAAR-LBSTREAM1" +if not "VERBOSE" in globals(): + VERBOSE = True +if not "TIME_INTERVAL" in globals(): + TIME_INTERVAL = 1.0 + + +if PREFIX[-1] != ":": + PREFIX = PREFIX + ":" + +def get_channel_list(): + ch=[] + try: + for i in range(20): + v= caget(PREFIX + "NAME" + str(i+1)) + if v.strip()=="": + break + ch.append(str(v.strip())) + except: + pass + return ch + +def ack_channel_list(channel_list): + try: + s="" + for c in channel_list: + s=s+c+"\n" + s=s+"\x00" + caput(PREFIX + "PACK_LIST",[ord(c) for c in s]) + except: + pass + +def start_stream(channel_list): + try: + print "Starting stream" + if len(channel_list)==0: + raise Exception ("No channel defined") + st = Stream("pulse_id", dispatcher) + for c in channel_list: + st.addScalar(c, c, 1, 0) + st.initialize() + st.start() + st.waitCacheChange(10000) #Wait stream be running before starting scan + if st.take() is None: + raise Exception("Error initializing data stream") + print "Stream started" + except: + st=None + print sys.exc_info()[1] + finally: + ack_channel_list(channel_list) + return st + +def stop_stream(st): + try: + if st: + st.close() + st=None + print "Stream closed" + except: + print sys.exc_info()[1] + finally: + ack_channel_list([]) + +#def on_start_change(val): +# fork(start_stream if (val==1) else stop_stream) +#start = Channel(PREFIX + "START_STOP", type = 'i', monitored = True, callback=on_start_change) + +t0=None +def handle_message(msg, channel_list, buf): + global t0 + if t0 is None: + t0 = time.time() + now=time.time() + num_channels = len(channel_list) + size_buffer= 300 #int((len(buf)-100)/(len(channel_list)+1)) + index = int(buf[2])*(num_channels+1) + 10 + buf[index] = msg.pulseId + index = index+1 + for v in msg.values(): + buf[index] = v + index = index+1 + buf[2] = buf[2]+1 + if (now >= (t0 + TIME_INTERVAL)) or (buf[2] == size_buffer): + buf[0] = msg.pulseId + buf[1]= num_channels + buf[3]= buf[2]-1 + if VERBOSE: + print to_list(buf[0:4]) + buf[2] = 0 + t0 = time.time() + return True + return False + +def run(): + channel_list = [] + st=None + start = Channel(PREFIX + "START_STOP", type = 'i') + outp = Channel(PREFIX + "PACK_DATA", type = '[d') + buf = to_array([0]*outp.get_size(),'d') + buf[2]= 0 + + try: + while True: + started = (start.get()==1) + if started and not st: + print "Started" + channel_list=get_channel_list() + print "Channel list: ", channel_list + st = start_stream(channel_list) + + class StreamListener (DeviceListener): + def onValueChanged(self, device, value, former): + if handle_message(value, channel_list, buf): + outp.putq(buf) + + + listener = StreamListener() + st.addListener(listener) + + elif st and not started: + print "Stopped" + channel_list=[] + stop_stream(st) + st = None + """ + if st: + st.waitCacheChange(0) + if handle_message(st.take(), channel_list, buf): + outp.putq(buf) + time.sleep(0.001) + else: + time.sleep(0.1) + """ + time.sleep(0.1) + finally: + stop_stream(st) + if outp: outp.close() + if start: start.close() + diff --git a/script/test/test_cpython.py b/script/test/test_cpython.py new file mode 100644 index 0000000..4e07cf7 --- /dev/null +++ b/script/test/test_cpython.py @@ -0,0 +1,2 @@ +import sys +print (sys.argv) \ No newline at end of file diff --git a/script/test/test_energy_scan.py b/script/test/test_energy_scan.py new file mode 100755 index 0000000..c9aaf19 --- /dev/null +++ b/script/test/test_energy_scan.py @@ -0,0 +1,42 @@ +if get_exec_pars().source == CommandSource.ui: + E_OFF = None + E_FROM = 7200 + E_TO = 7340 + STEPS = 10 + NUM_SHOTS= 3 + PLOT=None + +run("cpython/wrapper") + + +class Positioner(Writable): + def write(self, value): + pass + +av = create_averager(psss_spectrum_y,NUM_SHOTS,interval=-1,name="spectrum_average") +av_samples = av.samples +av_samples.alias = "spectrum_samples" +sensors = (av, av_samples) +#r=tscan(sensors, STEPS, 0.1) +r=lscan(Positioner(),sensors, 10, 10+STEPS, STEPS) +average, samples, pos_range= r.getReadable(0), r.getReadable(1), r.getPositions(0) + + + +#[amp, mean_val, sigma, offset],ydata = fit_energy(E_FROM, E_TO, STEPS +1, NUM_SHOTS, samples) +#[amp, mean_val, sigma, offset],ydata = fit_crystal_height(E_FROM, E_TO, STEPS+1, samples) +#if (mean_val<= E_FROM) or (mean_val>= E_TO): +# raise Exception ("Invalid fit mean: " + str(mean_val)) + +signal_centre, ydata = get_signal_centre(samples, pos_range) + + + + +#plot_gauss_fit(pos_range, ydata, gauss_pars=(offset, amp, mean_val, sigma), p=PLOT, title = "Data") +#plot_gauss_fit(pos_range, ydata, gauss_pars=None, p=PLOT, title = "Data") + +#PLOT.clear() +#plot_data(PLOT, ydata, "Data", xdata=pos_range, show_points = True, color=Color.BLUE) + + diff --git a/script/test/test_psss b/script/test/test_psss new file mode 100755 index 0000000..a2a2bd1 --- /dev/null +++ b/script/test/test_psss @@ -0,0 +1,11 @@ +import org.jfree.ui.RectangleAnchor as RectangleAnchor +import org.jfree.ui.TextAnchor as TextAnchor +p=plot(None)[0] +m1=p.addMarker(0,None,"",Color.WHITE) +m2=p.addMarker(0,None,"",Color.WHITE) +m2.setLabelAnchor(RectangleAnchor.TOP) +while True: + p.getSeries(0).setData(psss_spectrum_x.take(), psss_spectrum_y.take()) + m1.value, m2.value = psss_center.take() - psss_fwhm.take(),psss_center.take() + psss_fwhm.take() + m2.label = str(psss_center.take()) + time.sleep(1.0) \ No newline at end of file diff --git a/script/test/test_psss.py b/script/test/test_psss.py new file mode 100755 index 0000000..cdd44e9 --- /dev/null +++ b/script/test/test_psss.py @@ -0,0 +1,13 @@ + +p=plot(None)[0] + + +while True: + plot_psss(p) + time.sleep(1.0) + + + + + + \ No newline at end of file diff --git a/script/test/test_screenpanel_pipeline.py b/script/test/test_screenpanel_pipeline.py new file mode 100755 index 0000000..3cf989e --- /dev/null +++ b/script/test/test_screenpanel_pipeline.py @@ -0,0 +1,17 @@ +import ch.psi.pshell.device.HistogramGenerator as HistogramGenerator + +cam_server.start("SARES20-PROF141-M1_sp", "SARES20-PROF141-M1_sp1") + +channels = ["intensity", + "x_center_of_mass", + "x_fwhm", + "x_rms", + "x_fit_amplitude", + "x_fit_mean", + "x_fit_offset", + "x_fit_standard_deviation", + "x_profile" + ] +for channel in channels: + dev = cam_server.stream.getChild(channel) + add_device(dev, True) diff --git a/script/test/test_stream.py b/script/test/test_stream.py new file mode 100755 index 0000000..d696ba0 --- /dev/null +++ b/script/test/test_stream.py @@ -0,0 +1,43 @@ +import ch.psi.pshell.bs.DispatcherConfig.Incomplete as Incomplete +channels = ["SAROP11-PBPS117:INTENSITY", \ +"SAROP11-PBPS117:XPOS", \ +"SAROP11-PBPS117:YPOS", \ +"SLG-LSCP2-FNS:CH0:VAL_GET", \ +"SINEG01-DBPM340:Q1", \ +"SINEG01-DBPM340:X1", \ +"SINEG01-DBPM340:Y1", \ +"SINEG01-DBPM340:Q2", \ +"S20SY02-DBPM150:Q1", \ +"SINEG01-DBPM340:X2", \ +"SINEG01-DBPM340:Y2", \ +"SLG-LSCP2-FNS:CH0:VAL_GET"] + + +channels = [ \ + "SINEG01-DBPM340:X2", \ + "S20SY02-DBPM150:Q1", \ + "SLG-LSCP2-FNS:CH0:VAL_GET" \ + ] + +#channels = ["SLG-LSCP2-FNS:CH0:VAL_GET"] + +dispatcher.config.mappingIncomplete=None +dispatcher.config.mappingIncomplete = Incomplete.fill_null +#dispatcher.config.mappingIncomplete = Incomplete.provide_as_is +#dispatcher.config.mappingIncomplete = Incomplete.drop +s1 = Stream("s1", dispatcher) +s1.initialize() +for c in channels: + s1.addScalar(c,c, 1, 0) +s1.addScalar("SINEG01-DBPM340:Q2","SINEG01-DBPM340:Q2", 1, 0) + +add_device(s1, True) + +s1.start() +s1.waitCacheChange(5000) + +for i in range(20): + print s1.take().keys(), s1.take().values() + s1.waitCacheChange(5000) + +#ret = bscan (s1, 20, None, save=False) \ No newline at end of file diff --git a/script/users/edwin/correlation_stream.py b/script/users/edwin/correlation_stream.py new file mode 100755 index 0000000..597b226 --- /dev/null +++ b/script/users/edwin/correlation_stream.py @@ -0,0 +1,163 @@ +""" +Run as: +pshell_be -l -test -c -f="users/edwin/correlation_stream.py" -args="PREFIX:'SLAAR-LBSTREAM1'" + +or with additional parameters: +pshell_be -l -test -c -f="users/edwin/correlation_stream.py" -args="PREFIX:'SLAAR-LBSTREAM1',VERBOSE:False,TIME_INTERVAL:2.0" +""" + +if not "PREFIX" in globals(): + PREFIX = "SLAAR-LBSTREAM1" +if not "VERBOSE" in globals(): + VERBOSE = False +if not "TIME_INTERVAL" in globals(): + TIME_INTERVAL = 1.0 + +EMPTY_VALUE = 1112223330 + + +if PREFIX[-1] != ":": + PREFIX = PREFIX + ":" + +def get_channel_list(): + ch=[] + try: + for i in range(20): + v= caget(PREFIX + "NAME" + str(i+1)) + if v.strip()=="": + break + ch.append(str(v.strip())) + except: + pass + return ch + +def ack_channel_list(channel_list): + try: + s="" + for c in channel_list: + s=s+c+"\n" + s=s+"\x00" + caput(PREFIX + "PACK_LIST",[ord(c) for c in s]) + except: + pass + +def start_stream(channel_list): + try: + st=None + print "Starting stream" + if len(channel_list)==0: + raise Exception ("No channel defined") + st = Stream("pulse_id", dispatcher) + for c in channel_list: + st.addScalar(c, c, 1, 0) + st.initialize() + st.start() + st.waitCacheChange(10000) #Wait stream be running before starting scan + if st.take() is None: + raise Exception("Error initializing data stream") + ack_channel_list(channel_list) + print "Stream started" + except: + stop_stream(st) + st=None + print sys.exc_info()[1] + return st + +def stop_stream(st): + try: + if st: + st.close() + st=None + print "Stream closed" + except: + print sys.exc_info()[1] + finally: + ack_channel_list([]) + +#def on_start_change(val): +# fork(start_stream if (val==1) else stop_stream) +#start = Channel(PREFIX + "START_STOP", type = 'i', monitored = True, callback=on_start_change) + +t0=None +pid=None +def handle_message(msg, channel_list, buf): + global t0, pid + if t0 is None: + t0 = time.time() + now=time.time() + num_channels = len(channel_list) + size_buffer= 300 #int((len(buf)-100)/(len(channel_list)+1)) + buf[0] = msg.pulseId + buf[1] = num_channels + buf[4] = EMPTY_VALUE + #if (pid is not None) and ((pid+1) != msg.pulseId): + # print "Missing pid: ", (pid+1) + pid = msg.pulseId + #Count + if buf[2] < size_buffer: + buf[2] = buf[2]+1 + #Index + buf[3] = buf[3]+1 + if buf[3] == size_buffer: + buf[3]=0 + index = int(buf[3])*(num_channels+1) + 10 + buf[index] = msg.pulseId + index = index+1 + for v in msg.values(): + buf[index] = EMPTY_VALUE if ((v is None) or (math.isnan(v)))else v + index = index+1 + if now >= (t0 + TIME_INTERVAL): + if VERBOSE: + print to_list(buf[0:5]) + t0 = time.time() + return True + return False + +def run(): + channel_list = [] + st=None + start = Channel(PREFIX + "START_STOP", type = 'i') + outp = Channel(PREFIX + "PACK_DATA", type = '[d') + buf = to_array([0]*outp.get_size(),'d') + buf[2] = 0 + buf[3]= -1 + + try: + while True: + started = (start.get()==1) + if started and not st: + print "Started" + channel_list=get_channel_list() + print "Channel list: ", channel_list + st = start_stream(channel_list) + if st is not None: + class StreamListener (DeviceListener): + def onValueChanged(self, device, value, former): + if handle_message(value, channel_list, buf): + outp.putq(buf) + listener = StreamListener() + st.addListener(listener) + + elif st and not started: + print "Stopped" + channel_list=[] + stop_stream(st) + st = None + """ + if st: + st.waitCacheChange(0) + if handle_message(st.take(), channel_list, buf): + outp.putq(buf) + time.sleep(0.001) + else: + time.sleep(0.1) + """ + time.sleep(0.1) + finally: + stop_stream(st) + if outp: outp.close() + if start: start.close() + + +if __name__ == "__main__": + run() \ No newline at end of file