diff --git a/slsDetectorGui/.gitignore b/slsDetectorGui/.gitignore new file mode 100644 index 0000000000..8626cc9e54 --- /dev/null +++ b/slsDetectorGui/.gitignore @@ -0,0 +1,5 @@ +Makefile.gui +forms/include/ +mocs/ +objs/ +qrc_icons.cpp diff --git a/slsDetectorGui/CMakeLists.txt b/slsDetectorGui/CMakeLists.txt new file mode 100644 index 0000000000..0178b95365 --- /dev/null +++ b/slsDetectorGui/CMakeLists.txt @@ -0,0 +1,130 @@ + +set(CMAKE_AUTOMOC ON) + +set(SOURCES + slsDetectorPlotting/src/SlsQt1DPlot.cxx + slsDetectorPlotting/src/SlsQt1DZoomer.cxx + slsDetectorPlotting/src/SlsQt2DHist.cxx + slsDetectorPlotting/src/SlsQt2DPlot.cxx + slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx + slsDetectorPlotting/src/SlsQtNumberEntry.cxx + src/qDetectorMain.cpp + src/qDrawPlot.cpp + src/qCloneWidget.cpp + src/qTabMeasurement.cpp + src/qTabDataOutput.cpp + src/qTabPlot.cpp + src/qTabActions.cpp + src/qActionsWidget.cpp + src/qScanWidget.cpp + src/qTabAdvanced.cpp + src/qTabSettings.cpp + src/qTabDebugging.cpp + src/qTabDeveloper.cpp + src/qTabMessages.cpp + src/qServer.cpp +) + +set(FORMS + forms/form_detectormain.ui + forms/form_tab_measurement.ui + forms/form_tab_dataoutput.ui + forms/form_tab_plot.ui + forms/form_tab_advanced.ui + forms/form_tab_settings.ui + forms/form_tab_debugging.ui + forms/form_action.ui + forms/form_scan.ui +) + +qt4_wrap_ui(FORMS_H ${FORMS}) + +set(HEADERS + slsDetectorPlotting/include/SlsQt1DPlot.h + slsDetectorPlotting/include/SlsQt1DZoomer.h + slsDetectorPlotting/include/SlsQt2DHist.h + slsDetectorPlotting/include/SlsQt2DPlot.h + slsDetectorPlotting/include/SlsQt2DPlotLayout.h + slsDetectorPlotting/include/SlsQt2DZoomer.h + slsDetectorPlotting/include/SlsQtValidators.h + slsDetectorPlotting/include/SlsQtNumberEntry.h + include/qDefs.h + include/qDebugStream.h + include/qDetectorMain.h + include/qDrawPlot.h + include/qCloneWidget.h + include/qTabMeasurement.h + include/qTabDataOutput.h + include/qTabPlot.h + include/qTabActions.h + include/qActionsWidget.h + include/qScanWidget.h + include/qTabAdvanced.h + include/qTabSettings.h + include/qTabDebugging.h + include/qTabDeveloper.h + include/qTabMessages.h + include/gitInfoGui.h + include/qServer.h +) +set(RESOURCES + include/icons.qrc +) +qt4_add_resources(RESOURCES_SRCS ${RESOURCES}) + +include_directories( + include + slsDetectorPlotting/include + ../slsDetectorSoftware/commonFiles + ../slsDetectorSoftware/slsReceiverInterface + ../slsDetectorSoftware/slsDetector + ../slsDetectorSoftware/slsDetectorAnalysis + ../slsDetectorSoftware/multiSlsDetector + ../slsDetectorSoftware/usersFunctions + ../slsReceiverSoftware/include + ${QT_INCLUDE_DIR} + ${QT_QTCORE_INCLUDE_DIR} + ${QT_QTGUI_INCLUDE_DIR} + ${QWT_INCLUDE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} +) + +add_definitions( + -DDACS_INT -DVERBOSE -DPRINT_LOG +) + +add_executable(slsDetectorGui + ${SOURCES} + ${HEADERS} + ${FORMS_H} + ${RESOURCES_SRCS} +) + +set_target_properties(slsDetectorGui PROPERTIES + LINKER_LANGUAGE CXX + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +) + +add_library(zmq STATIC IMPORTED ) + +set_target_properties(zmq PROPERTIES + IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/../slsReceiverSoftware/include/libzmq.a +) + +target_link_libraries(slsDetectorGui + slsDetectorShared + ${QT_QTCORE_LIBRARIES} + ${QT_QTGUI_LIBRARIES} + ${QWT_LIBRARIES} + pthread + zmq + rt +) + +add_executable(gui_client + client/qClient.h + client/qClient.cpp +) +set_target_properties(gui_client PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +) diff --git a/slsDetectorGui/Makefile b/slsDetectorGui/Makefile new file mode 100644 index 0000000000..31fbd936fd --- /dev/null +++ b/slsDetectorGui/Makefile @@ -0,0 +1,59 @@ +# LEO: Won't compile without libSlsDetector + +include ../Makefile.include + +$(info ) +$(info ##################################) +$(info # Compiling slsDetectorGui #) +$(info ##################################) +$(info ) + + + +PROG = $(DESTDIR)/slsDetectorGui + +DESTDIR ?= ../bin +LIBDIR ?= $(DESTDIR) +DOCDIR ?= docs + +LIBRARYDIR ?= ../slsDetectorSoftware +LIBRARYRXRDIR ?= ../slsReceiverSoftware +INCLUDES ?= $(LIBRARYDIR)/commonFiles -I$(LIBRARYRXRDIR)/MySocketTCP -I$(LIBRARYDIR)/slsReceiverInterface -I$(LIBRARYDIR)/slsDetector -I$(LIBRARYDIR)/slsDetectorAnalysis -I$(LIBRARYDIR)/multiSlsDetector -I$(LIBRARYDIR)/usersFunctions -I$(LIBRARYRXRDIR)/includes + +#ifeq ( $(EIGERSLS), yes) +# LDFLAG += $(EIGERFLAGS) +#else ifeq ( $(ROOTSLS), yes) +# LDFLAG += $(ROOTFLAGS) +#endif + +.PHONY: all lib clean mm doc htmldoc guiclient + + +all: lib $(PROG) Makefile.gui guiclient + +lib: + cd ../ && $(MAKE) lib + +clean: + if test -e Makefile.gui; then $(MAKE) -f Makefile.gui clean; $(MAKE) -f Makefile.gui mocclean; rm Makefile.gui; else $(MAKE) Makefile.gui; $(MAKE) -f Makefile.gui clean; $(MAKE) -f Makefile.gui mocclean; fi + cd client && $(MAKE) clean +# cd manual && make clean + + +Makefile.gui: mm + +mm: + qmake -set QT_INSTALL_PREFIX $(QTDIR) && qmake -o Makefile.gui INCLUDES='$(INCLUDES)' DESTDIR=$(DESTDIR) SLSDETLIB=$(LIBDIR) SUBLIBS='$(LDFLAGDET)' + +doc: + cd manual && $(MAKE) DESTDIR=$(DOCDIR) + +htmldoc: + cd manual && $(MAKE) html DESTDIR=$(DOCDIR) + +$(PROG): Makefile.gui $(DIR) + $(MAKE) -f Makefile.gui SLSDETLIB=$(LIBDIR) DESTDIR=$(DESTDIR) SUBLIBS='$(LDFLAGDET)' INCLUDES='$(INCLUDES)' + +guiclient: + echo $(WD) + cd client && $(MAKE) DESTDIR=$(DESTDIR) diff --git a/slsDetectorGui/client/Makefile b/slsDetectorGui/client/Makefile new file mode 100644 index 0000000000..5545785fa8 --- /dev/null +++ b/slsDetectorGui/client/Makefile @@ -0,0 +1,36 @@ +CC = g++ +CLAGS += -DVERBOSE #VERYBOSE +LDLIBS += -lm -lstdc++ -lpthread + +LDIR = ../../slsDetectorSoftware +RDIR = ../../slsReceiverSoftware + +INCLUDES = -I $(LDIR)/commonFiles -I $(LDIR)/slsDetector -I ../include -I $(RDIR)/include +SRC_CLNT = qClient.cpp $(RDIR)/src/MySocketTCP.cpp + +PROGS = gui_client +DESTDIR ?= bin +INSTMODE = 0777 + +FINALDIR = ../../bin + +OBJS = $(SRC_CLNT:.cpp=.o) + + +all: clean $(PROGS) + +boot: $(OBJS) + +$(PROGS): + echo $(OBJS) + mkdir -p $(DESTDIR) + gcc $(SRC_CLNT) $(INCLUDES) $(FLAGS) $(LDLIBS) -o $@ + mv $(PROGS) $(FINALDIR) + +clean: + rm -rf $(DESTDIR)/$(PROGS) *.o $(FINALDIR)/$(PROGS) + + + + + diff --git a/slsDetectorGui/client/qClient.cpp b/slsDetectorGui/client/qClient.cpp new file mode 100644 index 0000000000..1583bae528 --- /dev/null +++ b/slsDetectorGui/client/qClient.cpp @@ -0,0 +1,234 @@ +/* + * qClient.cpp + * + * Created on: Feb 27, 2013 + * Author: Dhanya Maliakal + */ +// Qt Project Class Headers +#include "qClient.h" +// Project Class Headers +#include "MySocketTCP.h" +#include "slsDetectorBase.h" + +// C++ Include Headers +#include +#include +using namespace std; + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int main(int argc, char *argv[]){ + + qClient *cl =new qClient(argv[1]); + cl->executeLine(argc-2, argv+2); + + delete cl; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qClient::qClient(char* hostname){ + //create socket + mySocket = new MySocketTCP(hostname, DEFAULT_GUI_PORTNO); + if (mySocket->getErrorStatus()){ + cout << "Error: could not connect to host:" << hostname << " with port " << DEFAULT_GUI_PORTNO << endl; + delete mySocket; + exit(-1); + } + + //create socket to connect to stop server + myStopSocket = new MySocketTCP(hostname, DEFAULT_GUI_PORTNO+1); + if (myStopSocket->getErrorStatus()){ + cout << "Error: could not connect to host:" << hostname << " with port " << DEFAULT_GUI_PORTNO + 1 << endl; + delete myStopSocket; + exit(-1); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +qClient::~qClient() { + if(mySocket) delete mySocket; + if(myStopSocket) delete myStopSocket; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qClient::executeLine(int narg, char *args[]){ + + char arg[MAX_STR_LENGTH] = ""; + int iarg = -1; + char answer[100]; + string retval = ""; + string cmd = args[0]; + string argument; + + + //validate command structure + if(narg<1){ + cout << "Error: no command parsed" << endl; + return FAIL; + } + + + //help + if (cmd == "help"){ + retval = printCommands(); + } + + //file name + else if (cmd == "status"){ + + if(narg>1){ + argument = args[1]; + //start acquisition + if(argument == "start") + startAcquisition(); + else if (argument == "stop") + stopAcquisition(); + else{ + cout << "Error: could not parse arguments: " << argument << endl; + printCommands(); + return FAIL; + } + } + retval = getStatus(); + } + + + else if (cmd == "acquire"){ + startAcquisition(true); + retval = getStatus(); + } + + + else if (cmd == "exit"){ + return exitServer(); + } + + + //unrecognized command + else{ + cout << "Error: unrecognized command" << endl; + return FAIL; + } + + + //print result + cout << cmd << ": " << retval << endl; + + return OK; +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +string qClient::printCommands(){ + ostringstream os; + os << "\nexit \t exits servers in gui" << std::endl; + os << "status \t gets status of acquisition in gui. - can be running or idle" << std::endl; + os << "status i starts/stops acquistion in gui-non blocking. i is start or stop" << std::endl; + os << "acquire starts acquistion in gui-blocking" << std::endl; + return os.str(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +string qClient::getStatus(){ + int fnum = F_GET_RUN_STATUS; + int ret = FAIL; + runStatus retval=ERROR; + int progress = 0; + char answer[100]; + + if (myStopSocket->Connect() >= 0) { + myStopSocket->SendDataOnly(&fnum,sizeof(fnum)); + myStopSocket->ReceiveDataOnly(&ret,sizeof(ret)); + myStopSocket->ReceiveDataOnly(&retval,sizeof(retval)); + myStopSocket->ReceiveDataOnly(&progress,sizeof(progress)); + myStopSocket->Disconnect(); + }else + exit(-1); + + + sprintf(answer,"%d%% ",progress); + strcat(answer,slsDetectorBase::runStatusType((runStatus)retval).c_str()); + + return string(answer); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qClient::startAcquisition(bool blocking){ + int fnum = F_START_ACQUISITION; + if(blocking) fnum = F_START_AND_READ_ALL; + int ret = FAIL; + + if (mySocket->Connect() >= 0) { + mySocket->SendDataOnly(&fnum,sizeof(fnum)); + mySocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret == FAIL){ + mySocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Gui returned error: " << mess << std::endl; + } + mySocket->Disconnect(); + }else + exit(-1); + + return ret; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qClient::stopAcquisition(){ + int fnum = F_STOP_ACQUISITION; + int ret = FAIL; + + if (myStopSocket->Connect() >= 0) { + myStopSocket->SendDataOnly(&fnum,sizeof(fnum)); + myStopSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret == FAIL){ + myStopSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Gui returned error: " << mess << std::endl; + } + myStopSocket->Disconnect(); + }else + exit(-1); + + return ret; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qClient::exitServer(){ + int fnum = F_EXIT_SERVER; + int ret = FAIL; + + if (myStopSocket->Connect() >= 0) { + myStopSocket->SendDataOnly(&fnum,sizeof(fnum)); + myStopSocket->ReceiveDataOnly(&ret,sizeof(ret)); + myStopSocket->ReceiveDataOnly(mess,sizeof(mess)); + cout << mess << endl; + myStopSocket->Disconnect(); + }else + exit(-1); + + return ret; +} diff --git a/slsDetectorGui/client/qClient.h b/slsDetectorGui/client/qClient.h new file mode 100644 index 0000000000..fbec87a95d --- /dev/null +++ b/slsDetectorGui/client/qClient.h @@ -0,0 +1,65 @@ +/* + * qClient.h + * + * Created on: Feb 27, 2013 + * Author: Dhanya Maliakal + */ +#ifndef QCLIENT_H +#define QCLIENT_H + + +/** Qt Project Class Headers */ +/** Project Class Headers */ +class MySocketTCP; +#include "sls_detector_defs.h" +/** C++ Include Headers */ +#include +#include +using namespace std; + +/** + *@short Sets up the gui server + */ +class qClient: public virtual slsDetectorDefs{ + + +public: + /** \short The constructor*/ + qClient(char* hostname); + /** Destructor */ + virtual ~qClient(); + + /**Execute command*/ + int executeLine(int narg, char *args[]); + +private: + /** Print list of commands */ + string printCommands(); + + /** Start Acquisition + * @param blocking true if its a blocking acquistion + */ + int startAcquisition(bool blocking = false); + + /** Stops Acquisition */ + int stopAcquisition(); + + /** Gets run status */ + string getStatus(); + + /** Exits Server */ + int exitServer(); + + /** client socket */ + MySocketTCP *mySocket; + + /** client socket */ + MySocketTCP *myStopSocket; + + char mess[MAX_STR_LENGTH]; + +}; + + + +#endif /* QCLIENT_H */ diff --git a/slsDetectorGui/doxy.config b/slsDetectorGui/doxy.config new file mode 100644 index 0000000000..877d4c456e --- /dev/null +++ b/slsDetectorGui/doxy.config @@ -0,0 +1,106 @@ +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = YES + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = YES + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +INPUT = \ + slsDetectorPlotting/include/SlsQt1DPlot.h\ + slsDetectorPlotting/src/SlsQt1DPlot.cxx + slsDetectorPlotting/include/SlsQt1DZoomer.h\ + slsDetectorPlotting/src/SlsQt1DZoomer.cxx\ + slsDetectorPlotting/include/SlsQt2DHist.h\ + slsDetectorPlotting/src/SlsQt2DHist.cxx\ + slsDetectorPlotting/include/SlsQt2DPlot.h\ + slsDetectorPlotting/src/SlsQt2DPlot.cxx\ + slsDetectorPlotting/include/SlsQt2DPlotLayout.h\ + slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx\ + slsDetectorPlotting/include/SlsQtNumberEntry.h\ + slsDetectorPlotting/src/SlsQtNumberEntry.cxx\ + slsDetectorPlotting/include/SlsQt2DZoomer.h\ + slsDetectorPlotting/include/SlsQtValidators.h\ + include/qDetectorMain.h\ + src/qDetectorMain.cpp\ + include/qDrawPlot.h\ + src/qDrawPlot.cpp\ + include/qCloneWidget.h\ + src/qCloneWidget.cpp\ + include/qTabMeasurement.h\ + src/qTabMeasurement.cpp\ + include/qTabDataOutput.h\ + src/qTabDataOutput.cpp\ + include/qTabPlot.h\ + src/qTabPlot.cpp\ + include/qTabActions.h\ + src/qTabActions.cpp\ + include/qActionsWidget.h\ + src/qActionsWidget.cpp\ + include/qScanWidget.h\ + src/qScanWidget.cpp\ + include/qTabAdvanced.h\ + src/qTabAdvanced.cpp\ + include/qTabSettings.h\ + src/qTabSettings.cpp\ + include/qTabDebugging.h\ + src/qTabDebugging.cpp\ + include/qTabDeveloper.h\ + src/qTabDeveloper.cpp\ + include/qDefs.h + + +OUTPUT_DIRECTORY = docs + diff --git a/slsDetectorGui/forms/form_action.ui b/slsDetectorGui/forms/form_action.ui new file mode 100644 index 0000000000..33d93c35e9 --- /dev/null +++ b/slsDetectorGui/forms/form_action.ui @@ -0,0 +1,169 @@ + + + ActionsObject + + + + 0 + 0 + 680 + 25 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 1000 + + + + Form + + + + 0 + + + 0 + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + None + + + + + Custom Script + + + + + + + + false + + + + + + + false + + + Additional Parameter: + + + + + + + false + + + Browse + + + + :/icons/images/browse.png:/icons/images/browse.png + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 5 + 20 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 5 + 20 + + + + + + + + false + + + + 0 + 0 + + + + + + + + + + + diff --git a/slsDetectorGui/forms/form_detectormain.ui b/slsDetectorGui/forms/form_detectormain.ui new file mode 100644 index 0000000000..1cdc2001bb --- /dev/null +++ b/slsDetectorGui/forms/form_detectormain.ui @@ -0,0 +1,521 @@ + + + DetectorMainObject + + + true + + + + 0 + 0 + 800 + 848 + + + + + 0 + 0 + + + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + 0 + 0 + 0 + + + + + + + + + 185 + 185 + 185 + + + + + + + 185 + 185 + 185 + + + + + + + 185 + 185 + 185 + + + + + + + 89 + 89 + 89 + + + + + + + + + 9 + + + + SLS Detector GUI + + + Qt::ImhNone + + + false + + + QTabWidget::Rounded + + + false + + + + + 0 + 0 + + + + + 0 + 395 + + + + + 524287 + 395 + + + + + + + 0 + 0 + 800 + 25 + + + + + 0 + 0 + + + + + 0 + 25 + + + + + 16777215 + 25 + + + + + 9 + + + + Qt::StrongFocus + + + false + + + true + + + + + 9 + + + + &Utilities + + + + + + + + + + + + + + + + &Modes + + + + + + + + + &Help + + + + + + + + + + true + + + + 0 + 0 + + + + + 36 + 422 + + + + + 524287 + 524287 + + + + + Sans Serif + 11 + 50 + false + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> +<table border="0" style="-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;"> +<tr> +<td style="border: none;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#00007f;">Left Click :zoom in</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#00007f;">Righ</span><span style=" color:#00007f;">t Click </span><span style=" color:#00007f;">: zoom out by 1</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#00007f;">Middle Click : panning</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#00007f;">Ctrl+Right Click : zoom out to full size</span></p></td></tr></table></body></html> + + + + + + Qt::LeftToRight + + + QDockWidget::NoDockWidgetFeatures + + + Qt::BottomDockWidgetArea + + + SLS Detector Plot + + + 8 + + + + + 0 + 0 + + + + + 0 + 400 + + + + + 16777215 + 16777215 + + + + + + + + + 0 + 0 + 0 + + + + + + + + + 0 + 0 + 0 + + + + + + + + + 119 + 119 + 119 + + + + + + + + + 9 + 50 + false + + + + + + + &Load &Setup + + + + + + + + &Save &Setup + + + + + + + + &Measurement Wizard + + + + + &Load &Configuration + + + + + &Save &Configuration + + + + + &Energy Calibration + + + + + &Angular Calibration + + + + + true + + + false + + + &Debug + + + + + true + + + false + + + &Beamline + + + + + true + + + false + + + &Expert + + + + + true + + + false + + + &Configuration + + + + + &Version + + + + + &About + + + + + true + + + D&ockable Windows + + + + + &Load &Trimbits + + + + + &Save &Trimbits + + + + + &Load C&alibration + + + + + &Save C&alibration + + + + + true + + + &Listen to Gui Client + + + + + + diff --git a/slsDetectorGui/forms/form_scan.ui b/slsDetectorGui/forms/form_scan.ui new file mode 100644 index 0000000000..bd00b8c6e0 --- /dev/null +++ b/slsDetectorGui/forms/form_scan.ui @@ -0,0 +1,488 @@ + + + ScanObject + + + + 0 + 0 + 724 + 125 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 1000 + + + + Form + + + + 0 + + + 5 + + + 0 + + + + + false + + + + 0 + 0 + + + + + 180 + 0 + + + + + + + + 0 + + + 5 + + + 0 + + + 2 + + + 0 + + + 5 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + <nobr> +Defines scan range for a <b>Constant Step Size</b> with the following constraints: +</nobr><br><nobr> +1. <b>Number of Steps</b> >=2. +</nobr><br><nobr> +2. <b>Size</b> not equal to 0. +</nobr><br><nobr> +3. <b>From</b> not equal to <b>To</b>. +</nobr><br> + + + Constant Step Size + + + true + + + + + + + <nobr>Measures only at specific values listed by the user.</nobr><br> +<nobr>Number of entries is restricted to <b>Number of Steps</b> field.</nobr> + + + Specific Values + + + false + + + + + + + + 0 + 0 + + + + <nobr>Measures only at the specific values listed in a file.</nobr><br> +<nobr>Select the file, where these values are listed.</nobr> + + + Values from File + + + false + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + + + + + + + + + + + + 0 + + + + + false + + + + 0 + 0 + + + + Precision: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 5 + 20 + + + + + + + + false + + + + 0 + 0 + + + + 0 + + + 10 + + + 0 + + + + + + + + + 0 + + + + + false + + + + 0 + 0 + + + + Additional Parameter: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 5 + 20 + + + + + + + + false + + + + 0 + 0 + + + + + + + + + + 0 + + + + + false + + + + 0 + 0 + + + + Number of Steps: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 5 + 20 + + + + + + + + false + + + + 0 + 0 + + + + false + + + 0 + + + 1000000 + + + 0 + + + + + + + + + + None + + + + + Energy Scan (eV) + + + + + Threshold Scan + + + + + Trimbits Scan + + + + + Position Scan + + + + + Custom Script + + + + + + + + 0 + + + + + false + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 5 + 20 + + + + + + + + false + + + Browse + + + + :/icons/images/browse.png:/icons/images/browse.png + + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 30 + 20 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + comboScript + dispScript + btnBrowse + dispParameter + spinSteps + spinPrecision + radioRange + radioCustom + radioFile + + + + + + diff --git a/slsDetectorGui/forms/form_tab_advanced.ui b/slsDetectorGui/forms/form_tab_advanced.ui new file mode 100644 index 0000000000..227ecd3e62 --- /dev/null +++ b/slsDetectorGui/forms/form_tab_advanced.ui @@ -0,0 +1,1606 @@ + + + TabAdvancedObject + + + + 0 + 0 + 775 + 351 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 1000 + + + + Form + + + + :/icons/images/refresh.png:/icons/images/refresh.png + + + + + 5 + 3 + 761 + 343 + + + + + + + QTabWidget::North + + + 1 + + + Qt::ElideLeft + + + + Logs + + + + + 5 + 10 + 746 + 66 + + + + Calibration Logs + + + + + 25 + 20 + 320 + 31 + + + + + 42 + + + + + + 0 + 0 + + + + Energy Calibration + + + + + + + + 0 + 0 + + + + Angular Calibration + + + + + + + + + + Trimming + + + + + 5 + 10 + 467 + 66 + + + + Trimbits Plot + + + true + + + false + + + + + 230 + 15 + 228 + 44 + + + + + 17 + + + + + <nobr> +Updates plot with Trimbits from Shared Memory, not from Detector. +</nobr> + + + false + + + Refresh + + + + :/icons/images/refresh.png:/icons/images/refresh.png + + + + 24 + 16 + + + + + + + + <nobr> +Plots Trimbits from Detector. This will take time. +</nobr> + + + Get Trimbits + + + + :/icons/images/download.png:/icons/images/download.png + + + + + + + + + 25 + 20 + 187 + 31 + + + + + + + Data Graph + + + true + + + + + + + Histogram + + + + + + + + + true + + + + 5 + 85 + 746 + 226 + + + + Trimming + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + true + + + true + + + + + 25 + 25 + 696 + 195 + + + + + 12 + + + + + + 0 + 0 + + + + Trimming Method: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + 0 + 0 + + + + Exposure Time: + + + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Exposure time of each frame. + #exptime# + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + 5 + + + 0.000000000000000 + + + 2000000000.000000000000000 + + + 1.000000000000000 + + + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::LeftToRight + + + 2 + + + + hr + + + + + min + + + + + s + + + + + ms + + + + + us + + + + + ns + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 50 + 20 + + + + + + + + + 0 + 0 + + + + <nobr> +Trimfile to which the resulting trimbits will be written. +</nobr><br><nobr> +An extension given by the modules serial number will be attached. +</nobr> + + + Output Trim File: + + + + + + + <nobr> +Trimfile to which the resulting trimbits will be written. +</nobr><br><nobr> +An extension given by the modules serial number will be attached. +</nobr> + + + + + + + + 0 + 0 + + + + <nobr> +Trimfile to which the resulting trimbits will be written. +</nobr><br><nobr> +An extension given by the modules serial number will be attached. +</nobr> + + + Browse + + + + :/icons/images/browse.png:/icons/images/browse.png + + + + + + + 0 + + + + + + + + 0 + 0 + + + + Start Trimming + + + + :/icons/images/start.png:/icons/images/start.png + + + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Exposure time of each frame. + #exptime# + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + 3 + + + 0.000000000000000 + + + 10000.000000000000000 + + + 560.000000000000000 + + + + + + + + 0 + 0 + + + + Sets the Threshold DAC + + + Threshold (DACu): + + + + + + + true + + + + 0 + 0 + + + + + 0 + 0 + + + + Optimize Settings + + + + + + + + 0 + 0 + + + + Resolution (a.u.): + + + + + + + + 0 + 0 + + + + Number of measurements (not in real time) that will be acquired. + #frames# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 1 + + + 9 + + + 4 + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + Adjust to Fix Count Level + + + + + Equalize to Median + + + + + + + + + 0 + 0 + + + + Counts/ Channel: + + + + + + + + 0 + 0 + + + + Number of measurements (not in real time) that will be acquired. + #frames# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 16000000 + + + 500 + + + + + + + + + false + + + + 518 + 10 + 233 + 66 + + + + Developer Option + + + false + + + false + + + + + 12 + 28 + 94 + 16 + + + + Set All trimbits: + + + + + + 121 + 24 + 86 + 25 + + + + 63 + + + + + + + Region of Interest + + + + + 10 + 50 + 736 + 246 + + + + QFrame::NoFrame + + + true + + + + + 0 + 0 + 736 + 246 + + + + + 1 + + + 15 + + + + + + + + 10 + 5 + 736 + 41 + + + + + + + + 0 + 0 + + + + + 150 + 0 + + + + Get ROI + + + + :/icons/images/download.png:/icons/images/download.png + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 150 + 0 + + + + Set ROI + + + + :/icons/images/upload.png:/icons/images/upload.png + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 150 + 0 + + + + Clear ROI + + + + :/icons/images/erase.png:/icons/images/erase.png + + + + + + + + + Network + + + + + 10 + 135 + 736 + 171 + + + + Receiver Parameters + + + + + 25 + 135 + 291 + 25 + + + + Setup Receiver + + + + :/icons/images/setup.png:/icons/images/setup.png + + + + + + 25 + 25 + 686 + 96 + + + + + 6 + + + + + + 0 + 0 + + + + TCP Port: + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + Sets the Receiver UDP IP +#rx_udpip# + + + none + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 127 + 0 + + + + Sets Receiver UDP Port +#rx_udpport# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 2000000000 + + + 0 + + + + + + + + 0 + 0 + + + + UDP IP: + + + + + + + + 0 + 0 + + + + Hostname / IP: + + + + + + + + 0 + 0 + + + + <nobr>If the receiver is online<br>#r_online#</nobr>< + + + + Offline + + + + + Online + + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + Sets the Receiver UDP MAC +#rx_udpmac# + + + none + + + + + + + + 0 + 0 + + + + + 127 + 0 + + + + Sets Receiver TCP Port +#rx_tcpport# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 2000000000 + + + 0 + + + + + + + + 0 + 0 + + + + Online: + + + + + + + + 0 + 0 + + + + UDP Port: + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + Sets the Receiver Hostname, connects to it and gets the receiver mac address and eth. Sets some receiver parameters like file name, file dir, file index in receiver. +#rx_hostname# + + + none + + + + + + + + 0 + 0 + + + + UDP MAC: + + + + + + + + + + 35 + 15 + 686 + 101 + + + + + 6 + + + + + + 0 + 0 + + + + + 180 + 0 + + + + <nobr>If the detector is online<br>#online#</nobr>< + + + + Offline + + + + + Online + + + + + + + + + 0 + 0 + + + + Stop Port: + + + + + + + + 0 + 0 + + + + Control Port: + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + Sets the detector IP to send packets to receiver +#detectorip# + + + + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + Sets the detector MAC to send packets to receiver +#detectormac# + + + + + + + + + + + 0 + 0 + + + + MAC: + + + + + + + + 0 + 0 + + + + + 108 + 0 + + + + Online: + + + + + + + + 0 + 0 + + + + + 108 + 0 + + + + Detector: + + + + + + + + 0 + 0 + + + + IP: + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + + 16777215 + 16777215 + + + + Sets Control Port +#port# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 2000000000 + + + 0 + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + Sets Stop Port +#stopport# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 2000000000 + + + 0 + + + + + + + + + + tabAdvancedSettings + chkEnergyLog + chkAngularLog + boxPlot + radioDataGraph + radioHistogram + btnRefresh + btnGetTrimbits + boxTrimming + comboMethod + chkOptimize + spinResolution + spinCounts + spinExpTime + comboExpUnit + spinThreshold + dispFile + btnFile + btnStart + btnGetRoi + btnSetRoi + btnClearRoi + scrollArea + comboDetector + comboOnline + spinControlPort + dispIP + spinStopPort + dispMAC + dispRxrHostname + comboRxrOnline + spinTCPPort + dispUDPIP + spinUDPPort + dispUDPMAC + btnRxr + + + + + + diff --git a/slsDetectorGui/forms/form_tab_dataoutput.ui b/slsDetectorGui/forms/form_tab_dataoutput.ui new file mode 100644 index 0000000000..52b88b59fc --- /dev/null +++ b/slsDetectorGui/forms/form_tab_dataoutput.ui @@ -0,0 +1,718 @@ + + + TabDataOutputObject + + + + 0 + 0 + 775 + 345 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 1000 + + + + Form + + + + + 15 + 30 + 747 + 116 + + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + Output Directory + + + + + 5 + 10 + 731 + 96 + + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + QFrame::NoFrame + + + QFrame::Plain + + + + + 10 + 10 + 716 + 92 + + + + + 4 + + + + + Qt::NoFocus + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + false + + + QLineEdit::Normal + + + true + + + + + + + + 0 + 0 + + + + + + + + + 2 + 2 + 2 + + + + + + + + + 0 + 0 + 0 + + + + + + + + + 119 + 119 + 119 + + + + + + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + Readout: + + + + + + + Qt::StrongFocus + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + + + + + + 0 + 0 + + + + + 180 + 0 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + Browse + + + + :/icons/images/browse.png:/icons/images/browse.png + + + + + + + + + + + 15 + 160 + 746 + 170 + + + + Options + + + + + 17 + 21 + 192 + 137 + + + + + 6 + + + + + false + + + <nobr> +Compression using Root. Available only for Gotthard in Expert Mode. +</nobr><br><nobr> + #r_compression# +</nobr> + + + 10GbE + + + + + + + <nobr> +Compression using Root. Available only for Gotthard in Expert Mode. +</nobr><br><nobr> + #r_compression# +</nobr> + + + Compression + + + + + + + false + + + Angular Conversion + + + + + + + Discard Bad Channels + + + + + + + + + 255 + 21 + 476 + 76 + + + + + 6 + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + false + + + Rate: + + + + + + + false + + + + 0 + 0 + + + + Flat field corrections. + #flatfield# filename + + + Browse + + + + :/icons/images/browse.png:/icons/images/browse.png + + + + + + + false + + + Qt::ClickFocus + + + Flat field corrections. + #flatfield# filename + + + + + + + Flat field corrections. + #flatfield# filename + + + Flat Field File: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + false + + + + 0 + 0 + + + + + + + + + 2 + 2 + 2 + + + + + + + + + 0 + 0 + 0 + + + + + + + + + 119 + 119 + 119 + + + + + + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + Dead Time: + + + + + + + + 0 + 0 + + + + ns + + + -1 + + + 200000000 + + + + + + + false + + + + 0 + 0 + + + + + 16777215 + 30 + + + + <nobr> +Directory where one saves the data. +</nobr><br> + #outdir# +<br> + + + + Default + + + + :/icons/images/calculate.png:/icons/images/calculate.png + + + + + + + + + 230 + 21 + 20 + 134 + + + + QFrame::Raised + + + Qt::Vertical + + + + + + 244 + 92 + 491 + 72 + + + + + + 11 + 4 + 475 + 62 + + + + + + + + 200 + 16777215 + + + + + Continous + + + + + Store in RAM + + + + + + + + + 105 + 16777215 + + + + Clock Divider: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + 200 + 16777215 + + + + + Full Speed + + + + + Half Speed + + + + + Quarter Speed + + + + + Super Slow Speed + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + 105 + 16777215 + + + + Flags: + + + + + + + + Parallel + + + + + Non Parallel + + + + + Safe + + + + + + + + + boxOutDir + boxCorrection_2 + btnOutputBrowse + + + dispReadOutputDir + chkFlatField + dispFlatField + btnFlatField + chkRate + + + + + + diff --git a/slsDetectorGui/forms/form_tab_debugging.ui b/slsDetectorGui/forms/form_tab_debugging.ui new file mode 100644 index 0000000000..e8ebcd6325 --- /dev/null +++ b/slsDetectorGui/forms/form_tab_debugging.ui @@ -0,0 +1,471 @@ + + + TabDebuggingObject + + + + 0 + 0 + 775 + 345 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 1000 + + + + Form + + + + + 45 + 75 + 686 + 231 + + + + Qt::NoFocus + + + Tests + + + + + 15 + 110 + 141 + 51 + + + + + + + Qt::NoFocus + + + Readout Firmware + + + + + + + Qt::NoFocus + + + Readout Software + + + + + + + + + 15 + 185 + 656 + 36 + + + + + + + + 0 + 0 + + + + Run Test + + + + :/icons/images/start.png:/icons/images/start.png + + + + + + + + + 415 + 30 + 256 + 31 + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 100 + 16777215 + + + + Module: + + + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + true + + + + All Modules + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + + 280 + 110 + 141 + 51 + + + + + + + Qt::NoFocus + + + Readout Bus + + + + + + + Qt::NoFocus + + + Readout Memory + + + + + + + + + 530 + 110 + 141 + 26 + + + + + + + Qt::NoFocus + + + Chip + + + + + + + + + 15 + 30 + 276 + 31 + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 150 + 16777215 + + + + Readout: + + + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + + 15 + 60 + 276 + 31 + + + + + + + + 0 + 0 + + + + + 150 + 16777215 + + + + Status: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + 0 + 0 + + + + IDLE + + + + + + + + + 530 + 135 + 141 + 26 + + + + + + + Qt::NoFocus + + + Module Firmware + + + + + + + + + 5 + 95 + 676 + 16 + + + + Qt::Horizontal + + + + + + 5 + 165 + 676 + 16 + + + + Qt::Horizontal + + + + + + + 45 + 25 + 686 + 31 + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Get ID Information + + + + :/icons/images/download.png:/icons/images/download.png + + + + + + + + btnGetInfo + comboDetector + comboModule + btnTest + + + + + + diff --git a/slsDetectorGui/forms/form_tab_measurement.ui b/slsDetectorGui/forms/form_tab_measurement.ui new file mode 100644 index 0000000000..9290c74c9f --- /dev/null +++ b/slsDetectorGui/forms/form_tab_measurement.ui @@ -0,0 +1,1018 @@ + + + TabMeasurementObject + + + + 0 + 0 + 775 + 345 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 345 + + + + Form + + + + + 30 + 153 + 319 + 116 + + + + + 0 + 0 + + + + Progress Monitor + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + 10 + 75 + 300 + 23 + + + + 24 + + + + + + 10 + 25 + 91 + 16 + + + + Current Frame: + + + + + + 101 + 25 + 101 + 16 + + + + 0 + + + + + + 150 + 45 + 76 + 16 + + + + + 0 + 0 + + + + + 60 + 0 + + + + 0 + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + 10 + 45 + 136 + 16 + + + + Current Measurement: + + + + + + + 30 + 289 + 319 + 31 + + + + + 0 + 0 + + + + Qt::NoFocus + + + Starts or Stops Acquisition + + + Start + + + + :/icons/images/start.png:/icons/images/start.png + + + Shift+Space + + + true + + + false + + + + + + 390 + 8 + 362 + 342 + + + + QFrame::NoFrame + + + QFrame::Plain + + + + + 35 + 10 + 326 + 321 + + + + + + + false + + + Number of Triggers to be expected. + #cycles# + + + Number of Triggers: + + + + + + + false + + + + 0 + 0 + + + + Number of Triggers to be expected. + #cycles# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 2000000000 + + + 1 + + + + + + + false + + + The Delay between Trigger Edge and Start of Exposure ( or Readout). +#delay# + + + Delay After Trigger: + + + + + + + false + + + + 0 + 0 + + + + The Delay between Trigger Edge and Start of Exposure ( or Readout). +#delay# + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + 9 + + + 2000000000.000000000000000 + + + 0.000000000000000 + + + + + + + false + + + + 0 + 0 + + + + The Delay between Trigger Edge and Start of Exposure ( or Readout). +#delay# + + + Qt::LeftToRight + + + 2 + + + + hr + + + + + min + + + + + s + + + + + ms + + + + + us + + + + + ns + + + + + + + + false + + + + 0 + 0 + + + + Number of Gate Signals per Frame. + #gates# + + + Number of Gates: + + + + + + + false + + + + 0 + 0 + + + + Number of Gate Signals per Frame. + #gates# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 2000000000 + + + 1 + + + + + + + false + + + + 0 + 0 + + + + <nobr> +The data are accumulated over several (frames) pump cycles. +</nobr> +<br> +<nobr> +Enabled only in <b>Expert Mode</b> and if<b> Number of Frames</b> > 1. +</nobr> +<br> +<nobr>Setting <b>Number of Probes</b> will reset <b>Number of Triggers</b> to 1. +</nobr> +<br> +Maximum value is 3. <br> +#probes# + + + + Number of Probes: + + + + + + + false + + + + 0 + 0 + + + + <nobr> +The data are accumulated over several (frames) pump cycles. +</nobr> +<br> +<nobr> +Enabled only in <b>Expert Mode</b> and if<b> Number of Frames</b> > 1. +</nobr> +<br> +<nobr>Setting <b>Number of Probes</b> will reset <b>Number of Triggers</b> to 1. +</nobr> +<br> +Maximum value is 3. <br> +#probes# + + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 3 + + + 1 + + + + + + + + 0 + 0 + + + + Timing Mode of the detector. + #timing# + + + + None + + + + + Auto + + + + + Trigger Exposure Series + + + + + Trigger Readout + + + + + Gated with Fixed Number + + + + + Gated with Start Trigger + + + + + Burst Trigger + + + + + + + + false + + + Number of Frames: + + + + + + + false + + + + 0 + 0 + + + + Number of measurements (not in real time) that will be acquired. + #frames# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 1 + + + 2000000000 + + + 1 + + + + + + + true + + + <nobr> +Exposure Time of a frame. +</nobr><br><nobr> + #exptime# +</nobr> + + + Exposure Time: + + + + + + + true + + + + 0 + 0 + + + + <nobr> +Exposure Time of a frame. +</nobr><br><nobr> + #exptime# +</nobr> + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + 5 + + + 0.000000000000000 + + + 2000000000.000000000000000 + + + 1.000000000000000 + + + + + + + true + + + + 0 + 0 + + + + <nobr> +Exposure Time of a frame. +</nobr><br><nobr> + #exptime# +</nobr> + + + Qt::LeftToRight + + + 2 + + + + hr + + + + + min + + + + + s + + + + + ms + + + + + us + + + + + ns + + + + + + + + false + + + <nobr> +Frame period between exposures. +</nobr><br><nobr> + #period# +</nobr> + + + Acquisition Period: + + + + + + + false + + + + 0 + 0 + + + + <nobr> +Frame period between exposures. +</nobr><br><nobr> + #period# +</nobr> + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + 5 + + + 2000000000.000000000000000 + + + 0.000000000000000 + + + + + + + false + + + + 0 + 0 + + + + <nobr> +Frame period between exposures. +</nobr><br><nobr> + #period# +</nobr> + + + Qt::LeftToRight + + + 2 + + + + hr + + + + + min + + + + + s + + + + + ms + + + + + us + + + + + ns + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + Timing Mode: + + + + + + + + + + 20 + 5 + 336 + 159 + + + + QFrame::NoFrame + + + QFrame::Plain + + + + + 10 + 13 + 321 + 130 + + + + + 6 + + + + + Number of Measurements: + + + + + + + + 0 + 0 + + + + Number of measurements (not in real time) that will be acquired. + #frames# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 1 + + + 2000000000 + + + 1 + + + + + + + + 0 + 0 + + + + Root of the file name - please check that the output directory is correctly set and select the file name format. + #fname# + + + + + + + + + + Run Index: + + + + + + + + 0 + 0 + + + + Run index (automatically incremented) + #index# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + 0 + + + 2000000000 + + + 0 + + + + + + + <nobr>Sets output file name prefix</nobr><br> +<nobr>Check the box to enable write to file. </nobr> + + + File Name: + + + true + + + + + + + + + spinNumMeasurements + chkFile + dispFileName + spinIndex + comboTimingMode + spinNumFrames + spinExpTime + comboExpUnit + spinPeriod + comboPeriodUnit + spinNumTriggers + spinDelay + comboDelayUnit + spinNumGates + spinNumProbes + + + + + + diff --git a/slsDetectorGui/forms/form_tab_messages.ui b/slsDetectorGui/forms/form_tab_messages.ui new file mode 100644 index 0000000000..1f75475e53 --- /dev/null +++ b/slsDetectorGui/forms/form_tab_messages.ui @@ -0,0 +1,82 @@ + + + TabMessagesObject + + + + 0 + 0 + 775 + 345 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Form + + + + + + + + TextLabel + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + + + TextLabel + + + + + + + + + + + + + + + + diff --git a/slsDetectorGui/forms/form_tab_plot.ui b/slsDetectorGui/forms/form_tab_plot.ui new file mode 100644 index 0000000000..f50abeb2b3 --- /dev/null +++ b/slsDetectorGui/forms/form_tab_plot.ui @@ -0,0 +1,2941 @@ + + + TabPlotObject + + + + 0 + 0 + 775 + 345 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 1000 + + + + + + + + + 0 + 0 + 30 + + + + + + + + + 0 + 0 + 30 + + + + + + + + + 0 + 0 + 30 + + + + + + + + Form + + + + true + + + + 15 + 70 + 371 + 51 + + + + 2D Plot Options 1 + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + 5 + 15 + 361 + 31 + + + + 3 + + + + + + 20 + 5 + 327 + 26 + + + + + + + + 0 + 0 + + + + Interpolate + + + + + + + + 0 + 0 + + + + Contour + + + + + + + + 0 + 0 + + + + Log Scale (Z) + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 15 + 20 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + + + + 25 + 5 + 95 + 26 + + + + + 0 + + + + + true + + + + 0 + 0 + + + + Accumulate + + + + + + + + + 175 + 3 + 156 + 26 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Reset Accumulation + + + + :/icons/images/calculate.png:/icons/images/calculate.png + + + + 16 + 16 + + + + + + + + + 20 + 5 + 77 + 26 + + + + + 0 + + + + + true + + + + 0 + 0 + + + + Pedestal + + + + + + + + + 160 + 3 + 171 + 26 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Recalculate Pedestal + + + + :/icons/images/calculate.png:/icons/images/calculate.png + + + + 16 + 16 + + + + + + + + + 25 + 5 + 311 + 26 + + + + + 1 + + + + + + 0 + 0 + + + + Binary + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + false + + + + 0 + 0 + + + + from + + + + + + + false + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 0 + + + + + + + false + + + + 0 + 0 + + + + to + + + + + + + false + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 0 + + + + + + + + + + + 25 + 5 + 128 + 26 + + + + + 0 + + + + + true + + + + 0 + 0 + + + + <nobr> +Displays minimum, maximum and sum of values for each plot. +<nobr> + + + Display Statistics + + + + + + + + + true + + + + + 25 + 5 + 311 + 26 + + + + + 1 + + + + + true + + + + 0 + 0 + + + + from + + + + + + + true + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 0 + + + + + + + true + + + + 0 + 0 + + + + to + + + + + + + true + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 10000 + + + + + + + true + + + + 0 + 0 + + + + size + + + + + + + true + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 1000 + + + + + + + + + + + + 15 + 70 + 371 + 51 + + + + 1D Plot Options 1 + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + 4 + 15 + 366 + 31 + + + + 4 + + + + + + 25 + 5 + 107 + 26 + + + + + + + + 0 + 0 + + + + Superimpose + + + false + + + + + + + + + 210 + 5 + 128 + 26 + + + + + 1 + + + + + false + + + + 0 + 0 + + + + Persistency: + + + + + + + false + + + + 0 + 0 + + + + + 40 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + 1 + + + 10 + + + 1 + + + + + + + + + + + 25 + 5 + 321 + 26 + + + + + + + + 0 + 0 + + + + Log Scale (Y) + + + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 95 + 20 + + + + + + + + true + + + + 0 + 0 + + + + Points + + + + + + + true + + + + 0 + 0 + + + + Lines + + + true + + + + + + + + + + + 175 + 3 + 161 + 26 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Reset Accumulation + + + + :/icons/images/calculate.png:/icons/images/calculate.png + + + + 16 + 16 + + + + + + + 25 + 5 + 95 + 26 + + + + + 0 + + + + + true + + + + 0 + 0 + + + + Accumulate + + + + + + + + + + + 25 + 5 + 77 + 26 + + + + + 0 + + + + + true + + + + 0 + 0 + + + + Pedestal + + + + + + + + + 165 + 3 + 171 + 26 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Recalculate Pedestal + + + + :/icons/images/calculate.png:/icons/images/calculate.png + + + + 16 + 16 + + + + + + + <nobr> +All values between <b>from</b> and <b>to</b> will be reset to 1, others to 0. +</nobr> + + + + + 25 + 5 + 311 + 26 + + + + + 1 + + + + + + 0 + 0 + + + + <nobr> +All values between <b>from</b> and <b>to</b> will be reset to 1, others to 0. +</nobr> + + + Binary + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + false + + + + 0 + 0 + + + + from + + + + + + + false + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 0 + + + + + + + false + + + + 0 + 0 + + + + to + + + + + + + false + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 0 + + + + + + + + + + + 25 + 5 + 128 + 26 + + + + + 0 + + + + + true + + + + 0 + 0 + + + + <nobr> +Displays minimum, maximum and sum of values for each plot. +<nobr> + + + Display Statistics + + + + + + + + + true + + + + + 25 + 5 + 311 + 26 + + + + + 1 + + + + + true + + + + 0 + 0 + + + + from + + + + + + + true + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + 0 + + + 16777215 + + + 0 + + + + + + + true + + + + 0 + 0 + + + + to + + + + + + + true + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 10000 + + + + + + + true + + + + 0 + 0 + + + + size + + + + + + + true + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + -16777215 + + + 16777215 + + + 1000 + + + + + + + + + + + + 410 + 70 + 351 + 51 + + + + Save Image + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + 10 + 20 + 227 + 26 + + + + + 0 + + + + + true + + + + 0 + 0 + + + + Save All with Automatic File Name + + + + + + + + + 264 + 19 + 76 + 25 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Save + + + + :/icons/images/save.png:/icons/images/save.png + + + + 16 + 16 + + + + + + + + 410 + 5 + 351 + 51 + + + + 2D Scan - Y Axis Values + + + true + + + false + + + + + 10 + 20 + 342 + 26 + + + + + 0 + + + + + + 0 + 0 + + + + <nobr>Enabled only when there is a Scan Level 0</nobr> + + + Level 0 + + + true + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 7 + 10 + + + + + + + + + 0 + 0 + + + + <nobr>Enabled only when there is a Scan Level 1</nobr> + + + Level 1 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 7 + 10 + + + + + + + + + 0 + 0 + + + + <nobr>Enabled only when there is a Scan Level 0 or a Scan Level 1, not both</nobr> + + + Frame Index + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 7 + 10 + + + + + + + + + 0 + 0 + + + + <nobr>Disabled only for Angle Plots, Moench and Eiger Detectors</nobr> + + + All Frames + + + false + + + + + + + + + + 15 + 200 + 746 + 141 + + + + Plot Axis + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + 10 + 15 + 726 + 121 + + + + + QLayout::SetNoConstraint + + + 0 + + + + + Title Prefix: + + + + + + + + 0 + 0 + + + + + 250 + 0 + + + + QLineEdit::Normal + + + false + + + + + + + true + + + + 0 + 0 + + + + + 50 + 0 + + + + + + + + + 0 + 0 + + + + Z Max: + + + + + + + + 0 + 0 + + + + + 50 + 0 + + + + + + + + + 0 + 0 + + + + Y Max: + + + + + + + + 0 + 0 + + + + X Max: + + + + + + + + 0 + 0 + + + + + 50 + 0 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + Z Min: + + + + + + + + 0 + 0 + + + + + 50 + 0 + + + + + + + + + 0 + 0 + + + + X Min: + + + + + + + + 0 + 0 + + + + + 50 + 0 + + + + Qt::ImhDigitsOnly + + + + + + + + 0 + 0 + + + + Y Min: + + + + + + + + 0 + 0 + + + + + 50 + 0 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + X Axis: + + + + + + + + 0 + 0 + + + + + 250 + 0 + + + + Qt::ImhDigitsOnly + + + + + + + + 0 + 0 + + + + Y Axis: + + + + + + + + 0 + 0 + + + + + 20 + 0 + + + + Qt::ImhDigitsOnly + + + + + + + + 0 + 0 + + + + Z Axis: + + + + + + + + 0 + 0 + + + + + 20 + 0 + + + + Qt::ImhDigitsOnly + + + + + + + + + true + + + + 15 + 5 + 371 + 51 + + + + Plot Arguments + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + 10 + 20 + 358 + 26 + + + + + + + + 0 + 0 + + + + No Plot + + + + + + + + 0 + 0 + + + + Data Graph + + + true + + + + + + + true + + + + 0 + 0 + + + + Histogram + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 45 + 10 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 45 + 10 + + + + + + + + + + + 15 + 135 + 371 + 49 + + + + <nobr> +Interval between plots has 2 modes. A condition to be satisfied, in order to avoid losing images: +</nobr><br><br><nobr> +<b>Time Interval</b>: (Acquisition Period) * (nth Image) >= 250ms. +</nobr><br><nobr> +<b>Every nth Image</b>: minimum of 250ms. +</nobr> + + + Interval between Plots + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + 10 + 16 + 351 + 26 + + + + + 0 + + + + + + 0 + 0 + + + + + 150 + 0 + + + + + 16777215 + 16777215 + + + + + + + + + 11 + 11 + 11 + + + + + + + 20 + 20 + 20 + + + + + + + + + 11 + 11 + 11 + + + + + + + 20 + 20 + 20 + + + + + + + + + 119 + 119 + 119 + + + + + + + 20 + 20 + 20 + + + + + + + + 0 + + + + Time Interval + + + + + Every nth Image + + + + + + + + Qt::Horizontal + + + QSizePolicy::Preferred + + + + 80 + 20 + + + + + + + + + 0 + 0 + + + + + 140 + 21 + + + + + + + + + + true + + + + 410 + 135 + 351 + 51 + + + + Snapshot + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + 10 + 15 + 331 + 31 + + + + + + + + 0 + 0 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Create + + + + :/icons/images/new.png:/icons/images/new.png + + + false + + + + + + + + 0 + 0 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Close All + + + + :/icons/images/close.png:/icons/images/close.png + + + false + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + true + + + + 0 + 0 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + + 20 + 20 + 20 + + + + + + + + Qt::NoFocus + + + Save All + + + + :/icons/images/saveAll.png:/icons/images/saveAll.png + + + false + + + + + + + + + + 362 + 95 + 16 + 16 + + + + + 0 + 0 + + + + Qt::NoFocus + + + + + + + :/icons/images/rightArrow.png:/icons/images/rightArrow.png + + + + 16 + 16 + + + + true + + + + + + 23 + 94 + 16 + 16 + + + + + 0 + 0 + + + + Qt::NoFocus + + + + + + + :/icons/images/leftArrow.png:/icons/images/leftArrow.png + + + + 16 + 16 + + + + true + + + + + + 410 + 5 + 351 + 51 + + + + Histogram - X Axis Values + + + false + + + false + + + + + 10 + 20 + 351 + 26 + + + + + 0 + + + + + + 0 + 0 + + + + <nobr>Enabled only when there is a Scan Level 0</nobr> + + + Intensity + + + true + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 7 + 10 + + + + + + + + + 0 + 0 + + + + <nobr>Enabled only when there is a Scan Level 1</nobr> + + + Level 0 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 7 + 10 + + + + + + + + + 0 + 0 + + + + <nobr>Enabled only when there is a Scan Level 0 or a Scan Level 1, not both</nobr> + + + Level 1 + + + + + + + box1D + box2D + boxSave + boxScan + boxPlotAxis + groupBox_3 + boxFrequency + boxSnapshot + btnRight + btnLeft + boxHistogram + + + radioNoPlot + radioHistogram + radioDataGraph + boxScan + radioLevel0 + radioLevel1 + radioFileIndex + radioAllFrames + chkInterpolate + chkContour + chkLogz + chkSaveAll + comboFrequency + chkTitle + dispTitle + chkXAxis + dispXAxis + chkXMin + dispXMin + chkXMax + dispXMax + chkYAxis + dispYAxis + chkYMin + dispYMin + chkYMax + dispYMax + chkZAxis + dispZAxis + chkZMin + dispZMin + chkZMax + dispZMax + spinPersistency + chk1DLog + chkPoints + chkLines + chkSuperimpose + + + + + + diff --git a/slsDetectorGui/forms/form_tab_settings.ui b/slsDetectorGui/forms/form_tab_settings.ui new file mode 100644 index 0000000000..7c9f8f3ed8 --- /dev/null +++ b/slsDetectorGui/forms/form_tab_settings.ui @@ -0,0 +1,248 @@ + + + TabSettingsObject + + + + 0 + 0 + 775 + 345 + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 1000 + 1000 + + + + Form + + + + + 30 + 20 + 316 + 171 + + + + + + + Settings: + + + + + + + + 0 + 0 + + + + Settings of the detector. + #settings# + + + + Standard + + + + + Fast + + + + + High Gain + + + + + Dynamic Gain + + + + + Low Gain + + + + + Medium Gain + + + + + Very High Gain + + + + + Low Noise + + + + + Dynamic HG0 + + + + + Fix Gain 1 + + + + + Fix Gain 2 + + + + + Force Switch G1 + + + + + Force Switch G2 + + + + + Very Low Gain + + + + + Undefined + + + + + Uninitialized + + + + + + + + false + + + eV + + + -100000 + + + 100000 + + + 100 + + + -1 + + + + + + + Number of Modules: + + + + + + + Dynamic Range: + + + + + + + + 1.67772e+07 + + + + + 65535 + + + + + 255 + + + + + 7 + + + + + + + + 1 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Threshold: + + + + + + + + comboSettings + spinThreshold + spinNumModules + comboDynamicRange + + + + + + diff --git a/slsDetectorGui/gitInfo.txt b/slsDetectorGui/gitInfo.txt new file mode 100644 index 0000000000..0bcfcd467d --- /dev/null +++ b/slsDetectorGui/gitInfo.txt @@ -0,0 +1,9 @@ +Path: slsDetectorsPackage/slsDetectorGui +URL: origin git@git.psi.ch:sls_detectors_software/sls_detector_gui.git +Repository Root: origin git@git.psi.ch:sls_detectors_software/sls_detector_gui.git +Repsitory UUID: 14ee36afeb077c918d34aaea39431a6e05f9436d +Revision: 377 +Branch: developer +Last Changed Author: Dhanya_Maliakal +Last Changed Rev: 377 +Last Changed Date: 2016-11-22 14:11:11 +0100 diff --git a/slsDetectorGui/images/add.png b/slsDetectorGui/images/add.png new file mode 100644 index 0000000000..41058cb95b Binary files /dev/null and b/slsDetectorGui/images/add.png differ diff --git a/slsDetectorGui/images/browse.png b/slsDetectorGui/images/browse.png new file mode 100644 index 0000000000..e9404d3c77 Binary files /dev/null and b/slsDetectorGui/images/browse.png differ diff --git a/slsDetectorGui/images/calculate.png b/slsDetectorGui/images/calculate.png new file mode 100644 index 0000000000..49ac1f4b1e Binary files /dev/null and b/slsDetectorGui/images/calculate.png differ diff --git a/slsDetectorGui/images/close.png b/slsDetectorGui/images/close.png new file mode 100644 index 0000000000..7173b4e900 Binary files /dev/null and b/slsDetectorGui/images/close.png differ diff --git a/slsDetectorGui/images/download.png b/slsDetectorGui/images/download.png new file mode 100644 index 0000000000..5962012d82 Binary files /dev/null and b/slsDetectorGui/images/download.png differ diff --git a/slsDetectorGui/images/erase.png b/slsDetectorGui/images/erase.png new file mode 100644 index 0000000000..4c70f0847b Binary files /dev/null and b/slsDetectorGui/images/erase.png differ diff --git a/slsDetectorGui/images/leftArrow.png b/slsDetectorGui/images/leftArrow.png new file mode 100644 index 0000000000..34165b7150 Binary files /dev/null and b/slsDetectorGui/images/leftArrow.png differ diff --git a/slsDetectorGui/images/mountain.png b/slsDetectorGui/images/mountain.png new file mode 100644 index 0000000000..3962d0fbcc Binary files /dev/null and b/slsDetectorGui/images/mountain.png differ diff --git a/slsDetectorGui/images/new.png b/slsDetectorGui/images/new.png new file mode 100644 index 0000000000..7ef7b0b082 Binary files /dev/null and b/slsDetectorGui/images/new.png differ diff --git a/slsDetectorGui/images/refresh.png b/slsDetectorGui/images/refresh.png new file mode 100644 index 0000000000..822f5bfc49 Binary files /dev/null and b/slsDetectorGui/images/refresh.png differ diff --git a/slsDetectorGui/images/refresher.png b/slsDetectorGui/images/refresher.png new file mode 100644 index 0000000000..df73f01216 Binary files /dev/null and b/slsDetectorGui/images/refresher.png differ diff --git a/slsDetectorGui/images/remove.png b/slsDetectorGui/images/remove.png new file mode 100644 index 0000000000..a3f5d74deb Binary files /dev/null and b/slsDetectorGui/images/remove.png differ diff --git a/slsDetectorGui/images/rightArrow.png b/slsDetectorGui/images/rightArrow.png new file mode 100644 index 0000000000..74ac7f7958 Binary files /dev/null and b/slsDetectorGui/images/rightArrow.png differ diff --git a/slsDetectorGui/images/save.png b/slsDetectorGui/images/save.png new file mode 100644 index 0000000000..ff544b86d2 Binary files /dev/null and b/slsDetectorGui/images/save.png differ diff --git a/slsDetectorGui/images/saveAll.png b/slsDetectorGui/images/saveAll.png new file mode 100644 index 0000000000..04bba11bc9 Binary files /dev/null and b/slsDetectorGui/images/saveAll.png differ diff --git a/slsDetectorGui/images/setup.png b/slsDetectorGui/images/setup.png new file mode 100644 index 0000000000..f0323e56dd Binary files /dev/null and b/slsDetectorGui/images/setup.png differ diff --git a/slsDetectorGui/images/start.png b/slsDetectorGui/images/start.png new file mode 100644 index 0000000000..afe837e75c Binary files /dev/null and b/slsDetectorGui/images/start.png differ diff --git a/slsDetectorGui/images/stop.png b/slsDetectorGui/images/stop.png new file mode 100644 index 0000000000..316926dee6 Binary files /dev/null and b/slsDetectorGui/images/stop.png differ diff --git a/slsDetectorGui/images/upload.png b/slsDetectorGui/images/upload.png new file mode 100644 index 0000000000..d493327dbc Binary files /dev/null and b/slsDetectorGui/images/upload.png differ diff --git a/slsDetectorGui/include/gitInfoGui.h b/slsDetectorGui/include/gitInfoGui.h new file mode 100644 index 0000000000..1f436a2a40 --- /dev/null +++ b/slsDetectorGui/include/gitInfoGui.h @@ -0,0 +1,11 @@ +//#define SVNPATH "" +#define SVNURL "git@git.psi.ch:sls_detectors_software/sls_detector_gui.git" +//#define SVNREPPATH "" +#define SVNREPUUID "14ee36afeb077c918d34aaea39431a6e05f9436d" +//#define SVNREV 0x377 +//#define SVNKIND "" +//#define SVNSCHED "" +#define SVNAUTH "Dhanya_Maliakal" +#define SVNREV 0x377 +#define SVNDATE 0x20161122 +// diff --git a/slsDetectorGui/include/gitInfoGuiTmp.h b/slsDetectorGui/include/gitInfoGuiTmp.h new file mode 100644 index 0000000000..58e48f4978 --- /dev/null +++ b/slsDetectorGui/include/gitInfoGuiTmp.h @@ -0,0 +1,11 @@ +//#define SVNPATH "" +#define SVNURL "" +//#define SVNREPPATH "" +#define SVNREPUUID "" +//#define SVNREV "" +//#define SVNKIND "" +//#define SVNSCHED "" +#define SVNAUTH "" +#define SVNREV "" +#define SVNDATE "" +// diff --git a/slsDetectorGui/include/icons.qrc b/slsDetectorGui/include/icons.qrc new file mode 100644 index 0000000000..26f0b5da78 --- /dev/null +++ b/slsDetectorGui/include/icons.qrc @@ -0,0 +1,22 @@ + + + ../images/mountain.png + ../images/refresh.png + ../images/save.png + ../images/saveAll.png + ../images/close.png + ../images/add.png + ../images/new.png + ../images/download.png + ../images/browse.png + ../images/start.png + ../images/erase.png + ../images/remove.png + ../images/stop.png + ../images/leftArrow.png + ../images/rightArrow.png + ../images/upload.png + ../images/setup.png + ../images/calculate.png + + diff --git a/slsDetectorGui/include/qActionsWidget.h b/slsDetectorGui/include/qActionsWidget.h new file mode 100644 index 0000000000..2e024c8a18 --- /dev/null +++ b/slsDetectorGui/include/qActionsWidget.h @@ -0,0 +1,85 @@ +/* + * qActionsWidget.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QACTIONSWIDGET_H_ +#define QACTIONSWIDGET_H_ + +#include "qDefs.h" + +/** Form Header */ +#include "ui_form_action.h" +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Include Headers */ + +/** C++ Include Headers */ +#include +using namespace std; + + + +class qActionsWidget : public QWidget,private Ui::ActionsObject{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + */ + qActionsWidget(QWidget *parent, multiSlsDetector*& detector); + + ~qActionsWidget(); + + /**to update the widgets*/ + void Refresh(); + + + /**number of action widgets*/ + static int NUM_ACTION_WIDGETS; + + + +private: + /** The sls detector object */ + multiSlsDetector *myDet; + /**id of the action widget*/ + int id; + + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals + * */ + void Initialization(); + + +private slots: +/** Sets the scan or script. Accordingly enables, disables other widgets + * @param mode value chosen + * */ +void SetMode(int mode); + +/** Browse for the script + * */ +void BrowsePath(); + +/** Sets the script file + * */ +void SetScriptFile(); + +/** Set Parameter + * */ +void SetParameter(); + +}; + + + + +#endif /* QACTIONSWIDGET_H_ */ + diff --git a/slsDetectorGui/include/qCloneWidget.h b/slsDetectorGui/include/qCloneWidget.h new file mode 100644 index 0000000000..8e1312660d --- /dev/null +++ b/slsDetectorGui/include/qCloneWidget.h @@ -0,0 +1,165 @@ +/* + * qCloneWidget.h + * + * Created on: May 18, 2012 + * Author: l_maliakal_d + */ + +#ifndef QCLONEWIDGET_H_ +#define QCLONEWIDGET_H_ + +#include "qDefs.h" + + +/** Qt Project Class Headers */ +class SlsQtH1D; +#include "SlsQt1DPlot.h" +#include "SlsQt2DPlotLayout.h" +/** Qt Include Headers */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +/** C++ Include Headers */ +#include +#include +using namespace std; + +/** + *@short Sets up the clone plot widget + */ +class qCloneWidget:public QMainWindow{ + Q_OBJECT + +public: + /** \short The constructor + */ + qCloneWidget(QWidget *parent,int id,QString title,QString xTitle, QString yTitle, QString zTitle, int numDim,string FilePath, + bool displayStats, QString min, QString max, QString sum); + + /** Destructor + */ + ~qCloneWidget(); + + /** Sets up the widget window + * @param title title of the image with frame number + * @param xTitle title of x axis + * @param yTitle title of y axis + * @param zTitle title of z axis + * @param numDim 1D or 2D + * */ + void SetupWidgetWindow(QString title, QString xTitle, QString yTitle, QString zTitle, int numDim); + + + + /** Get the 1D hist values to plot + * @param nHists Number of graphs in 1D + * @param histNBins Total Number of X axis values/channels in 1D + * @param histXAxis X Axis value in 1D + * @param histYAxis Y Axis value in 1D + * @param histTitle Title for all the graphs in 1D + * @param lines style of plot if lines or dots + * @param markers style of plot markers or not + * */ + void SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis[],string histTitle[],bool lines,bool markers); + + /** Get the 1D hist values to plot for angle plotting + * @param nHists Number of graphs in 1D + * @param histNBins Total Number of X axis values/channels in 1D + * @param histXAxis X Axis value in 1D + * @param histYAxis Y Axis value in 1D + * @param histTitle Title for all the graphs in 1D + * @param lines style of plot if lines or dots + * @param markers style of plot markers or not + * */ + void SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis,string histTitle[],bool lines,bool markers); + + /** Get the 1D hist values to plot for angle plotting + * @param nbinsx number of bins in x axis + * @param xmin minimum in x axis + * @param xmax maximum in x axis + * @param nbinsy number of bins in y axis + * @param ymin minimum in y axis + * @param ymax maximum in y axis + * @param d data + * */ + void SetCloneHists2D(int nbinsx,double xmin,double xmax,int nbinsy, double ymin, double ymax, double *d); + + /**Set the range of the 1d plot + * @param IsXYRange array of x,y,min,max if these values are set + * @param XYRangeValues array of set values of x,y, min, max + */ + void SetRange(bool IsXYRange[], double XYRangeValues[]); + + /** Returns the 1d plot + */ + SlsQt1DPlot* Get1dPlot(){return cloneplot1D;}; + +public slots: +/** Save Plots automatically by save all clones + * returns -1 if fail*/ +int SavePlotAutomatic(); + + +private: + /** clone window id*/ + int id; + /** Default Save file path */ + string filePath; + + /** clone 2D Plot */ + SlsQt2DPlotLayout* cloneplot2D; + /** clone 1D Plot */ + SlsQt1DPlot* cloneplot1D; + /** vector of 1D hist values */ + QVector cloneplot1D_hists; + + /** markers for the plot*/ + QwtSymbol *marker; + QwtSymbol *nomarker; + + QMenuBar *menubar; + QAction *actionSave; + + QGridLayout *mainLayout; + QGroupBox *cloneBox; + QGridLayout *gridClone; + + QLabel *lblHistTitle; + + /** Gets the current time stamp for the window title*/ + char* GetCurrentTimeStamp(); + + /** Display Statistics */ + void DisplayStats(bool enable, QString min, QString max, QString sum); + + +private slots: +/** Save Plot */ +void SavePlot(); + +protected: + void closeEvent(QCloseEvent* event); + +signals: +void CloneClosedSignal(int); + +}; + + + + +#endif /* QCLONEWIDGET_H_ */ diff --git a/slsDetectorGui/include/qDebugStream.h b/slsDetectorGui/include/qDebugStream.h new file mode 100644 index 0000000000..816fcd78d4 --- /dev/null +++ b/slsDetectorGui/include/qDebugStream.h @@ -0,0 +1,105 @@ +/* + * qDebugStream.h + * + * Created on: Jun 28, 2012 + * Author: Anna Bergamaschi + */ + +#ifndef QDEBUGSTREAM_H_ +#define QDEBUGSTREAM_H_ + + +#include "qDefs.h" + + +#include +#include +#include +#include + +#include +#include +#include +using namespace std; + +#define STREAMEVENT 60001 + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +class qStreamEvent:public QEvent{ +public: + qStreamEvent(QString s):QEvent(static_cast(STREAMEVENT)),str(s){ +#ifdef PRINT_LOG + printf("%s\n",str.toAscii().constData()); +#endif + } + /** \returns the progress index */ + QString getString() {return str;} +private: + QString str; + +}; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +class qDebugStream : public basic_streambuf { + +public: + qDebugStream(ostream &stream, QWidget* w) : m_stream(stream), log_window(w) { + m_old_buf = stream.rdbuf(); + stream.rdbuf(this); + } + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + ~qDebugStream(){ + // output anything that is left + if (!m_string.empty()) + QApplication::postEvent(log_window, new qStreamEvent(m_string.c_str())); + m_stream.rdbuf(m_old_buf); + } + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +protected: + virtual int_type overflow(int_type v){ + if (v == '\n'){ + QApplication::postEvent(log_window, new qStreamEvent(m_string.c_str())); + m_string.erase(m_string.begin(), m_string.end()); + } + else + m_string += v; + return v; + } + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + virtual streamsize xsputn(const char *p, streamsize n) { + m_string.append(p, p + n); + //changed from uint because of 64 bit + int pos = 0; + + while (pos != string::npos){ + pos = m_string.find('\n'); + if (pos != string::npos){ + string tmp(m_string.begin(), m_string.begin() + pos); + QApplication::postEvent(log_window, new qStreamEvent(tmp.c_str())); + m_string.erase(m_string.begin(), m_string.begin() + pos + 1); + } + } + return n; + } + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +private: + ostream &m_stream; + streambuf *m_old_buf; + string m_string; + QWidget* log_window; +}; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +#endif /* QDEBUGSTREAM_H_ */ diff --git a/slsDetectorGui/include/qDefs.h b/slsDetectorGui/include/qDefs.h new file mode 100644 index 0000000000..0e5ddff6d6 --- /dev/null +++ b/slsDetectorGui/include/qDefs.h @@ -0,0 +1,302 @@ +/* + * qDefs.h + * + * Created on: May 4, 2012 + * Author: l_maliakal_d + */ + +#ifndef QDEFS_H +#define QDEFS_H + +#include "ansi.h" +#include "sls_detector_defs.h" +#include "slsDetector.h" +#include "multiSlsDetector.h" +#include +#include +#include +#include +#include +using namespace std; + +class qDefs:public QWidget{ +public: +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /** Empty Constructor + */ + qDefs(){}; +//------------------------------------------------------------------------------------------------------------------------------------------------- + +static const int64_t GUI_VERSION=0x20121213; + +#define GOODBYE -200 +//------------------------------------------------------------------------------------------------------------------------------------------------- + + enum{ + OK, + FAIL + }; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + enum MessageIndex{ + WARNING, + CRITICAL, + INFORMATION, + QUESTION + }; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + /** unit of time + */ + enum timeUnit{ + HOURS, /** hr */ + MINUTES, /** min */ + SECONDS, /** s */ + MILLISECONDS, /** ms */ + MICROSECONDS, /** us */ + NANOSECONDS /** ns */ + }; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /** returns the unit in words + * @param unit is the time unit + */ + static string getUnitString(timeUnit unit){ + switch(unit){ + case HOURS: return string("hrs"); + case MINUTES: return string("min"); + case SECONDS: return string("sec"); + case MILLISECONDS: return string("msec"); + case MICROSECONDS: return string("usec"); + case NANOSECONDS: return string("nsec"); + default: return string("error"); + } + }; +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /** returns the value in ns to send to server as the + * server class slsdetector accepts in ns. + * @param unit unit of time + * @param value time + * returns time value in ns + */ + static double getNSTime(timeUnit unit, double value){ + double valueNS=value; + switch(unit){ + case HOURS: valueNS*=60; + case MINUTES: valueNS*=60; + case SECONDS: valueNS*=1000; + case MILLISECONDS: valueNS*=1000; + case MICROSECONDS: valueNS*=1000; + case NANOSECONDS: + default:; + } + return valueNS; + }; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /** returns the time in the appropriate time unit + * @param unit unit of time + * @param value time in seconds + * returns the corresponding time value + */ + static double getCorrectTime(timeUnit& unit, double value){ + int intUnit = (int)SECONDS; + + /**0 ms*/ + if(!value){ + unit = MILLISECONDS; + return value; + } + + /** hr, min, sec */ + if(value>=1){ + double newVal = value; + while((newVal>=1)&&(intUnit>=(int)HOURS)){ + /** value retains the old value */ + value = newVal; + newVal = value/(double)60; + intUnit--; + } + /** returning the previous value*/ + unit = (timeUnit)(intUnit+1); + return value; + } + /** ms, us, ns */ + else{ + while((value<1)&&(intUnit<(int)NANOSECONDS)){ + value = value*(double)1000; + intUnit++; + } + unit = (timeUnit)(intUnit); + return value; + } + }; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /**displays an warning,error,info message + * @param message the message to be displayed + * @param source is the tab or the source of the message + * */ + static int Message(MessageIndex index, string message,string source) + { + static QMessageBox* msgBox; + size_t pos; + + //replace all \n with
+ pos = 0; + while((pos = message.find("\n", pos)) != string::npos){ + message.replace(pos, 1, "
"); + pos += 1; + } + message.append(string("

Source:   ") + source + string("

")); + + switch(index){ + case WARNING: + msgBox= new QMessageBox(QMessageBox::Warning,"WARNING",tr(message.c_str()),QMessageBox::Ok, msgBox); + break; + case CRITICAL: + msgBox= new QMessageBox(QMessageBox::Critical,"CRITICAL",tr(message.c_str()),QMessageBox::Ok, msgBox); + break; + case INFORMATION: + msgBox= new QMessageBox(QMessageBox::Information,"INFORMATION",tr(message.c_str()),QMessageBox::Ok, msgBox); + break; + default: + msgBox= new QMessageBox(QMessageBox::Question,"QUESTION",tr(message.c_str()),QMessageBox::Ok| QMessageBox::Cancel, msgBox); + break; + } + //msgBox->setDetailedText(QString(source.c_str())); //close button doesnt work with this static function and this + if(msgBox->exec()==QMessageBox::Ok) return OK; else return FAIL; + } + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /** range of x and y axes + */ + enum range{ + XMINIMUM, + XMAXIMUM, + YMINIMUM, + YMAXIMUM + }; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /**gets error mask and displays the message if it exists + * @param myDet is the multidetector object + /returns error message else an empty string + * */ + static string checkErrorMessage(multiSlsDetector*& myDet, string title = "Main"){ + + + int errorLevel= (int)WARNING; + string retval=""; + size_t pos; + + + retval = myDet->getErrorMessage(errorLevel); + + if(!retval.empty()){ + //replace all \n with
+ pos = 0; + while((pos = retval.find("\n", pos)) != string::npos){ + retval.replace(pos, 1, "
"); + pos += 1; + } + + //get rid of the last \n + if(retval.find_last_of("
")==retval.length()-1) + retval.erase((int)retval.find_last_of("
")-3,4); + + retval.insert(0,""); + retval.append(""); + + //display message + qDefs::Message((MessageIndex)errorLevel,retval,title); + } + + myDet->clearAllErrorMask(); + return retval; + }; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + /**gets error mask and displays the message if it exists + * @param myDet is the slsdetector object + * @param show to display the error message + /returns error message else an empty string + * */ + static string checkErrorMessage(slsDetector*& myDet, string title = "Main", bool show = true){ + + + int errorLevel= (int)WARNING; + string retval=""; + size_t pos; + int64_t emask=0; + + emask = myDet->getErrorMask(); + retval = myDet->getErrorMessage(emask); + + if(!retval.empty()){ + //replace all \n with
+ pos = 0; + while((pos = retval.find("\n", pos)) != string::npos){ + retval.replace(pos, 1, "
"); + pos += 1; + } + + //get rid of the last \n + if(retval.find_last_of("
")==retval.length()-1) + retval.erase((int)retval.find_last_of("
")-3,4); + + retval.insert(0,""); + retval.append(""); + + //display message + if(show) + qDefs::Message((MessageIndex)errorLevel,retval,title); + } + + myDet->clearErrorMask(); + + return retval; + }; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + /** scan arguments*/ + enum scanArgumentList{ + None, + Level0, + Level1, + FileIndex, + AllFrames + }; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + /** histogram arguments*/ + enum histogramArgumentList{ + Intensity, + histLevel0, + histLevel1 + }; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +}; + + +#endif /* QDEFS_H */ diff --git a/slsDetectorGui/include/qDetectorMain.h b/slsDetectorGui/include/qDetectorMain.h new file mode 100644 index 0000000000..7574380f56 --- /dev/null +++ b/slsDetectorGui/include/qDetectorMain.h @@ -0,0 +1,201 @@ +/* + * qDetectorMain.h + * Main Window of the GUI + * Created on: Apr 30, 2012 + * Author: l_maliakal_d + */ +#ifndef QDETECTORMAIN_H +#define QDETECTORMAIN_H + +#include "qDefs.h" + +/** Form Header */ +#include "ui_form_detectormain.h" +/** Qt Project Class Headers */ +#include "qDrawPlot.h" +#include "qTabMeasurement.h" +#include "qTabDataOutput.h" +class qTabPlot; +class qTabActions; +class qTabAdvanced; +class qTabSettings; +class qTabDebugging; +class qTabDeveloper; +class qTabMessages; +class qServer; +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Include Headers */ +#include +#include +#include +#include + +#include +using namespace std; + +/** To Over-ride the QTabWidget class to get the tabBar */ +class MyTabWidget:public QTabWidget{ +public: + MyTabWidget(QWidget* parent = 0) {setParent(parent);} + /** Overridden method from QTabWidget */ + QTabBar* tabBar(){return QTabWidget::tabBar();} +}; + + +/** + *@short Main window of the GUI. + */ +class qDetectorMain:public QMainWindow, private Ui::DetectorMainObject{ + Q_OBJECT + + +public: + /** \short Main Window constructor. + * This is mainly used to create detector object and all the tabs + * @param argc number of command line arguments for server options + * @param argv server options + * @param app the qapplication + * @param parent makes the parent window 0 by default + * */ + qDetectorMain(int argc, char **argv, QApplication *app, QWidget *parent = 0); + + /**Destructor + * */ + ~qDetectorMain(); + + /** Starts or stops Acquisition From gui client + * @param start 1 for start and 0 to stop + /returns success or fail + */ + int StartStopAcquisitionFromClient(bool start); + + /** Returns if plot is running + */ + bool isPlotRunning(){return myPlot->isRunning();}; + + /** Returns progress bar value */ + int GetProgress(){return tab_measurement->GetProgress();}; + + /** Returns file path */ + QString GetFilePath(){QString s = QString(myDet->getFilePath().c_str());qDefs::checkErrorMessage(myDet); return s;}; + + /** Verifies if output directories for all the receivers exist */ + int DoesOutputDirExist(){return tab_dataoutput->VerifyOutputDirectory();}; + + bool isCurrentlyTabDeveloper(); + +private: + /** The Qt Application */ + QApplication *theApp; + /** The sls detector object */ + multiSlsDetector *myDet; + /** sls detector id */ + int detID; + /** true for mythen and eiger */ + bool digitalDetector; + /** The Plot widget */ + qDrawPlot *myPlot; + /**Tab Widget */ + MyTabWidget *tabs; + /**Layout of the central Widget */ + QGridLayout *layoutTabs; + /** default height of Plot Window when docked */ + int heightPlotWindow; + /** default height of central widgetwhen plot Window when docked */ + int heightCentralWidget; + /** The default zooming tool tip */ + QString zoomToolTip; + + /** The default tab heading color */ + QColor defaultTabColor; + /** enumeration of the tabs */ + enum {Measurement, Settings, DataOutput, Plot, Actions, Advanced, Debugging, Developer, Messages, NumberOfTabs }; + /* Scroll Area for the tabs**/ + QScrollArea *scroll[NumberOfTabs]; + /**Measurement tab */ + qTabMeasurement *tab_measurement; + /**DataOutput tab */ + qTabDataOutput *tab_dataoutput; + /**Plot tab */ + qTabPlot *tab_plot; + /**Actions tab */ + qTabActions *tab_actions; + /**Settings tab */ + qTabSettings *tab_settings; + /**Advanced tab */ + qTabAdvanced *tab_advanced; + /**Debugging tab */ + qTabDebugging *tab_debugging; + /**Developer tab */ + qTabDeveloper *tab_developer; + /**Messages tab */ + qTabMessages *tab_messages; + + /** server object*/ + qServer *myServer; + + /**if the developer tab should be enabled,known from command line */ + int isDeveloper; + + /**Sets up the layout of the widget + * */ + void SetUpWidgetWindow(); + + /**Sets up detector + * @param fName file name of the config file at start up + * */ + void SetUpDetector(const string fName); + + /**Sets up the signals and the slots + * */ + void Initialization(); + + /** Loads config file at start up + * */ + void LoadConfigFile(const string fName); + + +private slots: +/** Enables modes as selected -Debug, Expert, Dockable(calls setdockablemode()) + * */ +void EnableModes(QAction *action); + +/** Executes actions in the utilities menu as selected + * */ +void ExecuteUtilities(QAction *action); + +/** Executes actions in the utilities menu as selected + * */ +void ExecuteHelp(QAction *action); + +/** Refreshes the tab each time the tab is changed. Also displays the next enabled tab + * */ +void Refresh(int index); + +/** Resizes the main window if the plot is docked/undocked + * @param b bool TRUE if undocked(outside main window), FALSE docked + * */ +void ResizeMainWindow(bool b); + +/** Enables/disables tabs depending on if acquisition is currently in progress + * */ +void EnableTabs(); + +/** Set the tool tip of mouse controlled zooming depening on if its enabled/disabled + * */ +void SetZoomToolTip(bool disable); + +/** Uncheck the Listen to gui client mode when the server has exited + */ +void UncheckServer(); + +protected: +/** Adjust the resizing to resize plot, except for actions tab + * */ +void resizeEvent(QResizeEvent* event); + + +}; + +#endif /* QDETECTORMAIN_H */ diff --git a/slsDetectorGui/include/qDrawPlot.h b/slsDetectorGui/include/qDrawPlot.h new file mode 100644 index 0000000000..a600acee4f --- /dev/null +++ b/slsDetectorGui/include/qDrawPlot.h @@ -0,0 +1,590 @@ +/* + * qDrawPlot.h + * + * Created on: May 7, 2012 + * Author: Dhanya Maliakal + */ +#ifndef QDRAWPLOT_H +#define QDRAWPLOT_H + + +#include "qDefs.h" + +/** Project Class Headers */ +class multiSlsDetector; +#include "detectorData.h" +/** Qt Project Class Headers */ +#include "SlsQt1DPlot.h" +#include "SlsQt2DPlotLayout.h" +class qCloneWidget; +/** Qt Include Headers */ +#include +#include +#include +#include +#include +#include "qwt_symbol.h" + + +#include +#include +#include +#include +#include +#include + +/** C++ Include Headers */ + + +#define MAX_1DPLOTS 10 + + +/** + *@short Sets up the plot widget + */ +class qDrawPlot:public QWidget{ + Q_OBJECT + + + + +public: + /** \short The constructor */ + qDrawPlot(QWidget *parent,multiSlsDetector*& detector); + /** Destructor */ + ~qDrawPlot(); + + /**is an acquisition running , need it to prevent measurement tab + * from being refreshed when switching tabs during acquisition */ + bool isRunning(){return running;}; + /** gets the progress of acquisition to the measurement tab*/ + int GetProgress(){return progress;}; + /** gets the file index to the measurement tab*/ + int GetFileIndex(){return currentFileIndex;}; + /** gets the frame index to the measurement tab*/ + int GetFrameIndex(){return currentFrameIndex;}; + /** sets file write enable , if not enabled, + * file index wont increase and so you need secondary titles to differentitate between plots*/ + void SetEnableFileWrite(bool enable){fileSaveEnable = enable;}; + + /** sets plot Title prefix*/ + void SetPlotTitlePrefix(QString title) {plotTitle_prefix = title;} + /** sets 1D X Axis Title */ + void SetHistXAxisTitle(QString title) {histXAxisTitle = title;} + /** sets 1D Y Axis Title */ + void SetHistYAxisTitle(QString title) {histYAxisTitle = title;} + /** sets 2D X Axis Title */ + void SetImageXAxisTitle(QString title) {imageXAxisTitle = title;} + /** sets 2D Y Axis Title */ + void SetImageYAxisTitle(QString title) {imageYAxisTitle = title;} + /** sets 2D Z Axis Title */ + void SetImageZAxisTitle(QString title) {imageZAxisTitle = title;} + /** Disables zoom if any of the axes range are checked and fixed with a value */ + void DisableZoom(bool disable); + /** Enables plot from the plot tab*/ + void EnablePlot(bool enable); + /** Enable angle plot */ + void EnableAnglePlot(bool enable){anglePlot = enable;}; + + /** Its a reminder to update plot to set the xy range + * This is done only when there is a plot to update */ + void SetXYRange(bool changed){XYRangeChanged = changed;}; + /**Sets the min/max for x/y + * @param val is the value to be set + * @param xy is xmin,xmax,ymin or ymax */ + void SetXYRangeValues(double val,qDefs::range xy){XYRangeValues[xy]=val;}; + /**Sets if min/max for x/y is enabled + * @param changed is if this has been changed + * @param xy is xmin,xmax,ymin or ymax */ + void IsXYRangeValues(bool changed,qDefs::range xy){IsXYRange[xy]=changed;}; + + /** Get minimum Plot timer - between plots */ + double GetMinimumPlotTimer(){return PLOT_TIMER_MS;}; + /** Set Plot timer - between plots in ms*/ + void SetPlotTimer(double time); + /** Set Plot frame factor - between plots, also for receiver if exists */ + void SetFrameFactor(int frame); + + /** Starts or stop acquisition + * Calls startDaq() function + * @param stop_if_running is 0 to stop acquisition and 1 to start acquisition + */ + void StartStopDaqToggle(bool stop_if_running=0); + /** Set frame enabled + * @param enable enable*/ + void setFrameEnabled(bool enable){isFrameEnabled = enable;}; + /** Set trigger enabled + * @param enable enable */ + void setTriggerEnabled(bool enable){isTriggerEnabled = enable;}; + + /** Updates the trimbit plot + * @param fromDetector is true if the trimbits should be loaded from detector + * @param Histogram true if histogram, else data graph + * returns ok/fail + * */ + int UpdateTrimbitPlot(bool fromDetector,bool Histogram); + + /** This is set once client initiates start/stop acquisition + * and this is reset when the gui really starts/stops- to know when to return + */ + void SetClientInitiated(){clientInitiated = true;}; + + /** Get client intiated variable. This is set once client initiates start/stop acquisition + * and this is reset when the gui really starts/stops- to know when to return + */ + bool GetClientInitiated(){return clientInitiated;}; + + /** Update all ranges, interpolate etc after cloning + * parameters are if they are checked or not + */ + void UpdateAfterCloning(bool points, bool logy, bool interpolate, bool contour, bool logz); + + /** set binary range */ + void SetBinary(bool enable, int from=0, int to=0); + + /** Enable/Disable Histogram */ + void SetHistogram(bool enable,int histArg, int min=0, int max=0, double size=0){histogram = enable;histogramArgument = histArg; histFrom=min;histTo=max;histSize=size;}; + +public slots: +/** To select 1D or 2D plot + @param i is 1 for 1D, else 2D plot */ +void SelectPlot(int i=2); +/** To select 1D plot */ +void Select1DPlot() {SelectPlot(1);} +/** To select 2D plot */ +void Select2DPlot() {SelectPlot(2);} +/** To clear plot */ +void Clear1DPlot(); +/** Creates a clone of the plot */ +void ClonePlot(); +/** Closes all the clone plots */ +void CloseClones(); +/** Saves all the clone plots */ +void SaveClones(); +/** To Save plot */ +void SavePlot(); +/** Save all plots **/ +void SaveAll(bool enable){saveAll = enable;}; +/** Sets persistency from plot tab */ +void SetPersistency(int val); +/** sets style of plot to lines*/ +void SetLines(bool enable){lines = enable;}; +/** sets markers */ +void SetMarkers(bool enable){markers = enable;}; +/** sets the scan argument to prepare the plot*/ +void SetScanArgument(int scanArg); +/** sets stop_signal to true */ +void StopAcquisition(){ stop_signal = true; }; +/** Set/unset pedestal */ +void SetPedestal(bool enable); +/** Recalculate Pedestal */ +void RecalculatePedestal(); +/** Set/unset accumulate */ +void SetAccumulate(bool enable); +/** Reset accumulation */ +void ResetAccumulate(); +/** Display Statistics */ +void DisplayStatistics(bool enable); + + + + + + +private: +/** Initializes all its members and the thread */ +void Initialization(); +/** Sets up the widget */ +void SetupWidgetWindow(); + + +/** Gets the image title */ +const char* GetImageTitle() {return imageTitle.c_str();} +/** Gets the hist title for a 1D plot */ +const char* GetHistTitle(int i) {return (i>=0&&i=0&&isetStyle(QwtPlotCurve::Lines); else h->setStyle(QwtPlotCurve::Dots); +#if QWT_VERSION<0x060000 + if(markers) h->setSymbol(*marker); else h->setSymbol(*noMarker); +#else + if(markers) h->setSymbol(marker); else h->setSymbol(noMarker); +#endif +}; + + +/** Find Statistics + * @param min is the minimum value + * @param max is the maximum value + * @param sum is the sum of all values + * @param array is the array to get statistics from + * @param size is the size of the array */ +void GetStatistics(double &min, double &max, double &sum, double* array, int size); + + + + + +private slots: +/** To update plot + * */ +void UpdatePlot(); +/** To start or stop acquisition + * @param start is 1 to start and 0 to stop acquisition + * */ +void StartDaq(bool start); +/** To set the reference to zero after closing a clone + * @param id is the id of the clone + * */ +void CloneCloseEvent(int id); +/**After a pause, the gui is allowed to collect the data + * this is called when it is over + * */ +void UpdatePause(){data_pause_over=true;}; +/** Shows the first save error message while automatic saving + * @param fileName file name of the first file that it tried to save. + * */ +void ShowSaveErrorMessage(QString fileName); +/**Shows an error message when acquisition stopped unexpectedly + * @param status is the status of the detector + * */ +void ShowAcquisitionErrorMessage(QString status); + + +private: +/** The sls detector object */ +multiSlsDetector *myDet; + +/** detectot type */ +slsDetectorDefs::detectorType detType; + + +/** Widgets needed to plot the clone */ +/** Max Number of Clone Windows */ +static const int MAXCloneWindows = 50; +/** Array of clone window widget pointers */ +qCloneWidget *winClone[MAXCloneWindows]; + +/** Widgets needed to set up plot*/ +QGroupBox *boxPlot; +QGridLayout *layout; +QGridLayout *plotLayout; +/** Timer to update plot */ +QTimer* plot_update_timer; + +/** Timer to pause getting data from client */ +QTimer* data_pause_timer; +bool data_pause_over; + + +/** 1D object */ +SlsQt1DPlot* plot1D; +/** 2D object */ +SlsQt2DPlotLayout* plot2D; +/** vector of 1D hist values */ +QVector plot1D_hists; + + +/**label with frame index for those with many frames per file*/ +QLabel *histFrameIndexTitle; + + +/** Current Measurement */ +int currentMeasurement; +/** currentFrame */ +int currentFrame; +/** variable to check if its the nth frame */ +int numFactor; +/** current Scan Division Level */ +int currentScanDivLevel; +/** current scan Value */ +double currentScanValue; +/** Number of Exposures */ +int number_of_exposures; +/** Number of Frames Per Measurement */ +int number_of_frames; +/** Duration between Exposures */ +double acquisitionPeriod; +/** Acquisition Time */ +double exposureTime; +/** Current file index*/ +int currentFileIndex; +/** Current frame index*/ +int currentFrameIndex; + +/**variables for threads */ +/** */ +volatile bool stop_signal; +/** */ +pthread_mutex_t last_image_complete_mutex; + +/**variables for histograms */ +/** X Axis Title in 2D */ +QString imageXAxisTitle; +/** Y Axis Title in 2D */ +QString imageYAxisTitle; +/** Z Axis Title in 2D */ +QString imageZAxisTitle; +/** X Axis Title in 1D */ +QString histXAxisTitle; +/** Y Axis Title in 1D */ +QString histYAxisTitle; +/** Title for all the graphs in 1D */ +std::string histTitle[MAX_1DPLOTS]; +/** Title in 2D */ +std::string imageTitle; +/** plot Title */ +QString plotTitle; +/** plot Title prefix */ +QString plotTitle_prefix; +/** 1D or 2D */ +unsigned int plot_in_scope; +/** Number of Pixels in X Axis */ +unsigned int nPixelsX; +/** Number of angle Pixels in X Axis */ +int nAnglePixelsX; +/** Number of pixel bins in Y Axis */ +int nPixelsY; +/** Min Pixel number for Y Axis*/ +double minPixelsY; +/** Max Pixel number for Y Axis*/ +double maxPixelsY; +/** starting pixel */ +double startPixel; +/** end Pixel*/ +double endPixel; +/** pixel width */ +double pixelWidth; + +/** Current Image Number */ +unsigned int lastImageNumber; + +/** Number of graphs in 1D */ +unsigned int nHists; +/** Total Number of X axis values/channels in 1D */ +int histNBins; +/** X Axis value in 1D */ +double* histXAxis; +/** Y Axis value in 1D */ +double* histYAxis[MAX_1DPLOTS]; +/** X Axis for angles in 1D */ +double* histXAngleAxis; +/** Y Axis for angles in 1D (no persistency) */ +double* histYAngleAxis; +/** X Axis for trimbits in 1D */ +double* histTrimbits; + + +/** Current Image Values in 2D */ +double* lastImageArray; + +/**persistency to be reached*/ +int persistency; +/** persistency takes time to reach as it increases per frame + * this is the current one */ +int currentPersistency; +/** to update the progress for each getData() so that + * measurement tab can request on a timer basis*/ +int progress; +/**If plot is enabled from plot tab*/ +bool plotEnable; +/**If plot is dotted */ +bool lines; +bool markers; +/** Plot marker */ +QwtSymbol *marker; +QwtSymbol *noMarker; +/** Save all plots */ +bool saveAll; +/** If error, while automatically saving plots, checks this at the end of an acquistion */ +bool saveError; +/** index of last saved image for automatic saving*/ +int lastSavedFrame; +/** index of measurement number of last saved image for automatic saving*/ +int lastSavedMeasurement; +/**if an acquisition is running, so as not to refresh tab + * and also to update plot only if running (while creating clones)*/ +bool running; + +/** if the min/max of x and y has been changed, + * to notify while plotting */ +bool XYRangeChanged; +/**the specific min/max of x/y*/ +double XYRangeValues[4]; +/**if the specific min/max of x/y is enabled */ +bool IsXYRange[4]; + +/** Default timer between plots*/ +static const double PLOT_TIMER_MS; + +/** Specific timer value between plots */ +double timerValue; +/** every nth frame when to plot */ +int frameFactor; +/**if frame is enabled in measurement tab */ +bool isFrameEnabled; +/**if trigger is enabled in measurement tab */ +bool isTriggerEnabled; + +/** scan arguments*/ +int scanArgument; + +/** histogram arguments*/ +int histogramArgument; + +/** enable angle plot */ +bool anglePlot; +/** prevents err msg displaying twice when detector stopped, "transmitting" */ +bool alreadyDisplayed; + +/**saves the file path and file name, not to access shared memory while running*/ +QString filePath; +QString fileName; + +/** Max Number of Clone Windows */ +static const int TRIM_HISTOGRAM_XMAX = 63; + +/**if the values increment backwards*/ +bool backwardScanPlot; + +/**if files will be saved and index increased*/ +bool fileSaveEnable; + + +/** true of originally 2d */ +bool originally2D; + + +//pedstal +/** Number of pedestal frames*/ +static const int NUM_PEDESTAL_FRAMES = 20; +/** set/unset pedestal*/ +bool pedestal; +/** pedestal values */ +double* pedestalVals; +/** temporary pedestal values to hide while recalculating*/ +double* tempPedestalVals; +/** count for 20 frames to calculate the pedestal */ +int pedestalCount; +/** start pedestal calculation */ +bool startPedestalCal; + +//accumulation +/** set/unset accumulation */ +bool accumulate; +/** to reset accumulation */ +bool resetAccumulate; + +/** range for binary plot output */ +bool binary; +int binaryFrom; +int binaryTo; + +/** this is set when client starts/stops acquisition + * and is reset once the gui really starts/stops */ +bool clientInitiated; + + +/** display statistics widgets */ +QWidget *widgetStatistics; +QLabel *lblMinDisp; +QLabel *lblMaxDisp; +QLabel *lblSumDisp; + +bool displayStatistics; + + +/* histogram */ +bool histogram; +int histFrom; +int histTo; +double histSize; +QwtPlotGrid *grid; +QwtPlotHistogram *plotHistogram; +QVector histogramSamples; + + +bool plotRequired; + + +signals: +void UpdatingPlotFinished(); +void InterpolateSignal(bool); +void ContourSignal(bool); +void LogzSignal(bool); +void LogySignal(bool); +void SetZRangeSignal(double,double); +void ResetZMinZMaxSignal(bool,bool,double,double); +void SetCurrentMeasurementSignal(int); +void saveErrorSignal(QString); +void AcquisitionErrorSignal(QString); +void UpdatePlotSignal(); +}; + + + +#endif /* QDRAWPLOT_H */ diff --git a/slsDetectorGui/include/qScanWidget.h b/slsDetectorGui/include/qScanWidget.h new file mode 100644 index 0000000000..329a211dad --- /dev/null +++ b/slsDetectorGui/include/qScanWidget.h @@ -0,0 +1,193 @@ +/* + * qScanWidget.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QSCANWIDGET_H_ +#define QSCANWIDGET_H_ + +#include "qDefs.h" + +/** Form Header */ +#include "ui_form_scan.h" +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Include Headers */ +#include +/** C++ Include Headers */ +#include +#include +using namespace std; + + +class qScanWidget : public QWidget,private Ui::ScanObject{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + */ + qScanWidget(QWidget *parent, multiSlsDetector*& detector); + + ~qScanWidget(); + + /**to update the widgets*/ + void Refresh(); + + + /**number of scan widgets*/ + static int NUM_SCAN_WIDGETS; + +private: + /** The sls detector object */ + multiSlsDetector *myDet; + /**id of the scan widget*/ + int id; + /**type of steps*/ + enum sizeIndex{RangeValues, CustomValues, FileValues}; + enum modes{None,EnergyScan,ThresholdScan,TrimbitsScan,PositionScan,CustomScript,NumModes}; + static const string modeNames[NumModes]; + + /**values*/ + int actualNumSteps; + vector positions; + + /**non error font*/ + QPalette normal; + QPalette red; + QString customTip; + QString fileTip; + QString rangeTip; + + /**widgets needed for diff size types*/ + QButtonGroup *btnGroup; + QStackedLayout *stackedLayout; + QLabel *lblFrom; + QDoubleSpinBox *spinFrom; + QLabel *lblTo; + QDoubleSpinBox *spinTo; + QLabel *lblSize; + QDoubleSpinBox *spinSize; + QComboBox *comboCustom; + QPushButton *btnCustom; + QLineEdit *dispFile; + QPushButton *btnFile; + + + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals */ + void Initialization(); + + /** Sets up all the parameters from server/client */ + void LoadPositions(); + + /** Sets up the scan parameters + * returns if it was set + */ + int SetScan(int mode); + +private slots: +/** Enables widgets depending on which size is clicked. + * Options: constant size,specific values,values from file + * */ +void EnableSizeWidgets(); + +/** Sets the scan or script. Accordingly enables, disables other widgets + * @param mode value chosen*/ +void SetMode(int mode); + +/** Browse for the script + * */ +void BrowsePath(); + +/** Sets the script file + * */ +void SetScriptFile(); + +/** Set Parameter + * */ +void SetParameter(); + +/** Set precision + * @param value value of precision to be set + * */ +void SetPrecision(int value); + +/** Set number of steps + * */ +void SetNSteps(); + +/**Checks if size is zero and return FAIL if it does + * */ +int RangeCheckSizeZero(); + +/**returns ok and number of steps if valid + * @param number of steps + * */ +int RangeCheckNumValid(int &num); + +/**returns fail if to is not exact + * */ +int RangeCheckToValid(); + +/** Sets number of steps if from changed + * */ +void RangeFromChanged(); + +/** Sets number of steps if to changed + * */ +void RangeToChanged(); + +/** Sets s of steps if size changed + * */ +void RangeSizeChanged(); + +/** Set range for scan + * */ +void SetRangeSteps(); + + +/** Range type: If size is changed, + * the Number of steps is calculated + * */ +//void RangeCalculateNumSteps(); + +/** Range type: If size is changed, the To is calculated + * */ +//void RangeCalculateTo(); + + +/** Set custom steps + * returns OK if set properly + * */ +int SetCustomSteps(); + +/** Delete custom steps + * */ +void DeleteCustomSteps(); + +/** Reads the file to get the steps + * */ +void SetFileSteps(); + +/** Browses for the file path for steps + * */ +void BrowseFileStepsPath(); + + + +signals: +void EnableScanBox(); +}; + + + + +#endif /* QSCANWIDGET_H_ */ + diff --git a/slsDetectorGui/include/qServer.h b/slsDetectorGui/include/qServer.h new file mode 100644 index 0000000000..bd26080c62 --- /dev/null +++ b/slsDetectorGui/include/qServer.h @@ -0,0 +1,137 @@ +/* + * qServer.h.h + * + * Created on: Feb 27, 2013 + * Author: Dhanya Maliakal + */ +#ifndef QSERVER_H +#define QSERVER_H + + +/** Qt Project Class Headers */ +#include "sls_detector_defs.h" +#include "qDefs.h" +class qDetectorMain; +/** Project Class Headers */ +class multiSlsDetector; +class MySocketTCP; +/** Qt Include Headers */ +#include +/** C++ Include Headers */ + + +/** + *@short Sets up the gui server + */ +class qServer: public QWidget, public virtual slsDetectorDefs{ + Q_OBJECT + + +public: + /** \short The constructor */ + qServer(qDetectorMain *t); + /** Destructor */ + ~qServer(); + + /** Start or Stop Gui Server + * @param start is 1 to start and 0 to stop + */ + int StartStopServer(int start); + +private: + /** assigns functions to the fnum enum */ + int FunctionTable(); + + /** Decodes Function */ + int DecodeFunction(MySocketTCP* sock); + + /** Exit Server */ + int ExitServer(); + + + /** + * Static function - Thread started which listens to client gui. + * Called by StartStopServer() + * @param this_pointer pointer to this object + */ + static void* StartServerThread(void *this_pointer); + + /** + * Thread started which listens to client gui. + * Called by startServerThread() + * + */ + int StartServer(); + + /** + * Static function - Thread started which listens to client gui to stop acquisition + * Called by StartStopServer() + * @param this_pointer pointer to this object + */ + static void* StopServerThread(void *this_pointer); + + /** + * Thread started which listens to client gui to stop acquisition. + * Called by startServerThread() + * + */ + int StopServer(); + + + + /** Get Detector Status */ + int GetStatus(); + + /** Starts Acquisition */ + int StartAcquisition(); + + /** Stops Acquisition */ + int StopsAcquisition(); + + /** Acquire - blocking */ + int Acquire(); + + + + /**The measurement tab object*/ + qDetectorMain *myMainTab; + + /** tcp socket to gui client */ + MySocketTCP *mySocket; + /** tcp socket to gui client to stop or get status */ + MySocketTCP *myStopSocket; + + /** server port number*/ + int port_no; + + /** Lock Status if server locked to a client */ + int lockStatus; + + /** Function List */ + static const int NUMBER_OF_FUNCTIONS = 256; + int (qServer::*flist[NUMBER_OF_FUNCTIONS])(); + + + /** if the gui server thread is running*/ + static int gui_server_thread_running; + /** thread listening to gui client*/ + pthread_t gui_server_thread; + /** thread also listening to gui client to stop acquisition*/ + pthread_t gui_stop_server_thread; + + /** server started */ + int checkStarted; + int checkStopStarted; + + /** Message */ + char mess[MAX_STR_LENGTH]; + + +signals: + void ServerStoppedSignal(); + +}; + + + +#endif /* QSERVER_H */ diff --git a/slsDetectorGui/include/qTabActions.h b/slsDetectorGui/include/qTabActions.h new file mode 100644 index 0000000000..d5d497fde5 --- /dev/null +++ b/slsDetectorGui/include/qTabActions.h @@ -0,0 +1,150 @@ +/* + * qTabActions.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABACTIONS_H_ +#define QTABACTIONS_H_ + +#include "qDefs.h" + + +/* Qt Project Class Headers */ +#include "qActionsWidget.h" +#include "qScanWidget.h" +/** C++ Project Class Headers */ +class multiSlsDetector; +/** Qt Include Headers */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/** + *@short sets up the acions parameters + */ +class qTabActions:public QWidget{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + */ + qTabActions(QWidget *parent,multiSlsDetector*& detector); + + /** Destructor + */ + ~qTabActions(); + + /** To refresh and update widgets + */ + void Refresh(); + + +public slots: + /** Disable Positions + * @param enable true if to disable + * */ + void EnablePositions(bool enable); + + +private: + /** The sls detector object */ + multiSlsDetector *myDet; + + slsDetectorDefs::detectorType detType; + + + enum actionIndex{ + ActionStart, + Scan0, + Scan1, + ActionBefore, + NumPositions, + HeaderBefore, + HeaderAfter, + ActionAfter, + ActionStop, + NumTotalActions}; + + QGridLayout *gridLayout; + QButtonGroup *group; + QPalette *palette; + + /** all action widget objects */ + qActionsWidget *actionWidget[6]; + qScanWidget *scanWidget[2]; + QWidget *positionWidget; + QPushButton *btnExpand[NumTotalActions]; + QLabel *lblName[NumTotalActions]; + + + /** NumPositions widget */ + QLabel *lblNumPos; + QLabel *lblPosList; + QSpinBox *spinNumPos; + QComboBox *comboPos; + QPushButton *btnDelete; + QCheckBox *chkInvert; + QCheckBox *chkSeparate; + QCheckBox *chkReturn; + + double *positions; + QPalette normal; + QIcon *iconPlus; + QIcon *iconMinus; + + + /** Sets up the widget */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals */ + void Initialization(); + + /** creates the Num Positions object */ + void CreatePositionsWidget(); + + /** Returns the index in each of the classes + * of actionwidget and scanwidget + * @param index the index in the list of all widgets + * returns actual index of the class + */ + int GetActualIndex(int index); + + /** Updates to green color if collapsed and mode not none + */ + void UpdateCollapseColors(); + + + + +private slots: + /** To Expand the Action Widget + * */ + void Expand(QAbstractButton *button); + + /** Sets the positions list and the number of positions + * */ + void SetPosition(); + + /** Deletes current position + * */ + void DeletePosition(); + + +signals: + void EnableScanBox(); + +}; + +#endif /* QTABACTIONS_H_ */ + diff --git a/slsDetectorGui/include/qTabAdvanced.h b/slsDetectorGui/include/qTabAdvanced.h new file mode 100644 index 0000000000..05bde9ccf2 --- /dev/null +++ b/slsDetectorGui/include/qTabAdvanced.h @@ -0,0 +1,234 @@ +/* + * qTabAdvanced.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABADVANCED_H_ +#define QTABADVANCED_H_ + +#include "qDefs.h" +#include "sls_detector_defs.h" + +/** Form Header */ +#include "ui_form_tab_advanced.h" +/** Project Class Headers */ +class multiSlsDetector; +class slsDetector; +/** Qt Project Class Headers */ +class qDrawPlot; +/** Qt Include Header */ +#include +#include +/** + *@short sets up the advanced parameters + */ +class qTabAdvanced:public QWidget, private Ui::TabAdvancedObject{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + * @param plot plot object reference + */ + qTabAdvanced(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot); + + /** Destructor + */ + ~qTabAdvanced(); + +public slots: + /** To refresh and update widgets + */ + void Refresh(); + +private: + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals + */ + void Initialization(); + + /** Add ROI Input + * @param num number of inputs to add + */ + void AddROIInput(int num); + + /** Checks for a few conditions before trimming + /returns OK or FAIL + */ + int validateBeforeTrimming(); + + /** update the setalltrimbits value from server + */ + void updateAllTrimbitsFromServer(); + + +private slots: + + /** Enable/Disable Energy and Calibration Logs + */ + void SetLogs(); + + /** Set acquisition time + */ + void SetExposureTime(); + + /** Set the Threshold dac value + */ + void SetThreshold(); + + /** Set output directory for trimming + */ + void SetOutputFile(); + + /** Browse output directory for trimming + */ + void BrowseOutputFile(); + + /** Enables trimming method and calls SetTrimmingMethod if enabled + * @param enable to enable trimming + */ + void EnableTrimming(bool enable); + + /** Enabling resolution and Counts if this is enabled + * @param enable to enable + */ + void SetOptimize(bool enable); + + /** Sets the trimming method + * @param mode trimming method + */ + void SetTrimmingMethod(int mode); + + /** Ensures the right trimming mode and Executes Trimming + */ + void StartTrimming(); + + /** Updates the plot with trimbits from detector/shared memory + */ + void UpdateTrimbitPlot(int id); + + /** Sets control port + * @param port control port + */ + void SetControlPort(int port); + + /** Sets stop port + * @param port stop port + */ + void SetStopPort(int port); + + /** Sets receiver tcp port + * @param port receiver tcp port + */ + void SetRxrTCPPort(int port); + + /** Sets receiver udp port + * @param port receiver udp port + */ + void SetRxrUDPPort(int port); + + /** Sets receiver online + * @param index 1 for online and 0 for offline + */ + void SetReceiverOnline(int index); + + /** Sets detector online + * @param index 1 for online and 0 for offline + */ + void SetOnline(int index); + + /** Sets network parameters like receiver udp ip, + * receiver udp mac, detector ip and detector mac + */ + void SetNetworkParameters(); + + /** Sets the receiver. which also sets the receiver parameters + */ + void SetReceiver(); + + /** Add ROI Input if the value changed in the last slot + */ + void AddROIInputSlot(){AddROIInput(1);}; + + /** Clears all the ROI inputs + */ + void clearROI(); + + /** Gets ROIs from detector and updates it + */ + void updateROIList(); + + /** Sets ROI in detector + */ + void setROI(); + + /** Clears ROI in detector + */ + void clearROIinDetector(); + + /** Clears ROI in detector + */ + void SetDetector(int index); + + /** Set all trimbits to a value + */ + void SetAllTrimbits(); + +private: + /** The multi detector object */ + multiSlsDetector *myDet; + + /** The sls detector object */ + slsDetector *det; + + /** detector type */ + slsDetectorDefs::detectorType detType; + + /** The Plot widget */ + qDrawPlot *myPlot; + + QButtonGroup *btnGroup; + + /** Tool Tip for the output dir */ + QString outputDirTip; + QString errOutputTip; + QString errOnlineTip; + QString detOnlineTip; + QString rxrOnlineTip; + QPalette red; + + /** Trimming mode */ + slsDetectorDefs::trimMode trimmingMode; + static const int TRIMMING_DYNAMIC_RANGE = 32; + static const int TRIMMING_FRAME_NUMBER = 1; + static const int TRIMMING_TRIGGER_NUMBER = 1; + static const int TRIMMING_PROBE_NUMBER = 0; + + bool isEnergy; + bool isAngular; + + /** ROI */ + vector lblFromX; + vector spinFromX; + vector lblFromY; + vector spinFromY; + vector lblToX; + vector spinToX; + vector lblToY; + vector spinToY; + int numRois; + + + + +}; + + + +#endif /* QTABADVANCED_H_ */ diff --git a/slsDetectorGui/include/qTabDataOutput.h b/slsDetectorGui/include/qTabDataOutput.h new file mode 100644 index 0000000000..026c38cc5b --- /dev/null +++ b/slsDetectorGui/include/qTabDataOutput.h @@ -0,0 +1,152 @@ +/* + * qTabDataOutput.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABDATAOUTPUT_H_ +#define QTABDATAOUTPUT_H_ + +#include "qDefs.h" + + +/** Form Header */ +#include "ui_form_tab_dataoutput.h" +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Include Headers */ +#include + + +/** + *@short sets up the DataOutput parameters + */ +class qTabDataOutput:public QWidget, private Ui::TabDataOutputObject{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + */ + qTabDataOutput(QWidget *parent,multiSlsDetector*& detector); + + /** Destructor + */ + ~qTabDataOutput(); + + /** To refresh and update widgets + */ + void Refresh(); + + /** verify output directories + * /returns success or fail + */ + int VerifyOutputDirectory(); + + /** To enable expert mode + * @param enable to enable if true + */ + void SetExpertMode(bool enable); + + +private: + /** The sls detector object */ + multiSlsDetector *myDet; + + /** detector type */ + slsDetectorDefs::detectorType detType; + + + QString flatFieldTip; + QString errFlatFieldTip; + QString outDirTip; + QPalette red; + QPalette black; + QPalette *red1; + QPalette *black1; + + /** enum for the Eiger clock divider */ + enum {FullSpeed, HalfSpeed, QuarterSpeed, SuperSlowSpeed, NumberofSpeeds}; + /** enum for the Eiger readout flags1 */ + enum {Continous, Storeinram}; + /** enum for the Eiger readout flags2 */ + enum {Parallel, NonParallel, Safe}; + + +/** methods */ + /** Sets up the widget */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals */ + void Initialization(); + + /** Populate the readouts + */ + void PopulateDetectors(); + + /** Get Compression */ + void GetCompression(); + + /** update speed */ + void updateSpeedFromServer(); + + /** update flags */ + void updateFlagsFromServer(); + +private slots: + +/** Open dialog to choose the output directory */ +void browseOutputDir(); + +/**set flat field file*/ +void SetFlatField(); + +/** update flat field correction from server */ +void UpdateFlatFieldFromServer(); + +/**browse flat field*/ +void BrowseFlatFieldPath(); + +/**rate correction*/ +void SetRateCorrection(int deadtime=0); + +/** default rate correction */ +void SetDefaultRateCorrection(); + +/** update rate correction from server */ +void UpdateRateCorrectionFromServer(); + +/**angular correction*/ +void SetAngularCorrection(); + +/**discard bad channels*/ +void DiscardBadChannels(); + +/** set output directory*/ +void SetOutputDir(); + +/** set output directory*/ +void GetOutputDir(); + +/** set compression */ +void SetCompression(bool enable); + +/** enable 10GbE */ +void EnableTenGigabitEthernet(bool enable, int get=0); + +/** set speed */ +void setSpeed(); + +/** set flags */ +void setFlags(); + +signals: +/**signal to enable/disable positions in Actions*/ +void AngularConversionSignal(bool); +}; + + + +#endif /* QTABDATAOUTPUT_H_ */ diff --git a/slsDetectorGui/include/qTabDebugging.h b/slsDetectorGui/include/qTabDebugging.h new file mode 100644 index 0000000000..484dfa87d9 --- /dev/null +++ b/slsDetectorGui/include/qTabDebugging.h @@ -0,0 +1,103 @@ +/* + * qTabDebugging.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABDEBUGGING_H_ +#define QTABDEBUGGING_H_ + +#include "qDefs.h" + + +/** Form Header */ +#include "ui_form_tab_debugging.h" +/** Project Class Headers */ +class multiSlsDetector; +class slsDetector; +/** Qt Include Headers */ +#include + + + +/** + *@short sets up the Debugging parameters + */ +class qTabDebugging:public QWidget, private Ui::TabDebuggingObject{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + */ + qTabDebugging(QWidget *parent,multiSlsDetector*& detector); + + /** Destructor + */ + ~qTabDebugging(); + + /** To refresh and update widgets + */ + void Refresh(); + +private: + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals + */ + void Initialization(); + + + +private slots: + /** Updates the module list depending on current detector + */ + void UpdateModuleList(); + + /** Updates the status depending on current detector + */ + void UpdateStatus(); + + /** Gets id and versions etc + */ + void GetInfo(); + + /** Sets id and versions on the display widget + */ + void SetParameters(QTreeWidgetItem *item); + + /** Test detector and module + */ + void TestDetector(); + +private: + /** The multi sls detector object */ + multiSlsDetector *myDet; + + /** detector type */ + slsDetectorDefs::detectorType detType; + + /**sls detecctor object */ + slsDetector *det; + + /** Tree Widget displaying the detectors, modules */ + QTreeWidget *treeDet; + /** Widget displaying the serial numbers, mac addresses etc */ + QFrame *dispFrame; + QLabel *lblDetectorId; + QLabel *lblDetectorSerial; + QLabel *lblDetectorFirmware; + QLabel *lblDetectorSoftware; + QLabel *lblModuleId; + QLabel *lblModuleFirmware; + QLabel *lblModuleSerial; + QPalette *blue; +}; + + + +#endif /* QTABDEBUGGING_H_ */ diff --git a/slsDetectorGui/include/qTabDeveloper.h b/slsDetectorGui/include/qTabDeveloper.h new file mode 100644 index 0000000000..2131a04e2e --- /dev/null +++ b/slsDetectorGui/include/qTabDeveloper.h @@ -0,0 +1,159 @@ +/* + * qTabDeveloper.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABDEVELOPER_H_ +#define QTABDEVELOPER_H_ + +#include "qDefs.h" + + +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Include Headers */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +class qDetectorMain; + +/** C++ Include Headers */ +#include +#include +using namespace std; + + +/**To override the spin box class to have an id and emit it*/ +class MyDoubleSpinBox:public QDoubleSpinBox{ +Q_OBJECT +private: + int myId; + private slots: + void valueChangedWithID() {emit editingFinished(myId);}; + public: + /** Overridden constructor from QDoubleSpinBox */ + MyDoubleSpinBox(int id,QWidget* parent = 0) + :QDoubleSpinBox(parent),myId(id){ + //setParent(parent); + connect(this,SIGNAL(editingFinished()), + this,SLOT(valueChangedWithID())); + } + signals: + void editingFinished(int myId); +}; + + + +/** + *@short sets up the Developer parameters + */ +class qTabDeveloper:public QWidget{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + */ + qTabDeveloper(qDetectorMain *parent,multiSlsDetector*& detector); + + /** Destructor + */ + ~qTabDeveloper(); + + /** To stop ADC Timer when starting acquisition + */ + void StopADCTimer(){if(adcTimer) adcTimer->stop();}; + +private: + /** parent widget */ + qDetectorMain *thisParent; + /** The sls detector object */ + multiSlsDetector *myDet; + /** The sls detector object */ + slsDetector *det; + /** detector type */ + slsDetectorDefs::detectorType detType; + /**number of dac widgets*/ + static int NUM_DAC_WIDGETS; + /**number of adc widgets*/ + static int NUM_ADC_WIDGETS; + + static const int ADC_TIMEOUT = 5000; + + vectordacNames; + vectoradcNames; + + + /**widgets needed*/ + QGridLayout *layout; + QScrollArea *scroll; + QGroupBox *boxDacs; + QGroupBox *boxAdcs; + QLabel *lblDacs[20]; + QLabel *lblAdcs[20]; + MyDoubleSpinBox *spinDacs[20]; + QLabel *lblDacsmV[20]; + QDoubleSpinBox *spinAdcs[20]; + QLabel *lblHV; + QComboBox *comboHV; + QTimer *adcTimer; + QGridLayout *dacLayout; + QString tipHV; + QPalette red; + QComboBox *comboDetector; + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals + */ + void Initialization(); + + /** Sets up the DAC Widgets + */ + void CreateDACWidgets(); + + /** Sets up the ADC Widgets + */ + void CreateADCWidgets(); + + /** Gets the sls index to set/get dac/adc + * @param index is the gui dac/adc index + * returns the sls index + */ + slsDetectorDefs::dacIndex getSLSIndex(int index); + +public slots: + + /** To refresh and update widgets + */ + void Refresh(); + +private slots: + /** Refreshes the adcs + */ + void RefreshAdcs(); + + /** Set Dac values + * @param id id of dac + */ + void SetDacValues(int id); + + /** Set High Voltage + */ + void SetHighVoltage(); +}; + + + +#endif /* QTABDEVELOPER_H_ */ diff --git a/slsDetectorGui/include/qTabMeasurement.h b/slsDetectorGui/include/qTabMeasurement.h new file mode 100644 index 0000000000..76180933a1 --- /dev/null +++ b/slsDetectorGui/include/qTabMeasurement.h @@ -0,0 +1,205 @@ +/* + * qTabMeasurement.h + * + * Created on: May 2, 2012 + * Author: l_maliakal_d + */ +#ifndef QTABMEASUREMENT +#define QTABMEASUREMENT + +#include "qDefs.h" + + +/** Form Header */ +#include "ui_form_tab_measurement.h" +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Project Class Headers */ +#include +#include "qDrawPlot.h" +class qDetectorMain; + +/** + *@short sets up the measurement parameters + */ +class qTabMeasurement:public QWidget, private Ui::TabMeasurementObject{ + Q_OBJECT + +public: + /** \short The constructor + * This tab allows to change the detector settings, the threshold, the number of (non real time) measurements, + * the acquisition time, the file name, the start run index and shows the current progress of the measurement + * via a progress bar and labels inidicating the current position, scan variable, frame number etc. + * Contains the start and stop acquisition button + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + * @param plot plot object reference + */ + qTabMeasurement(qDetectorMain *parent,multiSlsDetector*& detector, qDrawPlot*& plot); + + /** Destructor + */ + ~qTabMeasurement(); + + /** To refresh and update widgets + */ + void Refresh(); + + /** To enable expert mode + * @param enable to enable if true + */ + void SetExpertMode(bool enable); + + /** Returns the status of the Start/Stop Acquisition button + */ + bool GetStartStatus(){return btnStartStop->isChecked();}; + + /** Click the Start/Stop Acquisition button + * This is used if this command came from gui client + */ + void ClickStartStop(){btnStartStop->click();myPlot->SetClientInitiated();}; + + /** Returns progress bar value */ + int GetProgress(){return progressBar->value();}; + + +public slots: + + /** update plot is finished, + * changes start/stop text and enables/disables all widgets + */ + void UpdateFinished(); + + /** updates the current measurement + * @param val the value to be updated + */ + void SetCurrentMeasurement(int val); + + + + +private: + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up the timing mode + */ + void SetupTimingMode(); + + /** Sets up all the slots and signals + */ + void Initialization(); + + /** Enables/Disables all the widgets + */ + void Enable(bool enable); + + /** Validates before enabling or disabling probes */ + void EnableProbes(); + + /** Get timing mode from detector + * @param startup is true when gui has just started up*/ + void GetModeFromDetector(bool startup = false); + + /** Checks if acquisition period is greater than exposure time + * and dsplays in red as a warning */ + void CheckAcqPeriodGreaterThanExp(); + + +private slots: + /** Sets the timing mode + * @ param mode cane be None, Auto, Gated, Trigger Exposure Series, + * Trigger Frame, Trigger Readout, External Trigger Window + */ + void SetTimingMode(int mode); + + /** Set number of measurements + * @param num number of measurements to be set */ + void setNumMeasurements(int num); + + /** Set file name + */ + void setFileName(); + + /** Set index of file name + * @param index index of selection + */ + void setRunIndex(int index); + + /** starts/stops Acquisition + */ + void startStopAcquisition(); + + /** Set number of frames + * @param val number of frames to be set + */ + void setNumFrames(int val); + + /** Set acquisition time + */ + void setExposureTime(); + + /** Set frame period between exposures + */ + void setAcquisitionPeriod(); + + /** Set number of triggers + * @param val number of triggers to be set + */ + void setNumTriggers(int val); + + /** Set delay + */ + void setDelay(); + + /** Set number of gates + * @param val number of gates to be set + */ + void setNumGates(int val); + + /** Set number of probes + * @param val number of probes to be set + */ + void setNumProbes(int val); + + /** Update progress*/ + void UpdateProgress(); + + /** Enable write to file */ + void EnableFileWrite(bool enable); + + +private: + /** parent widget */ + qDetectorMain *thisParent; + /** The sls detector object */ + multiSlsDetector *myDet; + /** The Plot widget */ + qDrawPlot *myPlot; + /** detector type */ + slsDetectorDefs::detectorType detType; + /** enum for the timing mode */ + enum{None, Auto, Trigger_Exp_Series, Trigger_Readout, Gated, Gated_Start, Burst_Trigger, NumTimingModes}; + /** timer to update the progress*/ + QTimer *progressTimer; + /** tool tip variables*/ + QString acqPeriodTip; + QString errPeriodTip; + QPalette red; + /** expert mode */ + bool expertMode; + QIcon *iconStart; + QIcon *iconStop; + /** to access items in settings combobox */ + QStandardItemModel* model; + +signals: + void StartSignal(); + void StopSignal(); + void CheckPlotIntervalSignal(); +}; + + + +#endif /* QTABMEASUREMENT */ diff --git a/slsDetectorGui/include/qTabMessages.h b/slsDetectorGui/include/qTabMessages.h new file mode 100644 index 0000000000..8dd7f611b8 --- /dev/null +++ b/slsDetectorGui/include/qTabMessages.h @@ -0,0 +1,86 @@ +/* + * qTabMessages.h + * + * Created on: Jun 26, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABMESSAGES_H_ +#define QTABMESSAGES_H_ + + +#include "qDefs.h" + + + +/** Project Class Headers */ +class qDetectorMain; +/** Qt Include Headers */ +#include +#include +#include +#include +#include "qDebugStream.h" + +/** + *@short sets up the Messages parameters + */ +class qTabMessages:public QWidget{ + Q_OBJECT + +public: + /** \short The constructor + * @param det the qDetectorMain class reference + */ + qTabMessages(qDetectorMain* m); + + /** Destructor + */ + ~qTabMessages(); + + +private: + /** The qDetectorMain object */ + qDetectorMain *myMainTab; + + /** Log of executed commands */ + QTextEdit *dispLog; + + /** To save the log to file */ + QPushButton *btnSave; + + /** To clear the log to file */ + QPushButton *btnClear; + + /** This class creates the log */ + qDebugStream *qout; + qDebugStream *qerr; + + string errMsg; + +/** methods */ + /** Sets up the widget */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals */ + void Initialization(); + +private slots: +/** Stream log to textedit in GUI */ +void customEvent(QEvent *e); + +/** Save Log to File*/ +void SaveLog(); + +/** Clear Log to File*/ +void ClearLog(); + + + +}; + + + + + +#endif /* QTABMESSAGES_H_ */ diff --git a/slsDetectorGui/include/qTabPlot.h b/slsDetectorGui/include/qTabPlot.h new file mode 100644 index 0000000000..9ed83be7e4 --- /dev/null +++ b/slsDetectorGui/include/qTabPlot.h @@ -0,0 +1,166 @@ +/* + * qTabPlot.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABPLOT_H_ +#define QTABPLOT_H_ + +#include "qDefs.h" + + +/** Form Header */ +#include "ui_form_tab_plot.h" +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Project Class Headers */ +class qDrawPlot; +/** Qt Include Headers */ +#include +#include +#include + + +/** + *@short sets up the Plot parameters + */ +class qTabPlot:public QWidget, private Ui::TabPlotObject{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + * @param plot plot object reference + */ + qTabPlot(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot); + + /** Destructor + */ + ~qTabPlot(); + + /** Sets the scan argument of the plot + */ + void SetScanArgument(); + + /** To refresh and update widgets + */ + void Refresh(); + + +private: + /** The sls detector object */ + multiSlsDetector *myDet; + + /** The Plot widget */ + qDrawPlot *myPlot; + + + /** 1d/2d plot */ + bool isOneD; + bool isOriginallyOneD; + + /**is set if its a possible wrong interval between plots*/ + bool wrongInterval; + + QStackedLayout *stackedLayout; + QSpinBox *spinNthFrame; + QDoubleSpinBox *spinTimeGap; + QComboBox *comboTimeGapUnit; + QButtonGroup *btnGroupScan; + QButtonGroup *btnGroupPlotType; + QButtonGroup *btnGroupHistogram; + + /** some Default Values */ + static QString defaultPlotTitle; + static QString defaultHistXAxisTitle; + static QString defaultHistYAxisTitle; + static QString defaultImageXAxisTitle; + static QString defaultImageYAxisTitle; + static QString defaultImageZAxisTitle; + + /** scans */ + static const QString modeNames[5]; + + /** error palette*/ + QPalette *red; + QString intervalTip; + + + + + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up all the slots and signals + */ + void Initialization(); + + +public slots: + /** Set frequency between plots*/ + void SetFrequency(); + + /** Enable Scan box + */ + void EnableScanBox(); + + +private slots: + /** Selects the plot to display, enables/disables widgets + * @param b true to select plot dimension 1, else false to select 2D + */ + void Select1DPlot(bool b); + + /**Enables Persistency depending on Superimpose checkbox */ + void EnablePersistency(bool enable); + + /**Sets the titles in plot axis */ + void SetTitles(); + + /** Enables/Sets default Titles to default */ + void EnableTitles(); + + /** Enables range of the axes */ + void EnableRange(); + + /** Sets the range of the x and y axes */ + void SetAxesRange(); + + /** Sets the range of the z axis */ + void SetZRange(); + + /** Enables the range of the z axis */ + void EnableZRange(); + + /** Return true if valid */ + bool CheckZRange(QString value); + + /** Set Plot to none, data graph, histogram*/ + void SetPlot(); + + /** Change pages in plot options box to the right*/ + void SetPlotOptionsRightPage(); + + /** Change pages in plot options box to the left*/ + void SetPlotOptionsLeftPage(); + + /** Plot binary plot */ + void SetBinary(); + + /** Set histogram options */ + void SetHistogramOptions(); + +signals: + void DisableZoomSignal(bool); + void SetZRangeSignal(double,double); + void ResetZMinZMaxSignal(bool,bool,double,double); + +}; + + + +#endif /* QTABPLOT_H_ */ diff --git a/slsDetectorGui/include/qTabSettings.h b/slsDetectorGui/include/qTabSettings.h new file mode 100644 index 0000000000..ddb0d4da66 --- /dev/null +++ b/slsDetectorGui/include/qTabSettings.h @@ -0,0 +1,116 @@ +/* + * qTabSettings.h + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#ifndef QTABSETTINGS_H_ +#define QTABSETTINGS_H_ + +#include "qDefs.h" + + +/** Form Header */ +#include "ui_form_tab_settings.h" +/** Project Class Headers */ +class multiSlsDetector; +/** Qt Include Headers */ +#include + +/** + *@short sets up the Settings parameters + */ +class qTabSettings:public QWidget, private Ui::TabSettingsObject{ + Q_OBJECT + +public: + /** \short The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + */ + qTabSettings(QWidget *parent,multiSlsDetector*& detector); + + /** Destructor + */ + ~qTabSettings(); + + /** To refresh and update widgets + */ + void Refresh(); + + /** To enable expert mode + * @param enable to enable if true + */ + void SetExpertMode(bool enable){expertMode = enable;}; + + + + +private: + /** The sls detector object */ + multiSlsDetector *myDet; + + /** detector type */ + slsDetectorDefs::detectorType detType; + + /** expert mode */ + bool expertMode; + + enum{Standard,Fast,HighGain,DynamicGain,LowGain,MediumGain,VeryHighGain,LowNoise, + DynamicHG0,FixGain1,FixGain2,ForceSwitchG1,ForceSwitchG2, VeryLowGain, + Undefined,Uninitialized,NumSettings}; + + /** To be able to index items on a combo box */ + QStandardItemModel* model; + QModelIndex index[NumSettings]; + QStandardItem* item[NumSettings]; + + /** Sets up the widget + */ + void SetupWidgetWindow(); + + /** Sets up the detector settings + */ + void SetupDetectorSettings(); + + /** Sets up all the slots and signals + */ + void Initialization(); + + /** Gets the dynamic range and sets it on the gui + * @param setvalue the value set by the gui when used as a check + */ + void GetDynamicRange(int setvalue = -1); + + + +private slots: +/** Set settings according to selection + * @param index index of selection + */ +void setSettings(int index); + +/** Set number of modules if possible + * @param index number of modules + */ +void SetNumberOfModules(int index); + +/** Set dynamic range if possible + * @param index selection + */ +void SetDynamicRange(int index); + +/** Set threshold energy + */ +void SetEnergy(); + + +signals: +/**Update Trimbits after Set Settings */ +void UpdateTrimbitSignal(int); +}; + + + +#endif /* QTABSETTINGS_H_ */ diff --git a/slsDetectorGui/slsDetectorGui.pro b/slsDetectorGui/slsDetectorGui.pro new file mode 100644 index 0000000000..641716a66f --- /dev/null +++ b/slsDetectorGui/slsDetectorGui.pro @@ -0,0 +1,146 @@ +#When using yum for qt, comment out all lines with $(QTDIR) or $(QWTDIR), but export QWTDIR = /usr/include/qwt/ +#and leave "$(QWTDIR) \"uncommented in the INCLUDEPATH + +#When using epics, uncomment epics defines, libs and a line in INCLUDEPATH + + +QT_INSTALL_PREFIX = $(QTDIR) +QMAKE_UIC = $(QTDIR)/bin/uic +QMAKE_MOC = $(QTDIR)/bin/moc +QMAKE_RCC = $(QTDIR)/bin/rcc +QMAKE_INCDIR_QT = $(QTDIR)/include/ +QMAKE_LIBS_QT = -L$(QTDIR)/lib +QMAKE_LIBS = -L$(QTDIR)/lib + + + + +#epics +#DEFINES += EPICS VERBOSE DACS_INT PRINT_LOG #VERYVERBOSE +#LIBS = -L$(QWTDIR)/lib -lqwt -L$(QWT3D)/lib -Wl,-R$(QWTDIR)/lib -L /usr/local/epics/base/lib/$(EPICS_HOST_ARCH)/ -Wl,-R/usr/local/epics/base/lib/$(EPICS_HOST_ARCH) -lca -lCom + +#default +DEFINES += VERBOSE DACS_INT PRINT_LOG #VERYVERBOSE CHECKINFERROR +LIBS = -L$(QWTDIR)/lib -lqwt -L$(QWT3D)/lib + +CXXFLAGS += -g + + +QMAKE_CXXFLAGS_WARN_ON = -w +QMAKE_CFLAGS_WARN_ON = -w + + +DESTDIR ?= bin +MOC_DIR = mocs +OBJECTS_DIR = objs +UI_HEADERS_DIR = forms/include +SLSDETLIB ?= ../slsDetectorSoftware +RESOURCES += icons.qrc +CONFIG += debug no_include_pwd + + + +target.path += $(DESTDIR) +documentation.path = /$(DOCPATH) +documentation.files = docs/* +INSTALLS += target +INSTALLS += documentation +QMAKE_CLEAN += docs/*/* + + + + +DEPENDPATH += \ + slsDetectorPlotting/include\ + include\ + forms/include + + +INCLUDEPATH = \ + $(QWTDIR)/include\ + $(QWTDIR) \ + $(QWTDIR)/src\ + $(QWT3D)/include\ + slsDetectorPlotting/include\ + include\ + forms/include\ + /usr/include/qwt\ #these are not included for standard installations, also bin path should include qt4 bin, not qt3 bin + /usr/include/qt4\ + /usr/include/Qt\ + /usr/include/QtCore\ + /usr/include/QtGui\ + $(INCLUDES) +#epics +# $(INCLUDES) /usr/local/epics/base/include/ -I /usr/local/epics/base/include/os/Linux/ + + + + + + +SOURCES = \ + slsDetectorPlotting/src/SlsQt1DPlot.cxx\ + slsDetectorPlotting/src/SlsQt1DZoomer.cxx\ + slsDetectorPlotting/src/SlsQt2DHist.cxx\ + slsDetectorPlotting/src/SlsQt2DPlot.cxx\ + slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx\ + slsDetectorPlotting/src/SlsQtNumberEntry.cxx\ + src/qDetectorMain.cpp\ + src/qDrawPlot.cpp\ + src/qCloneWidget.cpp\ + src/qTabMeasurement.cpp\ + src/qTabDataOutput.cpp\ + src/qTabPlot.cpp\ + src/qTabActions.cpp\ + src/qActionsWidget.cpp\ + src/qScanWidget.cpp\ + src/qTabAdvanced.cpp\ + src/qTabSettings.cpp\ + src/qTabDebugging.cpp\ + src/qTabDeveloper.cpp\ + src/qTabMessages.cpp\ + src/qServer.cpp + +HEADERS = \ + slsDetectorPlotting/include/SlsQt1DPlot.h\ + slsDetectorPlotting/include/SlsQt1DZoomer.h\ + slsDetectorPlotting/include/SlsQt2DHist.h\ + slsDetectorPlotting/include/SlsQt2DPlot.h\ + slsDetectorPlotting/include/SlsQt2DPlotLayout.h\ + slsDetectorPlotting/include/SlsQt2DZoomer.h\ + slsDetectorPlotting/include/SlsQtValidators.h\ + slsDetectorPlotting/include/SlsQtNumberEntry.h\ + include/qDefs.h\ + include/qDebugStream.h\ + include/qDetectorMain.h\ + include/qDrawPlot.h\ + include/qCloneWidget.h\ + include/qTabMeasurement.h\ + include/qTabDataOutput.h\ + include/qTabPlot.h\ + include/qTabActions.h\ + include/qActionsWidget.h\ + include/qScanWidget.h\ + include/qTabAdvanced.h\ + include/qTabSettings.h\ + include/qTabDebugging.h\ + include/qTabDeveloper.h\ + include/qTabMessages.h\ + include/gitInfoGui.h\ + ../slsDetectorSoftware/commonFiles/sls_detector_defs.h\ + include/qServer.h + + +FORMS = \ + forms/form_detectormain.ui\ + forms/form_tab_measurement.ui\ + forms/form_tab_dataoutput.ui\ + forms/form_tab_plot.ui\ +# forms/form_tab_actions.ui\ + forms/form_tab_advanced.ui\ + forms/form_tab_settings.ui\ + forms/form_tab_debugging.ui\ +# forms/form_tab_developer.ui\ +# forms/form_tab_messages.ui + forms/form_action.ui\ + forms/form_scan.ui diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h new file mode 100644 index 0000000000..554a17fab9 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h @@ -0,0 +1,173 @@ + +/** + * @author Ian Johnson + * @version 1.0 + * Modifications: + * 19.06.2012: {Some functions have been added by Dhanya to enable zooming in and out + * without using mouse control: + * DisableZoom, + * SetXMinMax,SetYMinMax, + * GetXMinimum,GetXMaximum,GetYMinimum,GetYMaximum} + * */ + +#ifndef SLSQT1DPLOT_H +#define SLSQT1DPLOT_H + +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#include "ansi.h" + + +#include +#include +#include +#include +#include "SlsQt1DZoomer.h" +#include +using namespace std; + +class QPen; +class SlsQt1DPlot; + +class SlsQtH1D:public QwtPlotCurve{ + + public: + SlsQtH1D(QString title, int n, double xmin, double xmax, double* data=0); + SlsQtH1D(QString title, int n, double* data_x, double* data_y); + ~SlsQtH1D(); + + void Attach(SlsQt1DPlot* p); + void Detach(SlsQt1DPlot* p); + + int SetLineColor(int c=-1); + int SetLineWidth(int w=1); + void SetLineStyle(int s=0); + + void SetData(int n, double xmin, double xmax, double* d=0); + void SetData(int n, double* dx, double* dy); + + double* GetX() {return x;} + double* GetY() {return y;} + int GetNBinsX() {return ndata;} + + double FillBin(int bx, double v=1); + double Fill(double x, double v=1); + double SetBinContent(int bx,double v); + double SetContent(double x,double v); + int FindBinIndex(double px); + + double GetXMin() {return x[0];} + double GetFirstXgtZero() {return firstXgt0;} + double GetXMax() {return x[ndata-1];} + double GetYMin() {return ymin;} + double GetFirstYgtZero() {return firstYgt0;} + double GetYMax() {return ymax;} + + SlsQtH1D* Add(double v); + + + + private: + int ndata; + int n_array; + double dx; + double *x,*y; + double ymin,ymax; + double firstXgt0,firstYgt0; + + void Initailize(); + int SetUpArrays(int n); + int CheckIndex(int bx); + + QPen* pen_ptr; +}; + + +class SlsQtH1DList{ + public: + SlsQtH1DList(SlsQtH1D* hist=0); + ~SlsQtH1DList(); + + SlsQtH1D* Add(SlsQtH1D* h); + void Remove(SlsQtH1D* h); + void Print(); + + SlsQtH1D* Hist() {return the_hist;} //if no hist returns 0 + SlsQtH1DList* Next() {return the_next;} + + +private: + SlsQtH1DList* the_next; + SlsQtH1D* the_hist; +}; + + +class SlsQt1DPlot:public QwtPlot{ + Q_OBJECT + + public: + SlsQt1DPlot(QWidget* = NULL); + ~SlsQt1DPlot(); + + void SetTitle(const char *t); + void SetXTitle(const char* title); + void SetYTitle(const char* title); + + void InsertHLine(double y); + void RemoveHLine(); + void InsertVLine(double v); + void RemoveVLine(); + + + /** This group of functions have been added by Dhanya on 19.06.2012 to be able to + use zooming functionality without mouse control*/ + void DisableZoom(bool disableZoom); + void SetXMinMax(double min,double max){setAxisScale(QwtPlot::xBottom,min,max);}; + void SetYMinMax(double min,double max){setAxisScale(QwtPlot::yLeft,min,max);}; + double GetXMinimum(){return hist_list->Hist()->GetXMin();}; + double GetXMaximum(){return hist_list->Hist()->GetXMax();}; + double GetYMinimum(){return hist_list->Hist()->GetYMin();}; + double GetYMaximum(){return hist_list->Hist()->GetYMax();}; + /**---*/ + + + void SetZoom(double xmin,double ymin,double x_width,double y_width); + void SetZoomBase(double xmin,double ymin,double x_width, double y_width){ zoomer->SetZoomBase(xmin,ymin,x_width,y_width);} + + void alignScales(); + private: + + SlsQtH1DList* hist_list; + SlsQt1DZoomer* zoomer; + QwtPlotPanner* panner; + + QwtPlotMarker *hline; + QwtPlotMarker *vline; + + void SetupZoom(); + void UnknownStuff(); + //void alignScales(); + + void CalculateNResetZoomBase(); + void NewHistogramAttached(SlsQtH1D* h); + void HistogramDetached(SlsQtH1D* h); + + void SetLog(int axisId, bool yes); + + friend void SlsQtH1D::Attach(SlsQt1DPlot* p); + friend void SlsQtH1D::Detach(SlsQt1DPlot* p); + + + public slots: + void UnZoom(); + void Update(); + + void SetLogX(bool yes=1); + void SetLogY(bool yes=1); + + protected: + +}; + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h new file mode 100644 index 0000000000..3bcb35ee77 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h @@ -0,0 +1,81 @@ + +/** + * @author Ian Johnson + * @version 1.0 + */ + +#ifndef SLSQT1DZOOMER_H +#define SLSQT1DZOOMER_H + +#ifndef IAN +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#endif + + +#include +#include +#include + +class SlsQtH1D; + +class SlsQt1DZoomer:public QwtPlotZoomer{ + private: + double x0,x1,y0,y1; + double firstXgt0,firstYgt0; + bool xIsLog,yIsLog; + + public: +#if QWT_VERSION < 0x060100 + SlsQt1DZoomer(QwtPlotCanvas *canvas):QwtPlotZoomer(canvas){ +#else + SlsQt1DZoomer(QWidget *canvas):QwtPlotZoomer(canvas){ +#endif + setTrackerMode(AlwaysOn); + xIsLog=yIsLog=0; + } + + double x() {return x0;} + double x_firstGreaterThan0() {return firstXgt0;} + double w() {return x1-x0;} + + double y() {return y0;} + double y_firstGreaterThan0() {return firstYgt0;} + double h() {return y1-y0;} + + void SetZoomBase(double xmin,double ymin,double x_width, double y_width); + void SetZoomBase(SlsQtH1D* h); + void ExtendZoomBase(SlsQtH1D* h); + void ResetZoomBase(); + + bool IsLogX(){ return xIsLog;} + bool IsLogY(){ return yIsLog;} + bool SetLogX(bool yes) { return xIsLog=yes;} + bool SetLogY(bool yes) { return yIsLog=yes;} + + +#if QWT_VERSION<0x060000 + virtual QwtText trackerText(const QwtDoublePoint &pos) const{ +#else + virtual QwtText trackerText(const QPointF &pos) const{ +#endif + QColor bg(Qt::white); + +#if QT_VERSION >= 0x040300 + bg.setAlpha(200); +#endif + +#if QWT_VERSION<0x060000 + QwtText text = QwtPlotZoomer::trackerText(pos); +#else + QPoint p=pos.toPoint(); + QwtText text = QwtPlotZoomer::trackerText(p); +#endif + text.setBackgroundBrush( QBrush( bg )); + return text; + } + +}; + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h new file mode 100644 index 0000000000..a71a326761 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h @@ -0,0 +1,145 @@ + +/** + * @author Ian Johnson + * @version 1.0 + */ + + +#ifndef SLSQT2DHIST_H +#define SLSQT2DHIST_H + + +#ifndef IAN +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#endif + + + +#if QT_VERSION >= 0x040000 +#include +#endif +#include +#include +#include +#include + + +class SlsQt2DHist: public QwtRasterData{ + + private: + + double x_min,x_max,y_min,y_max; + double x_width,y_width; + + int nx,ny,nb; + double *data; + double z_min,z_mean,z_max; + bool z_mean_has_been_calculated; + + int nx_array,ny_array; + + bool interp; + + static double value_between_points(double p1,double v1,double p2,double v2,double p){ //linear extrap + return (v2-v1)/(p2-p1)*(p-p1)+v1; + } + + public: + SlsQt2DHist(int nbinsx=10, double xmin=0, double xmax=10, int nbinsy=10, double ymin=0, double ymax=10, double* d=0,double zmin=0,double zmax=-1); + virtual ~SlsQt2DHist(); + + double GetXMin() {return x_min;} + double GetXMax() {return x_max;} + double GetXBinWidth() {return x_width;} + double GetYMin() {return y_min;} + double GetYMax() {return y_max;} + double GetYBinWidth() {return y_width;} + double GetMinimum() {return z_min;} + double GetMaximum() {return z_max;} + double GetMean(); + + int GetNBinsX(){return nx;} + int GetNBinsY(){return ny;} + double GetBinValue(int bx,int by); + int GetBinIndex(int bx,int by); + double* GetDataPtr(){return data;} + + void Interpolate(bool on=1) {interp=on;} + void SetBinValue(int bx,int by,double v); + void SetData(int nbinsx, double xmin, double xmax, int nbinsy,double ymin, double ymax,double *d,double zmin=0, double zmax=-1); + + double SetMinimumToFirstGreaterThanZero(); + void SetMinimum(double zmin) {z_min=zmin;} + void SetMaximum(double zmax) {z_max=zmax;} + void SetMinMax(double zmin=0,double zmax=-1); + + int FindBinIndex(double x, double y); + + + + virtual QwtRasterData *copy() const{ + //this function does not create a new SlsQt2DHistData instance, + //just passes a pointer so that data is common to both the copy and the original instance + return (QwtRasterData*) this; + } + +#if QWT_VERSION<0x060000 + virtual QwtDoubleInterval range() const{ return QwtDoubleInterval(z_min,z_max);} +#else + virtual QwtInterval range() const{ return QwtInterval(z_min,z_max);} + virtual QwtInterval interval(Qt::Axis axis) const { + switch (axis){ + case Qt::ZAxis: + return QwtInterval(z_min,z_max); + case Qt::XAxis: + return QwtInterval(x_min,x_max); + case Qt::YAxis: + return QwtInterval(y_min,y_max); + default: + return QwtInterval(z_min,z_max); + }; + }; +#endif + + + + virtual double value(double x, double y) const{ + //if(!interp){ //default is box like plot + int index = int((x-x_min)/x_width) + int((y-y_min)/y_width)*nx; + if(index<0||index>nb) index = nb; + if(!interp) return data[index]; + //} + + + int x_int = int((x-x_min)/x_width-0.5); + if(x_int<0) x_int = 0; else if(x_int>nx-2) x_int = nx-2; + int y_int = int((y-y_min)/y_width-0.5); + if(y_int<0) y_int = 0; else if(y_int>ny-2) y_int = ny-2; + + int b00 = x_int*ny + y_int; + int b01 = x_int*ny + y_int+1; + int b10 = (x_int+1)*ny + y_int; + int b11 = (x_int+1)*ny + y_int+1; + + //vertical extrap + double y0 = y_min+(y_int+0.5)*y_width; + double y1 = y_min+(y_int+1.5)*y_width; + double left_v = value_between_points(y0,data[b00],y1,data[b01],y); + double right_v = value_between_points(y0,data[b10],y1,data[b11],y); + //horazontal extrap + + + + return 0.5; + + + return value_between_points(x_min+(x_int+0.5)*x_width,left_v, + x_min+(x_int+1.5)*x_width,right_v,x); + } + +}; + + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h new file mode 100644 index 0000000000..967eb68fe4 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h @@ -0,0 +1,118 @@ + +/** + * @author Ian Johnson + * @version 1.0 + * Modifications: + * 19.06.2012: {Some functions have been added by Dhanya to enable zooming in and out + * without using mouse control: + * DisableZoom, + * SetXMinMax,SetYMinMax, + * GetXMinimum,GetXMaximum,GetYMinimum,GetYMaximum} + */ + + +#ifndef SLSQT2DPLOT_H +#define SLSQT2DPLOT_H + +#ifndef IAN +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#endif + + + +#include +#include +#include + +#include "SlsQt2DZoomer.h" +#include "SlsQt2DHist.h" + + +class QwtPlotPanner; +class QwtScaleWidget; +class QwtLinearColorMap; + + +class SlsQt2DPlot: public QwtPlot{ + Q_OBJECT + +private: + QwtPlotSpectrogram *d_spectrogram; + SlsQt2DHist* hist; + SlsQt2DZoomer* zoomer; + QwtPlotPanner* panner; + QwtScaleWidget *rightAxis; + + QwtLinearColorMap* colorMapLinearScale; + QwtLinearColorMap* colorMapLogScale; +#if QWT_VERSION<0x060000 + QwtValueList* contourLevelsLinear; + QwtValueList* contourLevelsLog; +#else + QList contourLevelsLinear; + QList contourLevelsLog; +#endif + + void SetupZoom(); + void SetupColorMap(); + + QwtLinearColorMap* myColourMap(QVector colourStops); + QwtLinearColorMap* myColourMap(int log=0); + + int isLog; + + +public: + SlsQt2DPlot(QWidget * = NULL); + + // SlsQt2DHist *GetHistogram(){ return hist; } + void UnZoom(); + void SetZoom(double xmin,double ymin,double x_width,double y_width); + + + /** This group of functions have been added by Dhanya on 19.06.2012 to be able to + use zooming functionality without mouse control*/ + void DisableZoom(bool disableZoom); + void SetXMinMax(double min,double max){setAxisScale(QwtPlot::xBottom,min,max);}; + void SetYMinMax(double min,double max){setAxisScale(QwtPlot::yLeft,min,max);}; + double GetXMinimum(){return hist->GetXMin();}; + double GetXMaximum(){return hist->GetXMax();}; + double GetYMinimum(){return hist->GetYMin();}; + double GetYMaximum(){return hist->GetYMax();}; + /**---*/ + + + double GetZMinimum(){ return hist->GetMinimum();} + double GetZMaximum(){ return hist->GetMaximum();} + void SetZMinMax(double zmin=0,double zmax=-1); + void SetZMinimumToFirstGreaterThanZero(){hist->SetMinimumToFirstGreaterThanZero();} + double GetZMean() { return hist->GetMean();} + + void SetData(int nbinsx, double xmin, double xmax, int nbinsy,double ymin, double ymax,double *d,double zmin=0, double zmax=-1){ + hist->SetData(nbinsx,xmin,xmax,nbinsy,ymin,ymax,d,zmin,zmax); + } + + + + double* GetDataPtr() {return hist->GetDataPtr();} + int GetBinIndex(int bx,int by) {return hist->GetBinIndex(bx,by);} + int FindBinIndex(double x,double y) {return hist->FindBinIndex(x,y);} + void SetBinValue(int bx,int by,double v) { hist->SetBinValue(bx,by,v);} + double GetBinValue(int bx,int by) {return hist->GetBinValue(bx,by);} + + + void FillTestPlot(int i=0); + void Update(); + +public slots: + void LogZ(bool on=1); + void InterpolatedPlot(bool on); + void showContour(bool on); + void showSpectrogram(bool on); + // void printPlot(); + +}; + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlotLayout.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlotLayout.h new file mode 100644 index 0000000000..2d2315f778 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlotLayout.h @@ -0,0 +1,82 @@ +/** + * @author Ian Johnson + * @version 1.0 + * @comments + * 19.06.2012 All modifications with the Ian flag has been made since + * z_range_ne and the buttons are defined in another class. + * Logz button and z_range_ne have wrappers to connect them + * 05.05.2013 Added ResetZMinZMax + */ + + +#ifndef SLSQT2DPLOTLAYOUT_H +#define SLSQT2DPLOTLAYOUT_H + +#ifndef IAN +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#endif + + +#include +#include + +#include "SlsQtNumberEntry.h" +#include "SlsQt2DPlot.h" + +class QGridLayout; +class QString; +class QToolButton; + + +class SlsQt2DPlotLayout: public QGroupBox{ + Q_OBJECT + +public: + + SlsQt2DPlotLayout(QWidget * = NULL); + ~SlsQt2DPlotLayout(); + + SlsQt2DPlot* GetPlot(){return the_plot;} + void SetXTitle(QString st); + void SetYTitle(QString st); + void SetZTitle(QString st); + void UpdateNKeepSetRangeIfSet(); + + +private: + QGridLayout* the_layout; + QToolButton* btnInterpolate; + QToolButton* btnContour; + QToolButton* btnLogz; + SlsQt2DPlot* the_plot; + SlsQtNumberEntry* z_range_ne; + +#ifndef IAN + bool zRangeChecked; +#endif + + void CreateTheButtons(); + void ConnectSignalsAndSlots(); + void Layout(); + +public slots: +void SetZScaleToLog(bool yes); +void ResetRange(); + +#ifndef IAN +void SetZRange(double,double); +void EnableZRange(bool enable); +void ResetZMinZMax(bool zmin, bool zmax, double min, double max); + +#endif + +signals: +void InterpolateSignal(bool); +void ContourSignal(bool); + +}; + +#endif + diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h new file mode 100644 index 0000000000..5fed37f1a2 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h @@ -0,0 +1,78 @@ + +/** + * @author Ian Johnson + * @version 1.0 + * Dhanya-05.12.2012- included an additional header + */ + + +#ifndef SLSQT2DZOOMER_H +#define SLSQT2DZOOMER_H + +#ifndef IAN +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#endif + + +/**included by Dhanya on 05.12.2012 to avoid compile time errors with the latest gcc*/ +#include +/**end of Change by Dhanya*/ + +#include +#include + +#include "SlsQt2DHist.h" + +class SlsQt2DZoomer:public QwtPlotZoomer{ + private: + SlsQt2DHist* hist; + + public: +#if QWT_VERSION < 0x060100 + SlsQt2DZoomer(QwtPlotCanvas *canvas):QwtPlotZoomer(canvas){ +#else + SlsQt2DZoomer(QWidget *canvas):QwtPlotZoomer(canvas){ +#endif + setTrackerMode(AlwaysOn); + } + + void SetHist(SlsQt2DHist* h){ + hist=h; + } + + +#if QWT_VERSION<0x060000 + virtual QwtText trackerText(const QwtDoublePoint &pos) const{ +#else + virtual QwtText trackerTextF(const QPointF &pos) const{ +#endif + QColor bg(Qt::white); +#if QT_VERSION >= 0x040300 + bg.setAlpha(200); +#endif + + + //QwtText text = QwtPlotZoomer::trackerText(pos); + + static QwtText text; + if(hist){ + static char t[200]; + sprintf(t,"%3.2f, %3.2f, %3.2f",pos.x(),pos.y(),hist->value(pos.x(),pos.y())); + text.setText(t); + }else { +#if QWT_VERSION<0x060000 + QwtText text = QwtPlotZoomer::trackerText(pos); +#else + QPoint p=pos.toPoint(); + QwtText text = QwtPlotZoomer::trackerText(p); +#endif + + } + text.setBackgroundBrush( QBrush( bg )); + return text; + } +}; + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtNumberEntry.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtNumberEntry.h new file mode 100644 index 0000000000..dbeb0a31e5 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtNumberEntry.h @@ -0,0 +1,147 @@ + +/** + * @author Ian Johnson + * @version 1.0 + */ + +#ifndef SLSQTNUMBERENTRY_H +#define SLSQTNUMBERENTRY_H + +#ifndef IAN +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#endif + + +#include +#include + +class QGridLayout; + +class QLabel; +class QLineEdit; +class QIntValidator; +class QDoubleValidator; +class QCheckBox; +class QComboBox; +class QSpinBox; + +#include "SlsQtValidators.h" + +class SlsQtNumberEntry:public QWidget{ + Q_OBJECT + + public: + //type=0->units only, type=1->int,type=2->double, type=3->spinbox + //adding middle text will automatically add a second number field + SlsQtNumberEntry(QWidget *parent,int with_checkbox=0, char *start_string=0, int num_type=0, char *middle_string=0, int num2_type=0, int n_units=0, char** units=0, double* unit_factors=0, char* end_string=0); + //without unit box + SlsQtNumberEntry(QWidget *parent,int with_checkbox, char *start_strin, int num_type, char *middle_string, int num2_type, char* end_string); + + + ~SlsQtNumberEntry(); + + void Enable(bool en_flag=1); + void Disable(); + void EnableNumberField(int which_number_field,bool en_flag=1); //which_number_field is 0 or 1 + void DisableNumberField(int which_number_field); + + void AddCheckBox(); + void SetFrontText(char* s); + void SetMiddleText(char* s); + void SetBackText(char* s); + void SetupNumberField(int type,int which_number_field=0); + void SetUnits(int n_units,char** units,double* unit_factors); + + void SetMinimumNumberWidth(int nchar_width,int which_number_field=0); + void SetNDecimalsOfDoubleValidators(int ndecimals); + void SetNDecimalsOfDoubleValidator(int ndecimals,int which_number_field=0); + void SetMinimumUnitWidth(int nchar_width); + + bool Enabled(); + bool CheckBoxState(); + bool IsValueOk(int which_number_field=0); + + const char* GetFrontText(); + const char* GetMiddleText(); + const char* GetBackText(); + + int GetNumberInt(int which_number_field=0,bool* ok=0); + double GetNumber(int which_number_field=0,bool *ok=0); + + int GetValueInt(int which_number_field=0,bool* ok=0); + double GetValue(int which_number_field=0,bool *ok=0); + + int GetComboBoxIndex(); + double GetComboBoxValue(); + + private: + void SetupNumberEntry(int with_checkbox=0, char *start_string=0, int num_type=0, char *middle_string=0, int num2_type=0, int n_units=0, char** units=0, double* unit_factors=0, char* end_string=0); + + QGridLayout* layout; //default layout + + QCheckBox* check_box; + QLabel* front_text; + QLabel* middle_text; + QLineEdit* num_field[2]; + QSpinBox* spin_box[2]; + bool num_field_enabled[2]; + + SlsQtIntValidator* validator_int[2]; + SlsQtDoubleValidator* validator_double[2]; + QComboBox* unit_cbb; + double* factors; + QLabel* back_text; + + void SetText(char* s, QLabel** pp); + void SetLayout(); + + + public slots: + void FirstValueEntered(); + void SecondValueEntered(); + void UnitSelected(); + + void SetRange(int min, int max, int which_number_field=0); + void SetRange(double min, double max, int which_number_field=0); + void SetFirstRange(int min, int max) {SetRange(min,max,0);} + void SetSecondRange(int min, int max) {SetRange(min,max,1);} + + double SetValue(double v, int which_number_field=0); + void SetFirstValue(int v) {SetValue(v,0);} + void SetSecondValue(int v) {SetValue(v,1);} + void SetFirstValue(double v) {SetValue(v,0);} + void SetSecondValue(double v) {SetValue(v,1);} + + // double SetNumber(int v, int which_number_field=0); + double SetNumber(double v, int which_number_field=0); + void SetFirstNumber(int v) {SetNumber(v,0);} + void SetSecondNumber(int v) {SetNumber(v,1);} + void SetFirstNumber(double v) {SetNumber(v,0);} + void SetSecondNumber(double v) {SetNumber(v,1);} + + int SetComboBoxIndex(int index); + + void CheckBoxClicked(); + void PrintTheValue(); + + void RefreshFirstNumberEntry(); + void RefreshSecondNumberEntry(); + void RefreshNumberEntery(int number_field=0); + + signals: + void CheckBoxChanged(bool state); + void CheckBoxChanged(SlsQtNumberEntry* ptr); + void AValueChanged(SlsQtNumberEntry* ptr); + void FirstValueChanged(int value); + void FirstValueChanged(double value); + void FirstValueChanged(SlsQtNumberEntry* ptr); + void SecondValueChanged(int value); + void SecondValueChanged(double value); + void SecondValueChanged(SlsQtNumberEntry* ptr); + void UnitChanged(double); + void UnitChanged(SlsQtNumberEntry* ptr); +}; + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtValidators.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtValidators.h new file mode 100644 index 0000000000..bd2d70efd0 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtValidators.h @@ -0,0 +1,79 @@ + +/** + * @author Ian Johnson + * @version 1.0 + */ + +#ifndef SLSQTVALIDATORS_H +#define SLSQTVALIDATORS_H + +#ifndef IAN +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; +#endif + +#include +#include + +#include +#include + +using std::cout; +using std::endl; + +class SlsQtIntValidator:public QIntValidator{ + + public: + SlsQtIntValidator(QWidget *parent):QIntValidator(parent){} + + virtual void fixup (QString& text) const { + bool ok = 1; + int v = text.toInt(&ok); + + if(!ok){ + v = text.toDouble(&ok); + if(ok) text = QString::number(v); + else text = QString::number(0); + fixup(text); + } + + if(vtop()) text = QString::number(top()); + } + +}; + +class SlsQtDoubleValidator:public QDoubleValidator{ + + public: + SlsQtDoubleValidator(QWidget *parent):QDoubleValidator(parent){} + + virtual void fixup (QString& text) const { + + bool ok = 1; + double v = text.toDouble(&ok); + + if(!ok){ + text = QString::number(0); + fixup(text); + } + + int nd = this->decimals(); //ndigest behind zero + if(vtop()){ + v = floor(top()*pow(10,nd))/pow(10,nd); + text = QString::number(v,'g'); + }else{ + v = round(v*pow(10,nd))/pow(10,nd); + text = QString::number(v,'g'); + } + } + } + +}; + +#endif diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cxx b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cxx new file mode 100644 index 0000000000..1382e0e50c --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cxx @@ -0,0 +1,517 @@ + +/** + * @author Ian Johnson + * @version 1.0 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "SlsQt1DPlot.h" + +#if QWT_VERSION >= 0x060100 +#define QwtLog10ScaleEngine QwtLogScaleEngine +#endif + +using namespace std; + +SlsQtH1D::SlsQtH1D(QString title,int n, double min, double max, double* data):QwtPlotCurve(title){ + Initailize(); + SetData(n,min,max,data); +} + +SlsQtH1D::SlsQtH1D(QString title,int n, double* data_x, double* data_y):QwtPlotCurve(title){ + Initailize(); + SetData(n,data_x,data_y); +} + +void SlsQtH1D::Initailize(){ + ndata=n_array=0; + x=y=0; + pen_ptr = new QPen(); + SetLineColor(); +} + +SlsQtH1D::~SlsQtH1D(){delete x;delete y;delete pen_ptr;} + +void SlsQtH1D::Attach(SlsQt1DPlot* p){ + attach((QwtPlot*) p); + p->NewHistogramAttached(this); +} + +void SlsQtH1D::Detach(SlsQt1DPlot* p){ + detach(); + p->HistogramDetached(this); +} + + +int SlsQtH1D::SetLineColor(int c){ + static int last_color = 1; + if(c<0) c=(last_color+1)%3; + + switch(c){ + case 0: pen_ptr->setColor(Qt::black); break; + case 1: pen_ptr->setColor(Qt::red); break; + case 2: pen_ptr->setColor(Qt::blue); break; + case 3: pen_ptr->setColor(Qt::green); break; + case 4: pen_ptr->setColor(Qt::magenta); break; + case 5: pen_ptr->setColor(Qt::cyan); break; + case 6: pen_ptr->setColor(Qt::darkYellow); break; + case 7: pen_ptr->setColor(Qt::gray); break; + case 8: pen_ptr->setColor(Qt::darkBlue); break; + case 9: pen_ptr->setColor(Qt::darkGreen); break; + case 10: pen_ptr->setColor(Qt::darkMagenta); break; + } +/* if(c==0) pen_ptr->setColor(Qt::black); + else if(c==1) pen_ptr->setColor(Qt::red); + else pen_ptr->setColor(Qt::blue);*/ + + setPen(*pen_ptr); + + return last_color=c; +} + +int SlsQtH1D::SetLineWidth(int w){ + pen_ptr->setWidth(w); + setPen(*pen_ptr); + return w; +} + +void SlsQtH1D::SetLineStyle(int s){ + if(s==1) pen_ptr->setStyle(Qt::DashLine); + else if(s==2) pen_ptr->setStyle(Qt::DotLine); + else if(s==3) pen_ptr->setStyle(Qt::DashDotLine); + else if(s==4) pen_ptr->setStyle(Qt::DashDotDotLine); + else if(s==5) pen_ptr->setStyle(Qt::CustomDashLine); + else pen_ptr->setStyle(Qt::SolidLine); + setPen(*pen_ptr); +} + + +void SlsQtH1D::SetData(int n, double xmin, double xmax, double *data){ + n = SetUpArrays(n); + + ndata=n; + if(xmin>xmax){ + double t=xmin; + xmin=xmax; + xmax=t; + } + + dx = (xmax-xmin)/n; + ymin=ymax= data ? data[0]:0; + firstXgt0=-1; + firstYgt0=-1; + + for(int i=0;iy[i]) ymin = y[i]; + if(data&&ymax0&&(firstXgt0<0||firstXgt0>x[i])) firstXgt0=x[i]; + if(y[i]>0&&(firstYgt0<0||firstYgt0>y[i])) firstYgt0=y[i]; + } + + // cout<0&&data_x[0]>data_x[n-1]) ? 1:0; + n = SetUpArrays(n); + + ndata=n; + dx=-1; //signifies not regular intervals + + ymin=ymax= data_y ? data_y[0]:0; + + firstXgt0=-1; + firstYgt0=-1; + + for(int i=0;iy[b]) ymin = y[b]; + if(data_y&&ymax0&&(firstXgt0<0||firstXgt0>x[b])) firstXgt0=x[b]; + if(y[b]>0&&(firstYgt0<0||firstYgt0>y[b])) firstYgt0=y[b]; + } + +#if QWT_VERSION<0x060000 + setRawData(x,y,ndata); +#else + setRawSamples(x,y,ndata); +#endif +} + +int SlsQtH1D::SetUpArrays(int n){ + n = n<1 ? 1 : n; //overflow bin + + if(n+1>n_array){ + n_array = n+1; + if(x) delete x; + if(y) delete y; + x = new double [n_array]; + y = new double [n_array]; + } + + return n; +} + +double SlsQtH1D::FillBin(int bx, double v) { + bx = CheckIndex(bx); + return SetBinContent(bx,y[bx]+v); +} +double SlsQtH1D::Fill(double x, double v){return FillBin(FindBinIndex(x),v);} + +double SlsQtH1D::SetBinContent(int bx,double v){ + bx = CheckIndex(bx); + y[bx]=v; + if(bx0&&(firstYgt0<=0||y[bx]ymax) ymax = y[bx]; + } + return y[bx]; +} + +double SlsQtH1D::SetContent(double x,double v) {return SetBinContent(FindBinIndex(x),v); } + +int SlsQtH1D::FindBinIndex(double px){ + if(dx>0) CheckIndex(int((px-x[0])/dx)); + + //find closest bin + int b=0; for(;bpx) break; + + if(b==0) return 0; + else if(fabs(px-x[b-1])ndata) ? ndata : bx;}//ndata is the overflow bin + +SlsQtH1D* SlsQtH1D::Add(double v){ for(int bx=0;bxthe_hist) return hist; //already added + if(!hl->the_next) break; + hl=hl->the_next; + } + if(hl->the_hist) hl->the_next = new SlsQtH1DList(hist); + else hl->the_hist = hist; + + // Print(); + + return hist; +} + +void SlsQtH1DList::Print(){ + // cout<<"Printing List"<the_hist<<" "<the_next<the_next; + if(i>10) break; + } +} + +void SlsQtH1DList::Remove(SlsQtH1D* hist){ + // cout<<"Removing: "<the_hist!=hist) hl = hl->the_next; + else{ //match + if(!hl->the_next) hl->the_hist=0; // first the_hist is zero when there's no next + else{ + SlsQtH1DList* t = hl->the_next; + hl->the_hist = t->the_hist; + hl->the_next = t->the_next; + t->the_next = 0; + delete t; + } + } + } + // Print(); +} + + + +//1d plot stuff +SlsQt1DPlot::SlsQt1DPlot(QWidget *parent):QwtPlot(parent){ + // n_histograms_attached=0; + hline=vline=0; + hist_list = new SlsQtH1DList(); + + UnknownStuff(); + alignScales(); + SetupZoom(); + + // Assign a title +#ifndef IAN + insertLegend(new QwtLegend(), QwtPlot::BottomLegend); +#else + insertLegend(new QwtLegend(), QwtPlot::RightLegend); +#endif + + axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); +} + +SlsQt1DPlot::~SlsQt1DPlot(){ + delete hist_list; + + if(hline) delete hline; + if(vline) delete vline; +} + +void SlsQt1DPlot::CalculateNResetZoomBase(){ + if(hist_list->Hist()) zoomer->SetZoomBase(hist_list->Hist()); + SlsQtH1DList* hl = hist_list->Next(); + while(hl){ + if(hl->Hist()) zoomer->ExtendZoomBase(hl->Hist()); + hl=hl->Next(); + } +} + +void SlsQt1DPlot::NewHistogramAttached(SlsQtH1D* h){ + hist_list->Add(h); + CalculateNResetZoomBase(); + //commented out by dhanya to take off zooming every hist in 1d plots + //if(!hist_list->Next()) UnZoom(); + Update(); +} + +void SlsQt1DPlot::HistogramDetached(SlsQtH1D* h){ + hist_list->Remove(h); + CalculateNResetZoomBase(); + Update(); +} + +void SlsQt1DPlot::Update(){ + replot(); +} + +void SlsQt1DPlot::SetTitle(const char* title){ + setTitle(title); +} + +void SlsQt1DPlot::SetXTitle(const char* title){ + QwtText t(title); + t.setFont(QFont("Sans Serif",11,QFont::Normal)); + setAxisTitle(QwtPlot::xBottom,t); +} +void SlsQt1DPlot::SetYTitle(const char* title){ + QwtText t(title); + t.setFont(QFont("Sans Serif",11,QFont::Normal)); + setAxisTitle(QwtPlot::yLeft,t); +} + +void SlsQt1DPlot::SetLogX(bool yes){ SetLog(QwtPlot::xBottom,yes);} +void SlsQt1DPlot::SetLogY(bool yes){ SetLog(QwtPlot::yLeft,yes);} +void SlsQt1DPlot::SetLog(int axisId, bool yes){ + if(axisId==QwtPlot::xBottom) zoomer->SetLogX(yes); + if(axisId==QwtPlot::yLeft) zoomer->SetLogY(yes); + + zoomer->ResetZoomBase(); //needs to be done before setting Engine + + //the old ones are deleted by in the setAxisScaleFunction() function see: 128 of file qwt_plot_axis.cpp + if(yes) setAxisScaleEngine(axisId,new QwtLog10ScaleEngine()); + else setAxisScaleEngine(axisId,new QwtLinearScaleEngine()); + + axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); + + Update(); +} + +void SlsQt1DPlot::UnZoom(){ + setAxisScale(QwtPlot::xBottom,zoomer->x(),zoomer->x()+zoomer->w()); + setAxisScale(QwtPlot::yLeft,zoomer->y(),zoomer->y()+zoomer->h()); + + zoomer->setZoomBase();//Call replot for the attached plot before initializing the zoomer with its scales. + Update(); +} + +void SlsQt1DPlot::SetZoom(double xmin,double ymin,double x_width,double y_width){ + setAxisScale(QwtPlot::xBottom,xmin,xmin+x_width); + setAxisScale(QwtPlot::yLeft ,ymin,ymin+y_width); + Update(); +} + +void SlsQt1DPlot::RemoveHLine(){ + if(hline) hline->detach(); + delete hline; + hline=0; +} + +void SlsQt1DPlot::InsertHLine(double y){ + if(!hline){ + hline = new QwtPlotMarker(); + hline->setLabelAlignment(Qt::AlignRight|Qt::AlignTop); + hline->setLineStyle(QwtPlotMarker::HLine); + hline->attach(this); + } + hline->setYValue(y); +} + +void SlsQt1DPlot::RemoveVLine(){ + if(vline) vline->detach(); + delete vline; + vline=0; +} + +void SlsQt1DPlot::InsertVLine(double x){ + if(!vline){ + vline = new QwtPlotMarker(); + vline->setLabelAlignment(Qt::AlignRight|Qt::AlignTop); + vline->setLineStyle(QwtPlotMarker::VLine); + vline->attach(this); + } + vline->setXValue(x); +} + + + + +void SlsQt1DPlot::SetupZoom(){ + // LeftButton for the zooming + // MidButton for the panning + // RightButton: zoom out by 1 + // Ctrl+RighButton: zoom out to full size + + zoomer = new SlsQt1DZoomer(canvas()); + +#if QT_VERSION < 0x040000 + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); +#else + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); +#endif + zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); + + panner = new QwtPlotPanner((QwtPlotCanvas*)canvas()); + panner->setAxisEnabled(QwtPlot::yRight, false); + panner->setMouseButton(Qt::MidButton); + + // Avoid jumping when labels with more/less digits + // appear/disappear when scrolling vertically + + const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); + QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); + sd->setMinimumExtent( fm.width("100.00") ); + + const QColor c(Qt::darkBlue); + zoomer->setRubberBandPen(c); + zoomer->setTrackerPen(c); +} + + +// Set a plain canvas frame and align the scales to it +void SlsQt1DPlot::alignScales(){ + // The code below shows how to align the scales to + // the canvas frame, but is also a good example demonstrating + // why the spreaded API needs polishing. + + ((QwtPlotCanvas*)canvas())->setFrameStyle(QFrame::Box | QFrame::Plain ); + ((QwtPlotCanvas*)canvas())->setLineWidth(1); + + for(int i = 0; i < QwtPlot::axisCnt; i++ ){ + QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(i); + if(scaleWidget) scaleWidget->setMargin(0); + QwtScaleDraw *scaleDraw = (QwtScaleDraw *)axisScaleDraw(i); + if(scaleDraw) scaleDraw->enableComponent(QwtAbstractScaleDraw::Backbone, false); + } +} + +void SlsQt1DPlot::UnknownStuff(){ +#if QWT_VERSION<0x060000 + // Disable polygon clipping + //not supported for version 6 + QwtPainter::setDeviceClipping(false); + canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, false); + canvas()->setPaintAttribute(QwtPlotCanvas::PaintPacked, false); +#else + // We don't need the cache here + ((QwtPlotCanvas*)canvas())->setPaintAttribute(QwtPlotCanvas::BackingStore, false); + +#endif + + + +#if QT_VERSION >= 0x040000 +#ifdef Q_WS_X11 + // Qt::WA_PaintOnScreen is only supported for X11, but leads + // to substantial bugs with Qt 4.2.x/Windows + canvas()->setAttribute(Qt::WA_PaintOnScreen, true); +#endif +#endif +} + + + +//Added by Dhanya on 19.06.2012 to disable zooming when any of the axes range has been set +void SlsQt1DPlot::DisableZoom(bool disableZoom){ +#ifdef VERBOSE + if(disableZoom) cout<<"Disabling zoom"<setMousePattern(QwtEventPattern::MouseSelect1,Qt::NoButton); +#if QT_VERSION < 0x040000 + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlButton); +#else + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlModifier); +#endif + zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::NoButton); + } + if(panner) panner->setMouseButton(Qt::NoButton); + }else { + if(zoomer){ + zoomer->setMousePattern(QwtEventPattern::MouseSelect1,Qt::LeftButton); +#if QT_VERSION < 0x040000 + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); +#else + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); +#endif + zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); + } + if(panner) panner->setMouseButton(Qt::MidButton); + } +} + + + + diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cxx b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cxx new file mode 100644 index 0000000000..31386094e2 --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cxx @@ -0,0 +1,109 @@ + +/** + * @author Ian Johnson + * @version 1.0 + */ + + +#include + +#include +#include + +#include "SlsQt1DPlot.h" +#include "SlsQt1DZoomer.h" + +using namespace std; + +void SlsQt1DZoomer::ResetZoomBase(){ + SetZoomBase(x0,y0,x1-x0,y1-y0); //for going between log and nonlog plots +} + +void SlsQt1DZoomer::SetZoomBase(double xmin,double ymin,double x_width, double y_width){ + if(xIsLog&&xmin<=0){ + double xmax = xmin+x_width; + xmin = firstXgt0*0.98; + if(xmax<=xmin) x_width=firstXgt0; + else x_width=xmax-xmin; + } + if(yIsLog&&ymin<=0){ + double ymax = ymin+y_width; + ymin = firstYgt0*0.98; + if(ymax<=ymin) y_width=firstYgt0; + else y_width=ymax-ymin; + } + + if(plot()){ + if(xIsLog){ + #if QWT_VERSION < 0x50200 + float xmin_curr = plot()->axisScaleDiv(QwtPlot::xBottom)->lBound(); + float xmax_curr = plot()->axisScaleDiv(QwtPlot::xBottom)->hBound(); + #elif QWT_VERSION < 0x060100 + float xmin_curr = plot()->axisScaleDiv(QwtPlot::xBottom)->lowerBound(); + float xmax_curr = plot()->axisScaleDiv(QwtPlot::xBottom)->upperBound(); + #else + float xmin_curr = plot()->axisScaleDiv(QwtPlot::xBottom).lowerBound(); + float xmax_curr = plot()->axisScaleDiv(QwtPlot::xBottom).upperBound(); + #endif + if(xmin_currxmin+x_width) xmax_curr=xmin+x_width; + plot()->setAxisScale(QwtPlot::xBottom,xmin_curr,xmax_curr); + } + if(yIsLog){ + #if QWT_VERSION < 0x50200 + float ymin_curr = plot()->axisScaleDiv(QwtPlot::yLeft)->lBound(); + float ymax_curr = plot()->axisScaleDiv(QwtPlot::yLeft)->hBound(); + #elif QWT_VERSION < 0x060100 + float ymin_curr = plot()->axisScaleDiv(QwtPlot::yLeft)->lowerBound(); + float ymax_curr = plot()->axisScaleDiv(QwtPlot::yLeft)->upperBound(); + #else + float ymin_curr = plot()->axisScaleDiv(QwtPlot::yLeft).lowerBound(); + float ymax_curr = plot()->axisScaleDiv(QwtPlot::yLeft).upperBound(); + #endif + if(ymin_currymin+y_width) ymax_curr=ymin+y_width; + plot()->setAxisScale(QwtPlot::yLeft,ymin_curr,ymax_curr); + } + plot()->replot(); + } + +#if QWT_VERSION<0x060000 + setZoomBase(QwtDoubleRect(xmin,ymin,x_width,y_width)); +#else + setZoomBase(QRectF(xmin,ymin,x_width,y_width)); +#endif +} + +void SlsQt1DZoomer::SetZoomBase(SlsQtH1D* h){ + x0 = h->GetXMin()<0 ? h->GetXMin()*1.02 : h->GetXMin()/1.02; + x1 = h->GetXMax()<0 ? h->GetXMax()/1.02 : h->GetXMax()*1.02; + y0 = h->GetYMin()<0 ? h->GetYMin()*1.02 : h->GetYMin()/1.02; + y1 = h->GetYMax()<0 ? h->GetYMax()/1.02 : h->GetYMax()*1.02; + + firstXgt0 = h->GetFirstXgtZero(); //for log plots + firstYgt0 = h->GetFirstYgtZero(); //for log plots + + ResetZoomBase(); +} + +void SlsQt1DZoomer::ExtendZoomBase(SlsQtH1D* h){ + double h_x0 = h->GetXMin()<0 ? h->GetXMin()*1.02 : h->GetXMin()/1.02; + double h_x1 = h->GetXMax()<0 ? h->GetXMax()/1.02 : h->GetXMax()*1.02; + double h_y0 = h->GetYMin()<0 ? h->GetYMin()*1.02 : h->GetYMin()/1.02; + double h_y1 = h->GetYMax()<0 ? h->GetYMax()/1.02 : h->GetYMax()*1.02; + + if(h_x0x1) x1 = h_x1; + if(h_y0y1) y1 = h_y1; + + if(h->GetFirstXgtZero()GetFirstXgtZero(); + if(h->GetFirstYgtZero()GetFirstYgtZero(); + + // cout<<"extend "< +#include +#include "SlsQt2DHist.h" + +using std::cout; +using std::endl; + +SlsQt2DHist::SlsQt2DHist(int nbinsx, double xmin, double xmax, int nbinsy, double ymin, double ymax, double* d,double zmin,double zmax):QwtRasterData(){ + x_min=0;x_max=0;y_min=0;y_max=0; + interp=0; + nx_array=ny_array=0;data=0; + SetData(nbinsx,xmin,xmax,nbinsy,ymin,ymax,d,zmin,zmax); +} + + +SlsQt2DHist::~SlsQt2DHist(){if(data) delete [] data;} + +int SlsQt2DHist::GetBinIndex(int bx, int by){ + int b = bx*ny+by; + if(b<0 || b>=nb){ + cout<<"GetBinIndex:: Incorrect indicies bx and by returning overflow bin;"<nx_array*ny_array){ + if(data) delete [] data; + data = new double [nbinsx*nbinsy+1]; //one for under/overflow bin + nx_array = nbinsx; + ny_array = nbinsy; + } + nx=nbinsx; + ny=nbinsy; + nb=nx*ny; + data[nb]=0;//set over flow to zero + if(d){ + memcpy(data,d,nb*sizeof(double)); + SetMinMax(zmin,zmax); + } +} + +void SlsQt2DHist::SetMinMax(double zmin,double zmax){ + if(zminz_max) z_max=data[i]; + z_mean+=data[i]; + } + z_mean/=nb; + if(z_min>0) z_min/=1.02; else z_min*=1.02; + if(z_max>0) z_max*=1.02; else z_max/=1.02; + } +#if QWT_VERSION<0x060000 + ; +#else + setInterval( Qt::ZAxis,QwtInterval(z_min,z_max)); +#endif + +} + +double SlsQt2DHist::GetMean(){ + if(!z_mean_has_been_calculated){ + z_mean_has_been_calculated = 1; + z_mean=0; + for(int i=0;i0 && data[i] +#include +#include +#include +#include + +#if QT_VERSION >= 0x040000 +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#include "SlsQt2DPlot.h" + +#if QWT_VERSION >= 0x060100 +#define QwtLog10ScaleEngine QwtLogScaleEngine +#endif + +using namespace std; + +SlsQt2DPlot::SlsQt2DPlot(QWidget *parent):QwtPlot(parent){ + isLog=0; + + axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); + + d_spectrogram = new QwtPlotSpectrogram(); + + hist = new SlsQt2DHist(); + SetupZoom(); + SetupColorMap(); + + +#if QWT_VERSION<0x060000 + d_spectrogram->setData(*hist); +#else + d_spectrogram->setData(hist); +#endif + + + d_spectrogram->attach(this); + + plotLayout()->setAlignCanvasToScales(true); + + FillTestPlot(); + Update(); + +} + + +void SlsQt2DPlot::SetupColorMap(){ + + + + + colorMapLinearScale = myColourMap(0); +#if QWT_VERSION<0x060000 + d_spectrogram->setColorMap(*colorMapLinearScale ); +#else + d_spectrogram->setColorMap(colorMapLinearScale ); +#endif + + colorMapLogScale = myColourMap(1); +#if QWT_VERSION<0x060000 + contourLevelsLinear = new QwtValueList(); + for(double level=0.5;level<10.0;level+=1.0 ) (*contourLevelsLinear) += level; + d_spectrogram->setContourLevels(*contourLevelsLinear); +#else + ; + + for(double level=0.5;level<10.0;level+=1.0 ) (contourLevelsLinear) += level; + d_spectrogram->setContourLevels(contourLevelsLinear); +#endif + + + // +#if QWT_VERSION<0x060000 + contourLevelsLog = new QwtValueList(); + for(double level=0.5;level<10.0;level+=1.0 ) (*contourLevelsLog) += (pow(10,2*level/10.0)-1)/99.0 * 10; + +#else + ; + + for(double level=0.5;level<10.0;level+=1.0 ) (contourLevelsLog) += (pow(10,2*level/10.0)-1)/99.0 * 10; +#endif + + + // A color bar on the right axis + rightAxis = axisWidget(QwtPlot::yRight); + + rightAxis->setTitle("Intensity"); + rightAxis->setColorBarEnabled(true); + enableAxis(QwtPlot::yRight); +} + +void SlsQt2DPlot::FillTestPlot(int mode){ + static int nx = 50; + static int ny = 50; + static double *the_data=0; + if(the_data==0) the_data = new double [nx*ny]; + + double dmax = sqrt(pow(nx/2.0-0.5,2) + pow(ny/2.0-0.5,2)); + for(int i=0;iSetData(nx,200,822,ny,-0.5,ny-0.5,the_data); +} + +void SlsQt2DPlot::SetupZoom(){ + // LeftButton for the zooming + // MidButton for the panning + // RightButton: zoom out by 1 + // Ctrl+RighButton: zoom out to full size + + zoomer = new SlsQt2DZoomer(canvas()); + zoomer->SetHist(hist); + +#if QT_VERSION < 0x040000 + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); +#else + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); +#endif + zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); + + panner = new QwtPlotPanner(canvas()); + panner->setAxisEnabled(QwtPlot::yRight, false); + panner->setMouseButton(Qt::MidButton); + + // Avoid jumping when labels with more/less digits + // appear/disappear when scrolling vertically + + const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); + QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); + sd->setMinimumExtent( fm.width("100.00") ); + + const QColor c(Qt::darkBlue); + zoomer->setRubberBandPen(c); + zoomer->setTrackerPen(c); +} + +/*void SlsQt2DPlot::CompletelyUnZoom(){ + setAxisScale(QwtPlot::xBottom,hist->GetXMin(),hist->GetXMin()+(hist->GetXMax()-hist->GetXMin())); + setAxisScale(QwtPlot::yLeft,hist->GetYMin(),hist->GetYMin()+(hist->GetYMax()-hist->GetYMin())); + zoomer->setZoomBase(); + //replot(); +}*/ + +void SlsQt2DPlot::UnZoom(){ +#if QWT_VERSION<0x060000 + zoomer->setZoomBase(QwtDoubleRect(hist->GetXMin(),hist->GetYMin(),hist->GetXMax()-hist->GetXMin(),hist->GetYMax()-hist->GetYMin())); +#else + zoomer->setZoomBase(QRectF(hist->GetXMin(),hist->GetYMin(),hist->GetXMax()-hist->GetXMin(),hist->GetYMax()-hist->GetYMin())); +#endif + zoomer->setZoomBase();//Call replot for the attached plot before initializing the zoomer with its scales. + // zoomer->zoom(0); +} + +void SlsQt2DPlot::SetZoom(double xmin,double ymin,double x_width,double y_width){ + +#if QWT_VERSION<0x060000 + zoomer->setZoomBase(QwtDoubleRect(xmin,ymin,x_width,y_width)); + +#else + zoomer->setZoomBase(QRectF(xmin,ymin,x_width,y_width)); +#endif +} + +void SlsQt2DPlot::SetZMinMax(double zmin,double zmax){ + hist->SetMinMax(zmin,zmax); +} + + +QwtLinearColorMap* SlsQt2DPlot::myColourMap(QVector colourStops) { + +int ns=5; + +double r[]={0.00, 0.00, 0.87, 1.00, 0.51}; +double g[]={0.00, 0.81, 1.00, 0.20, 0.00}; + double b[] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; + + QColor c1,c2,c; + c1.setRgbF(r[0],g[0],b[0],0); + c2.setRgbF(r[ns-1],g[ns-1],b[ns-1]); + QwtLinearColorMap* copyMap = new QwtLinearColorMap(Qt::lightGray, c2); + + for (int is=0; isaddColorStop(colourStops.value(is),c ); + } + + return copyMap; + + +} +QwtLinearColorMap* SlsQt2DPlot::myColourMap(int log) { + +int ns=5; + + + QVector cs1(0); + QVector lcs1(0); + + + cs1.append(0.); + cs1.append(0.34); + cs1.append(0.61); + cs1.append(0.84); + cs1.append(1.); +if (log) { + for (int is=0; issetColorMap(d_spectrogram->data().range(),d_spectrogram->colorMap()); +#else + if (isLog) + hist->SetMinimumToFirstGreaterThanZero(); + + const QwtInterval zInterval = d_spectrogram->data()->interval( Qt::ZAxis ); + + rightAxis->setColorMap(zInterval,myColourMap(isLog)); + +#endif + + if(!zoomer->zoomRectIndex()) UnZoom(); + +#if QWT_VERSION<0x060000 + + + setAxisScale(QwtPlot::yRight,d_spectrogram->data().range().minValue(), + d_spectrogram->data().range().maxValue()); +#else + + + setAxisScale(QwtPlot::yRight,zInterval.minValue(), zInterval.maxValue()); +#ifdef VERYVERBOSE + cout << "axis scale set" << endl; +#endif + plotLayout()->setAlignCanvasToScales(true); +#ifdef VERYVERBOSE + cout << "layout" << endl; +#endif +#endif +#ifdef VERYVERBOSE + cout << "going to replot" << endl; +#endif + replot(); +#ifdef VERYVERBOSE + cout << "done" << endl; +#endif +} + + + +void SlsQt2DPlot::showContour(bool on){ + d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ContourMode,on); + Update(); +} + +void SlsQt2DPlot::showSpectrogram(bool on){ + // static int io=0; + // FillTestPlot(io++); + d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ImageMode, on); + d_spectrogram->setDefaultContourPen(on ? QPen() : QPen(Qt::NoPen)); + Update(); +} + +void SlsQt2DPlot::InterpolatedPlot(bool on){ + hist->Interpolate(on); + Update(); +} + + +void SlsQt2DPlot::LogZ(bool on){ + if(on){ +isLog=1; + //if(hist->GetMinimum()<=0) hist->SetMinimumToFirstGreaterThanZero(); +#if QWT_VERSION<0x060000 + d_spectrogram->setColorMap(*colorMapLogScale); +#else + d_spectrogram->setColorMap(myColourMap(isLog)); +#endif + setAxisScaleEngine(QwtPlot::yRight,new QwtLog10ScaleEngine); +#if QWT_VERSION<0x060000 + d_spectrogram->setContourLevels(*contourLevelsLog); +#else + d_spectrogram->setContourLevels(contourLevelsLog); +#endif + }else{ +isLog=0; + +#if QWT_VERSION<0x060000 + d_spectrogram->setColorMap(*colorMapLinearScale); +#else + d_spectrogram->setColorMap(myColourMap(isLog)); +#endif + + + + setAxisScaleEngine(QwtPlot::yRight,new QwtLinearScaleEngine); + +#if QWT_VERSION<0x060000 + d_spectrogram->setContourLevels(*contourLevelsLinear); +#else + d_spectrogram->setContourLevels(contourLevelsLinear); +#endif + + } + Update(); + +} + +//Added by Dhanya on 19.06.2012 to disable zooming when any of the axes range has been set +void SlsQt2DPlot::DisableZoom(bool disableZoom){ +#ifdef VERBOSE + if(disableZoom) cout<<"Disabling zoom"<setMousePattern(QwtEventPattern::MouseSelect1,Qt::NoButton); +#if QT_VERSION < 0x040000 + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlButton); +#else + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlModifier); +#endif + zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::NoButton); + } + if(panner) panner->setMouseButton(Qt::NoButton); + }else { + if(zoomer){ + zoomer->setMousePattern(QwtEventPattern::MouseSelect1,Qt::LeftButton); +#if QT_VERSION < 0x040000 + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); +#else + zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); +#endif + zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); + } + if(panner) panner->setMouseButton(Qt::MidButton); + } +} + + +/* +void SlsQt2DPlot::printPlot(){ + QPrinter printer; + printer.setOrientation(QPrinter::Landscape); +#if QT_VERSION < 0x040000 + printer.setColorMode(QPrinter::Color); + printer.setOutputFileName("spectrogram.ps"); + if (printer.setup()) +#else + printer.setOutputFileName("spectrogram.pdf"); + QPrintDialog dialog(&printer); + if ( dialog.exec() ) +#endif + { + print(printer); + } +} + +*/ diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx new file mode 100644 index 0000000000..df80824a5e --- /dev/null +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx @@ -0,0 +1,239 @@ +/** + * @author Ian Johnson + * @version 1.0 + */ + + +#include + +#include +#include +#include +#include +#include + +#include "SlsQt2DPlotLayout.h" + +using namespace std; + +SlsQt2DPlotLayout::SlsQt2DPlotLayout(QWidget *parent):QGroupBox(parent){ + the_layout=0; + the_plot = new SlsQt2DPlot(this); + + z_range_ne = new SlsQtNumberEntry(this,1,"Set the z axis range from",2,"to",2); + z_range_ne->setFixedWidth(402); +#ifndef IAN + zRangeChecked = false; + z_range_ne->hide(); +#endif + + CreateTheButtons(); + Layout(); + ConnectSignalsAndSlots(); +} + +SlsQt2DPlotLayout::~SlsQt2DPlotLayout(){ + + if(the_layout) delete the_layout; + + + delete the_plot; + delete z_range_ne; +} + + +void SlsQt2DPlotLayout::CreateTheButtons(){ + /** Dhanya: All these buttons are already in another class, logz is used and a wrapper around it*/ +#ifdef IAN + btnInterpolate = new QToolButton(this); + btnInterpolate->setText("Interpolate"); + btnInterpolate->setCheckable(true); + btnInterpolate->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + + btnContour = new QToolButton(this); + btnContour->setText("Contour"); + btnContour->setCheckable(true); + btnContour->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); +#endif + btnLogz = new QToolButton(this); + btnLogz->setText("Log Scale (Z)"); + btnLogz->setCheckable(true); + btnLogz->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); +#ifndef IAN + btnLogz->hide(); +#endif +} + + +void SlsQt2DPlotLayout::Layout(){ + if(the_layout) delete the_layout; + the_layout = new QGridLayout(this); +#ifdef IAN + the_layout->addWidget(btnInterpolate,1,1); + the_layout->addWidget(btnContour,1,2); + the_layout->addWidget(btnLogz,1,3); + the_layout->addWidget(the_plot,2,1,3,3); + the_layout->addWidget(z_range_ne,5,1,1,3); + the_layout->setMargin(12); +#else + the_layout->addWidget(the_plot,2,0,3,3); + the_layout->addWidget(z_range_ne,5,0,1,3); +#endif +} + +void SlsQt2DPlotLayout::ConnectSignalsAndSlots(){ +#ifndef IAN + connect(this, SIGNAL(InterpolateSignal(bool)), the_plot, SLOT(InterpolatedPlot(bool))); + connect(this, SIGNAL(ContourSignal(bool)), the_plot, SLOT(showContour(bool))); +#else + connect(btnInterpolate, SIGNAL(toggled(bool)),the_plot, SLOT(InterpolatedPlot(bool))); + connect(btnContour, SIGNAL(toggled(bool)),the_plot, SLOT(showContour(bool))); + connect(btnLogz, SIGNAL(toggled(bool)),this,SLOT(SetZScaleToLog(bool))); + btnInterpolate->setChecked(false); + btnContour->setChecked(false); +#endif + connect(z_range_ne, SIGNAL(CheckBoxChanged(bool)), this, SLOT(ResetRange())); + connect(z_range_ne, SIGNAL(AValueChanged(SlsQtNumberEntry*)), this, SLOT(ResetRange())); + btnLogz->setChecked(false); +} + +void SlsQt2DPlotLayout::UpdateNKeepSetRangeIfSet(){ +#ifdef IAN + if(z_range_ne->CheckBoxState()){ +#endif + //just reset histogram range before update + the_plot->SetZMinMax(z_range_ne->GetValue(0),z_range_ne->GetValue(1)); +#ifdef IAN + } +#endif + the_plot->Update(); +} + +void SlsQt2DPlotLayout::ResetRange(){ + //refind z limits + the_plot->SetZMinMax(); + if(btnLogz->isChecked()) the_plot->SetZMinimumToFirstGreaterThanZero(); +#ifdef IAN + if(z_range_ne->CheckBoxState()){ +#else + if(zRangeChecked){ +#endif + //first time check validity + bool same = (z_range_ne->GetValue(0)==z_range_ne->GetValue(1)) ? 1:0; + if(!z_range_ne->IsValueOk(0)||same) z_range_ne->SetValue(the_plot->GetZMinimum(),0); + if(!z_range_ne->IsValueOk(1)||same) z_range_ne->SetValue(the_plot->GetZMaximum(),1); + z_range_ne->SetRange(the_plot->GetZMinimum(),z_range_ne->GetValue(1),0); + z_range_ne->SetRange(z_range_ne->GetValue(0),the_plot->GetZMaximum(),1); + + //set histogram range + the_plot->SetZMinMax(z_range_ne->GetValue(0),z_range_ne->GetValue(1)); + } + the_plot->Update(); +} + + +void SlsQt2DPlotLayout::ResetZMinZMax(bool zmin, bool zmax, double min, double max){ + + if(zmin || zmax) zRangeChecked = true; + else zRangeChecked = false; + + if(zmin) z_range_ne->SetNumber(min,0); + if(zmax) z_range_ne->SetNumber(max,1); + + + //refind z limits + the_plot->SetZMinMax(); + //finds zmin value from hist + if(btnLogz->isChecked()) + the_plot->SetZMinimumToFirstGreaterThanZero(); + + if(zRangeChecked){ + + //if value not given, take max or min of plot + if(zmax) z_range_ne->SetValue(max,0); + else z_range_ne->SetValue(the_plot->GetZMaximum(),1); + + if(zmin) z_range_ne->SetValue(min,0); + else z_range_ne->SetValue(the_plot->GetZMinimum(),0); + + //check if zmin and zmax is same or not a proper double value + //if(zmin && zmax){ + bool same = (z_range_ne->GetValue(0)==z_range_ne->GetValue(1)) ? 1:0; + if(!z_range_ne->IsValueOk(0)||same) z_range_ne->SetValue(the_plot->GetZMinimum(),0); + if(!z_range_ne->IsValueOk(1)||same) z_range_ne->SetValue(the_plot->GetZMaximum(),1); + //} + + z_range_ne->SetRange(the_plot->GetZMinimum(),z_range_ne->GetValue(1),0); + z_range_ne->SetRange(z_range_ne->GetValue(0),the_plot->GetZMaximum(),1); + + //set histogram range + the_plot->SetZMinMax(z_range_ne->GetValue(0),z_range_ne->GetValue(1)); + + } + the_plot->Update(); +} + + +void SlsQt2DPlotLayout::SetZScaleToLog(bool yes){ +#ifndef IAN +#ifdef VERBOSE + cout<<"Setting ZScale to log:"<setChecked(yes); +#endif + the_plot->LogZ(yes); + ResetRange(); +} + + +void SlsQt2DPlotLayout::SetXTitle(QString st){ +#ifndef IAN + QwtText title(st); + title.setFont(QFont("Sans Serif",11,QFont::Normal)); + GetPlot()->axisWidget(QwtPlot::xBottom)->setTitle(title); +#else + GetPlot()->axisWidget(QwtPlot::xBottom)->setTitle(st); +#endif +} + +void SlsQt2DPlotLayout::SetYTitle(QString st){ +#ifndef IAN + QwtText title(st); + title.setFont(QFont("Sans Serif",11,QFont::Normal)); + GetPlot()->axisWidget(QwtPlot::yLeft)->setTitle(title); +#else + GetPlot()->axisWidget(QwtPlot::yLeft)->setTitle(st); +#endif +} + +void SlsQt2DPlotLayout::SetZTitle(QString st){ +#ifndef IAN + QwtText title(st); + title.setFont(QFont("Sans Serif",11,QFont::Normal)); + GetPlot()->axisWidget(QwtPlot::yRight)->setTitle(title); +#else + GetPlot()->axisWidget(QwtPlot::yRight)->setTitle(st); +#endif +} + + +#ifndef IAN +void SlsQt2DPlotLayout::SetZRange(double zmin, double zmax){ +#ifdef VERBOSE + cout<<"zmin:"<SetNumber(zmin,0); + z_range_ne->SetNumber(zmax,1); + ResetRange(); +} + + +void SlsQt2DPlotLayout::EnableZRange(bool enable){ +#ifdef VERBOSE + cout<<"Setting Z Range Enable to "< +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "SlsQtNumberEntry.h" + +using namespace std; + +SlsQtNumberEntry::SlsQtNumberEntry(QWidget *parent, int with_checkbox, char *start_string, int num_type, char* middle_string, int num2_type, int n_units, char** units, double* unit_factors,char* end_string):QWidget(parent){ + SetupNumberEntry(with_checkbox,start_string,num_type,middle_string,num2_type,n_units,units,unit_factors,end_string); +} + +//without unit drop box +SlsQtNumberEntry::SlsQtNumberEntry(QWidget *parent,int with_checkbox, char *start_string, int num_type, char* middle_string, int num2_type,char* end_string):QWidget(parent){ + SetupNumberEntry(with_checkbox,start_string,num_type,middle_string,num2_type,0,0,0,end_string); +} + +void SlsQtNumberEntry::SetupNumberEntry(int with_checkbox, char *start_string, int num_type, char* middle_string, int num2_type, int n_units, char** units, double* unit_factors,char* end_string){ + + layout = 0; + + check_box = 0; + front_text = 0; + num_field[0] = 0; + spin_box[0] = 0; + validator_int[0] = 0; + validator_double[0] = 0; + middle_text = 0; + num_field[1] = 0; + spin_box[1] = 0; + validator_int[1] = 0; + validator_double[1] = 0; + unit_cbb = 0; + factors = 0; + back_text = 0; + if(with_checkbox) AddCheckBox(); + SetFrontText(start_string); + + SetupNumberField(num_type,0); + SetMiddleText(middle_string); + SetupNumberField(num2_type,1); + SetUnits(n_units,units,unit_factors); + SetBackText(end_string); + + SetLayout(); + +} + + +SlsQtNumberEntry::~SlsQtNumberEntry(){ + + if(check_box) delete check_box; + if(front_text) delete front_text; + if(middle_text) delete middle_text; + if(validator_int[0]) delete validator_int[0]; + if(validator_double[0]) delete validator_double[0]; + if(num_field[0]) delete num_field[0]; + if(spin_box[0]) delete spin_box[0]; + if(validator_int[1]) delete validator_int[1]; + if(validator_double[1]) delete validator_double[1]; + if(num_field[1]) delete num_field[1]; + if(spin_box[1]) delete spin_box[1]; + if(unit_cbb) delete unit_cbb; + if(factors) delete factors; + if(back_text) delete back_text; + +} + +void SlsQtNumberEntry::AddCheckBox(){ + if(check_box) delete check_box; + check_box = new QCheckBox(this); + connect(check_box,SIGNAL(clicked()),this,SLOT(CheckBoxClicked())); + SetLayout(); +} + +void SlsQtNumberEntry::SetFrontText(char* s) {SetText(s,&front_text); SetLayout();} +void SlsQtNumberEntry::SetMiddleText(char* s) {SetText(s,&middle_text); SetLayout();} +void SlsQtNumberEntry::SetBackText(char* s) {SetText(s,&back_text); SetLayout();}; +void SlsQtNumberEntry::SetText(char* s, QLabel** pp){ + if(*pp){delete *pp; *pp=0;} + if(s){ + *pp = new QLabel(this); + (*pp)->setText(s); + } + SetLayout(); +} + + +void SlsQtNumberEntry::SetupNumberField(int type, int which_number_field){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + + num_field_enabled[i]=1; + if(spin_box[i]) { delete spin_box[i]; spin_box[i]=0;} + if(validator_int[i]) { delete validator_int[i]; validator_int[i]=0;} + if(validator_double[i]) { delete validator_double[i]; validator_double[i]=0;} + if(num_field[i]) { delete num_field[i]; num_field[i]=0;} + + if(type>0&&type<3){ + num_field[i] = new QLineEdit(this); + num_field[i]->setAlignment(Qt::AlignRight); + SetMinimumNumberWidth(3,i); + if(type==1){ + validator_int[i] = new SlsQtIntValidator(num_field[i]); + num_field[i]->setValidator(validator_int[i]); + SetNumber(0,i); + }else{ + validator_double[i] = new SlsQtDoubleValidator(num_field[i]); + num_field[i]->setValidator(validator_double[i]); + //default settings + SetNDecimalsOfDoubleValidator(3,i); //defalut value + SetNumber(0,i); + } + + num_field[i]->setAlignment(Qt::AlignRight); + + if(i==0){ + connect(num_field[i],SIGNAL(lostFocus()),this,SLOT(RefreshFirstNumberEntry())); + connect(num_field[i],SIGNAL(returnPressed()),this,SLOT(FirstValueEntered())); + connect(num_field[i],SIGNAL(lostFocus()),this,SLOT(FirstValueEntered())); + }else{ + connect(num_field[i],SIGNAL(lostFocus()),this,SLOT(RefreshSecondNumberEntry())); + connect(num_field[i],SIGNAL(returnPressed()),this,SLOT(SecondValueEntered())); + connect(num_field[i],SIGNAL(lostFocus()),this,SLOT(SecondValueEntered())); + } + }else if(type==3){ + spin_box[i] = new QSpinBox(); + if(i==0) connect(spin_box[i],SIGNAL(editingFinished()),this,SLOT(FirstValueEntered())); + else connect(spin_box[i],SIGNAL(editingFinished()),this,SLOT(SecondValueEntered())); + spin_box[i]->setAlignment(Qt::AlignRight); + } + + SetLayout(); +} + +void SlsQtNumberEntry::SetUnits(int n_units, char** units, double* unit_factors){ + if(unit_cbb){ delete unit_cbb; unit_cbb=0;} + if(factors) { delete factors; factors=0;} + + if(n_units>0&&units&&unit_factors){ + unit_cbb = new QComboBox(this); + factors = new double [n_units]; + + for(int i=0;iinsertItem(i,units[i]); + factors[i] = unit_factors[i]; + } + + connect(unit_cbb,SIGNAL(activated(int)),this,SLOT(UnitSelected())); + } + + SetLayout(); +} + +void SlsQtNumberEntry::SetLayout(){ + if(layout) delete layout; + layout = new QGridLayout(this); + + int i = 0; + if(check_box) layout->addWidget(check_box,1,i++); + if(front_text) layout->addWidget(front_text,1,i++); + if(num_field[0]) layout->addWidget(num_field[0],1,i++); + if(spin_box[0]) layout->addWidget(spin_box[0],1,i++); + if(middle_text) layout->addWidget(middle_text,1,i++); + if(num_field[1]) layout->addWidget(num_field[1],1,i++); + if(spin_box[1]) layout->addWidget(spin_box[1],1,i++); + if(unit_cbb) layout->addWidget(unit_cbb,1,i++); + if(back_text) layout->addWidget(back_text,1,i++); + + CheckBoxClicked(); +} + + +void SlsQtNumberEntry::SetMinimumNumberWidth(int nchar_width,int which_number_field){ + if(num_field[which_number_field]) num_field[which_number_field] + ->setMinimumWidth(nchar_width*num_field[which_number_field]->minimumSizeHint().width()); + if(spin_box[which_number_field]) spin_box[which_number_field] + ->setMinimumWidth(nchar_width*spin_box[which_number_field]->minimumSizeHint().width()); +} + +void SlsQtNumberEntry::SetNDecimalsOfDoubleValidators(int ndecimals){ + SetNDecimalsOfDoubleValidator(ndecimals,0); + SetNDecimalsOfDoubleValidator(ndecimals,1); +} + +void SlsQtNumberEntry::SetNDecimalsOfDoubleValidator(int ndecimals, int which_number_field){ + //0 -> standard, 1->scientific + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + if(validator_double[i]){ + validator_double[i]->setDecimals(ndecimals); + SetNumber(GetNumber(i),i); + } +} + +void SlsQtNumberEntry::SetMinimumUnitWidth(int nchar_width){ + if(unit_cbb) unit_cbb->setMinimumWidth(nchar_width*unit_cbb->minimumSizeHint().width()); +} + + +/* +double SlsQtNumberEntry::SetNumber(int v,int which_number_field){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + + if(num_field[i]){ + if(validator_int[i]){ + QString s = QString::number(v); + validator_int[i]->fixup(s); + num_field[i]->setText(s); + } + if(validator_double[i]){ + QString s = QString::number(v); + validator_double[i]->fixup(s); + num_field[i]->setText(s); + } + }else if(spin_box[i]){ + spin_box[i]->setValue(v); + }else return 0; + + return GetNumber(i); +} +*/ + +double SlsQtNumberEntry::SetNumber(double v,int which_number_field){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + + if(num_field[i]){ + if(validator_int[i]){ + QString s = QString::number(v); + validator_int[i]->fixup(s); + num_field[i]->setText(s); + } + if(validator_double[i]){ + QString s = QString::number(v); + //validator_double[i]->fixup(s);//commented out as it ignores the zmax values + num_field[i]->setText(s); + } + }else if(spin_box[i]){ + spin_box[i]->setValue(round(v)); + }else return 0; + + return GetNumber(i); +} + + +void SlsQtNumberEntry::SetRange(int min, int max,int which_number_field){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + if(min>max){ + cout<<"Warning: SetRange(int,int) no effect min > max"<setRange(min,max); + if(validator_double[i]) validator_double[i]->setRange(min,max,validator_double[i]->decimals()); + if(spin_box[i]) spin_box[i]->setRange(min,max); + SetNumber(GetNumber(i),i); + } +} + + +void SlsQtNumberEntry::SetRange(double min, double max,int which_number_field){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + if(min>max){ + cout<<"Warning: SetRange(double,double) no effect min("<= max("<setRange(min,max,validator_double[i]->decimals()); + if(spin_box[i]) spin_box[i]->setRange(min,max); + SetNumber(GetNumber(i),i); + } + +} + +bool SlsQtNumberEntry::CheckBoxState(){ + if(check_box&&check_box->checkState()) return 1; + return 0; +} + +void SlsQtNumberEntry::CheckBoxClicked(){ + if(check_box){ + if(check_box->checkState()) Enable(); + else Disable(); + + emit CheckBoxChanged(check_box->checkState()); + emit CheckBoxChanged(this); + } + +} + +void SlsQtNumberEntry::Disable(){ Enable(0); } +void SlsQtNumberEntry::Enable(bool en_flag){ + if(check_box) check_box->setChecked(en_flag); + if(front_text) front_text->setEnabled(en_flag); + if(num_field[0]) num_field[0]->setEnabled(en_flag&&num_field_enabled[0]); + if(spin_box[0]) spin_box[0]->setEnabled(en_flag&&num_field_enabled[0]); + if(middle_text) middle_text->setEnabled(en_flag); + if(num_field[1]) num_field[1]->setEnabled(en_flag&&num_field_enabled[1]); + if(spin_box[1]) spin_box[1]->setEnabled(en_flag&&num_field_enabled[1]); + if(unit_cbb) unit_cbb->setEnabled(en_flag); + if(back_text) back_text->setEnabled(en_flag); +} + +void SlsQtNumberEntry::DisableNumberField(int which_number_field){ EnableNumberField(which_number_field,0); } +void SlsQtNumberEntry::EnableNumberField(int which_number_field,bool en_flag){ + if(which_number_field>=0||which_number_field<=1){ + num_field_enabled[which_number_field]=en_flag; + if(num_field[which_number_field]) num_field[which_number_field]->setEnabled(num_field_enabled[which_number_field]); + if(spin_box[which_number_field]) spin_box[which_number_field]->setEnabled(num_field_enabled[which_number_field]); + } +} + +void SlsQtNumberEntry::UnitSelected(){ + emit UnitChanged(GetComboBoxValue()); + emit UnitChanged(this); + emit AValueChanged(this); + emit FirstValueChanged(GetValueInt(0)); + emit FirstValueChanged(GetValue(0)); + emit FirstValueChanged(this); + emit SecondValueChanged(GetValueInt(1)); + emit SecondValueChanged(GetValue(1)); + emit SecondValueChanged(this); +} + +void SlsQtNumberEntry::RefreshFirstNumberEntry() { RefreshNumberEntery(0);} +void SlsQtNumberEntry::RefreshSecondNumberEntry() { RefreshNumberEntery(1);} +void SlsQtNumberEntry::RefreshNumberEntery(int which_number_field){ + //does not apply to spin boxes + if(num_field[which_number_field]){ + SetNumber(GetNumber(which_number_field),which_number_field); + } + //refreshes the entery in a general format for ints and fixes doubles, + //for example removes leading zeros + //However, also moves curser position +} + +void SlsQtNumberEntry::FirstValueEntered(){ + emit AValueChanged(this); + emit FirstValueChanged(GetValue(0)); + emit FirstValueChanged(GetValueInt(0)); + emit FirstValueChanged(this); +} + +void SlsQtNumberEntry::SecondValueEntered(){ + emit AValueChanged(this); + emit SecondValueChanged(GetValue(1)); + emit SecondValueChanged(GetValueInt(1)); + emit SecondValueChanged(this); +} + + +bool SlsQtNumberEntry::Enabled(){ + if(check_box && !check_box->checkState()) return 0; + return 1; +} + +bool SlsQtNumberEntry::IsValueOk(int which_number_field){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + + bool ok=0; + if(validator_int[i]) num_field[i]->text().toInt(&ok); + if(validator_double[i]) num_field[i]->text().toDouble(&ok); + if(spin_box[i]) ok=true; + + return ok; +} + +const char* SlsQtNumberEntry::GetFrontText(){ + if(front_text) return front_text->text().toStdString().c_str(); + return 0; +} +const char* SlsQtNumberEntry::GetMiddleText(){ + if(middle_text) return middle_text->text().toStdString().c_str(); + return 0; +} +const char* SlsQtNumberEntry::GetBackText(){ + if(back_text) back_text->text().toStdString().c_str(); + return 0; +} + +int SlsQtNumberEntry::GetNumberInt(int which_number_field,bool* ok){ + return round(GetNumber(which_number_field,ok)); +} + +double SlsQtNumberEntry::GetNumber(int which_number_field,bool* ok){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + + if(ok) *ok = 1; + + if(num_field[i]){ + if(validator_int[i]) return num_field[i]->text().toInt(ok); + else return num_field[i]->text().toDouble(ok); + } + else if(spin_box[i]) return spin_box[i]->value(); + else {if(ok) *ok=0;} + + return 0; +} + + + +double SlsQtNumberEntry::SetValue(double v,int which_number_field){ + if(unit_cbb) SetNumber(round(v/GetComboBoxValue()),which_number_field); + else SetNumber(v,which_number_field); + + return GetValue(which_number_field); +} + + +int SlsQtNumberEntry::GetValueInt(int which_number_field,bool* ok){ + return round(GetValue(which_number_field,ok)); +} + +double SlsQtNumberEntry::GetValue(int which_number_field,bool* ok){ + int i = (which_number_field<0||which_number_field>1) ? 0:which_number_field; + + double v; + if(ok) *ok = 1; + + if(num_field[i]){ + if(validator_int[i]) v = num_field[i]->text().toInt(ok); + else v = num_field[i]->text().toDouble(ok); + } + else if(spin_box[i]) v = spin_box[i]->value(); + else v = 1; //incase there is only a unit pulldown + + + if(unit_cbb) v *= GetComboBoxValue(); + + if(!num_field[i]&&!spin_box[i]&&!unit_cbb){v=0; if(ok) *ok=0;} + + return v; +} + + +int SlsQtNumberEntry::SetComboBoxIndex(int index){ + if(unit_cbb){ + if(index<0||index>=unit_cbb->count()){ + cout<<"usage error : can not set combo box index, index out of range."<setCurrentIndex(index); + } + } + else cout<<"usage error : can not set combo box index, no combo box."<currentIndex(); + + cout<<"usage error : can not get combo box index, no combo box."<currentIndex()]; + + cout<<"usage error : can not get combo box value, no combo box."< +// C++ Include Headers +#include +using namespace std; + +//------------------------------------------------------------------------------------------------------------------------------------------------- +int qActionsWidget::NUM_ACTION_WIDGETS(0); +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qActionsWidget::qActionsWidget(QWidget *parent,multiSlsDetector*& detector): + QWidget(parent),myDet(detector){ + setupUi(this); + SetupWidgetWindow(); + Initialization(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qActionsWidget::~qActionsWidget(){ + delete myDet; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qActionsWidget::SetupWidgetWindow(){ + id = NUM_ACTION_WIDGETS; + NUM_ACTION_WIDGETS++; + + setFixedHeight(25); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qActionsWidget::Initialization(){ + //mode + connect(comboScript, SIGNAL(currentIndexChanged(int)), this,SLOT(SetMode(int))); + //file + connect(dispScript, SIGNAL(editingFinished()), this, SLOT(SetScriptFile())); + connect(btnBrowse, SIGNAL(clicked()), this, SLOT(BrowsePath())); + //parameter + connect(dispParameter, SIGNAL(editingFinished()), this, SLOT(SetParameter())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qActionsWidget::SetMode(int mode){ +#ifdef VERBOSE + cout << "Setting\taction:" << id << "\tmode:" << mode << endl; +#endif + //enabling/disabling + dispScript->setEnabled(mode); + btnBrowse->setEnabled(mode); + lblParameter->setEnabled(mode); + dispParameter->setEnabled(mode); + + QString fName = dispScript->text(); + //set the mode + if(mode) myDet->setActionScript(id,fName.toAscii().constData()); + else myDet->setActionScript(id,""); + //mode is not set when fname is blank + + if(!fName.isEmpty()){ + //check if mode didnt get set + if(mode!=myDet->getActionMode(id)){ + qDefs::Message(qDefs::WARNING,"The mode could not be changed.","qActionsWidget::SetMode"); + comboScript->setCurrentIndex(myDet->getActionMode(id)); + }//if mode got set and its custom script + else if(mode){ + //when the file name did not get set correctly + if(fName.compare(QString(myDet->getActionScript(id).c_str()))){ + qDefs::Message(qDefs::WARNING,"The file path could not be set.","qActionsWidget::SetMode"); + dispScript->setText(QString(myDet->getActionScript(id).c_str())); + SetScriptFile(); + } + } + } + qDefs::checkErrorMessage(myDet,"qActionsWidget::SetMode"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qActionsWidget::BrowsePath(){ +#ifdef VERBOSE + cout << "Browsing Script File Path" << endl; +#endif + QString fName = dispScript->text(); + QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); + if(dir.isEmpty()) dir = "/home"; + //dialog + fName = QFileDialog::getOpenFileName(this, + tr("Load Script File"),dir, + tr("Script Files(*.awk);;All Files(*)")); + //if empty, set the file name and it calls setscriptfile, else ignore + if (!fName.isEmpty()){ + dispScript->setText(fName); + SetScriptFile(); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qActionsWidget::SetScriptFile(){ + QString fName = dispScript->text(); +#ifdef VERBOSE + cout << "Setting\taction:" << id << "\tscript:" << fName.toAscii().constData() << endl; +#endif + bool set = false; + struct stat st_buf; + + //blank + if(fName.isEmpty()) + set = true; + else if(!fName.compare("none")) + set = true; + //not blank + else{ + //path doesnt exist + if(stat(fName.toAscii().constData(),&st_buf)){ + qDefs::Message(qDefs::WARNING,"The script file entered does not exist","qActionsWidget::SetScriptFile"); + dispScript->setText(QString(myDet->getActionScript(id).c_str())); + } + //if its not a file + else if (!S_ISREG (st_buf.st_mode)) { + qDefs::Message(qDefs::WARNING,"The script file path entered is not a file","qActionsWidget::SetScriptFile"); + dispScript->setText(QString(myDet->getActionScript(id).c_str())); + } + else + set=true; + } + + + //if blank or valid file + if(set){ + //scan and positions wouldnt get here + myDet->setActionScript(id,fName.toAscii().constData()); + if(fName.compare(QString(myDet->getActionScript(id).c_str()))){ + //did not get set, write what is was before + if(!fName.isEmpty()) + qDefs::Message(qDefs::WARNING,"The script file could not be set. Reverting to previous file.","qActionsWidget::SetScriptFile"); + dispScript->setText(QString(myDet->getActionScript(id).c_str())); + } + } + + //dont display if theres a none + if(!dispScript->text().compare("none")) dispScript->setText(""); + + qDefs::checkErrorMessage(myDet,"qActionsWidget::SetScriptFile"); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qActionsWidget::SetParameter(){ + QString parameter = dispParameter->text(); +#ifdef VERBOSE + cout << "Setting\taction:" << id << "\tparameter:" << parameter.toAscii().constData() << endl; +#endif + myDet->setActionParameter(id,parameter.toAscii().constData()); + //dont display if theres a none + if(!dispParameter->text().compare("none")) dispParameter->setText(""); + + qDefs::checkErrorMessage(myDet,"qActionsWidget::SetParameter"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qActionsWidget::Refresh(){ + int mode = (myDet->getActionMode(id)>0?1:0); + string script = myDet->getActionScript(id); + string parameter = myDet->getActionParameter(id); + + + //settings values and checking for none + if(QString(script.c_str()).compare("none")) + dispScript->setText(QString(script.c_str())); + if(mode)SetScriptFile(); + dispParameter->setText(QString(parameter.c_str())); + SetParameter(); + //set mode which also checks everything + comboScript->setCurrentIndex(mode); +#ifdef VERBOSE + cout << "Updated\taction:" << id << "\t" + "mode:"< +#include +#include +#include "qwt_symbol.h" +/** C++ Include Headers */ + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +qCloneWidget::qCloneWidget(QWidget *parent,int id,QString title,QString xTitle, QString yTitle, QString zTitle, + int numDim,string FilePath,bool displayStats, QString min, QString max, QString sum): + QMainWindow(parent),id(id),cloneplot2D(0),cloneplot1D(0),filePath(FilePath) + { + // Window title + char winTitle[300],currTime[50]; + strcpy(currTime,GetCurrentTimeStamp()); + sprintf(winTitle,"Snapshot:%d - %s",id,currTime); + setWindowTitle(QString(winTitle)); + + marker = new QwtSymbol(); + nomarker = new QwtSymbol(); + marker->setStyle(QwtSymbol::Cross); + marker->setSize(5,5); + + // Set up widget + SetupWidgetWindow(title,xTitle, yTitle, zTitle, numDim); + DisplayStats(displayStats,min,max,sum); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +qCloneWidget::~qCloneWidget(){ + delete cloneplot1D; + delete cloneplot2D; + delete cloneBox; +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qCloneWidget::SetupWidgetWindow(QString title, QString xTitle, QString yTitle, QString zTitle, int numDim){ + + menubar = new QMenuBar(this); + actionSave = new QAction("&Save",this); + menubar->addAction(actionSave); + setMenuBar(menubar); + + + //Main Window Layout + QWidget *centralWidget = new QWidget(this); + mainLayout = new QGridLayout(centralWidget); + centralWidget->setLayout(mainLayout); + + //plot group box + cloneBox = new QGroupBox(this); + gridClone = new QGridLayout(cloneBox); + cloneBox->setLayout(gridClone); + cloneBox->setContentsMargins(0,0,0,0); + cloneBox->setAlignment(Qt::AlignHCenter); + cloneBox->setFont(QFont("Sans Serif",11,QFont::Normal)); + cloneBox->setTitle(title); + // According to dimensions, create appropriate 1D or 2Dplot + if(numDim==1){ + cloneplot1D = new SlsQt1DPlot(cloneBox); + + cloneplot1D->setFont(QFont("Sans Serif",9,QFont::Normal)); + cloneplot1D->SetXTitle(xTitle.toAscii().constData()); + cloneplot1D->SetYTitle(yTitle.toAscii().constData()); + + + cloneBox->setFlat(false); + cloneBox->setContentsMargins(0,30,0,0); + gridClone->addWidget(cloneplot1D,0,0); + + lblHistTitle = new QLabel(""); + mainLayout->addWidget(lblHistTitle,0,0); + + }else{ + cloneplot2D = new SlsQt2DPlotLayout(cloneBox); + cloneplot2D->setFont(QFont("Sans Serif",9,QFont::Normal)); + cloneplot2D->SetXTitle(xTitle); + cloneplot2D->SetYTitle(yTitle); + cloneplot2D->SetZTitle(zTitle); + cloneplot2D->setAlignment(Qt::AlignLeft); + + cloneBox->setFlat(true); + cloneBox->setContentsMargins(0,20,0,0); + gridClone->addWidget(cloneplot2D,0,0); + } + + // main window widgets + mainLayout->addWidget(cloneBox,1,0); + setCentralWidget(centralWidget); + + // Save + connect(actionSave,SIGNAL(triggered()),this,SLOT(SavePlot())); + + setMinimumHeight(300); + resize(500,350); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qCloneWidget::SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis[],string histTitle[],bool lines,bool markers){ + //for each plot, create hists + for(int hist_num=0;hist_numcloneplot1D_hists.size()){ + cloneplot1D_hists.append(k=new SlsQtH1D("1d plot",histNBins,histXAxis,histYAxis[hist_num])); + k->SetLineColor(0); + }else{ + k=cloneplot1D_hists.at(hist_num); + k->SetData(histNBins,histXAxis,histYAxis[hist_num]); + } + + + //style of plot + if(lines) k->setStyle(QwtPlotCurve::Lines); + else k->setStyle(QwtPlotCurve::Dots); +#if QWT_VERSION<0x060000 + if(markers) k->setSymbol(*marker); + else k->setSymbol(*nomarker); +#else + if(markers) k->setSymbol(marker); + else k->setSymbol(nomarker); +#endif + + //set title and attach plot + lblHistTitle->setText(QString(histTitle[0].c_str())); + + k->Attach(cloneplot1D); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qCloneWidget::SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis,string histTitle[],bool lines,bool markers){ + // for each plot create hists + for(int hist_num=0;hist_numcloneplot1D_hists.size()){ + cloneplot1D_hists.append(k=new SlsQtH1D("1d plot",histNBins,histXAxis,histYAxis)); + k->SetLineColor(hist_num+1); + }else{ + k=cloneplot1D_hists.at(hist_num); + k->SetData(histNBins,histXAxis,histYAxis); + } + //style of plot + if(lines) k->setStyle(QwtPlotCurve::Lines); + else k->setStyle(QwtPlotCurve::Dots); + if(markers) { + QwtSymbol *marker = new QwtSymbol(); + marker->setStyle(QwtSymbol::Cross); + marker->setSize(5,5); +#if QWT_VERSION<0x060000 + k->setSymbol(*marker); +#else + k->setSymbol(marker); +#endif + }else { + QwtSymbol *noMarker = new QwtSymbol(); +#if QWT_VERSION<0x060000 + k->setSymbol(*noMarker); +#else + k->setSymbol(noMarker); +#endif + } + //set title and attach plot + lblHistTitle->setText(QString(histTitle[0].c_str())); + k->Attach(cloneplot1D); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qCloneWidget::SetCloneHists2D(int nbinsx,double xmin,double xmax,int nbinsy, double ymin, double ymax, double *d){ + cloneplot2D->GetPlot()->SetData(nbinsx,xmin,xmax,nbinsy,ymin,ymax,d); + cloneplot2D->UpdateNKeepSetRangeIfSet(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +void qCloneWidget::SetRange(bool IsXYRange[],double XYRangeValues[]){ + double XYCloneRangeValues[4]; + + if(!IsXYRange[qDefs::XMINIMUM]){ + if(cloneplot1D) XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot1D->GetXMinimum(); + else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetXMinimum(); + }else XYCloneRangeValues[qDefs::XMINIMUM]= XYRangeValues[qDefs::XMINIMUM]; + + if(!IsXYRange[qDefs::XMAXIMUM]){ + if(cloneplot1D) XYCloneRangeValues[qDefs::XMAXIMUM]= cloneplot1D->GetXMaximum(); + else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetXMaximum(); + }else XYCloneRangeValues[qDefs::XMAXIMUM]= XYRangeValues[qDefs::XMAXIMUM]; + + if(!IsXYRange[qDefs::YMINIMUM]){ + if(cloneplot1D) XYCloneRangeValues[qDefs::YMINIMUM]= cloneplot1D->GetYMinimum(); + else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetYMinimum(); + }else XYCloneRangeValues[qDefs::YMINIMUM]= XYRangeValues[qDefs::YMINIMUM]; + + if(!IsXYRange[qDefs::YMAXIMUM]){ + if(cloneplot1D) XYCloneRangeValues[qDefs::YMAXIMUM]= cloneplot1D->GetYMaximum(); + else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetYMaximum(); + }else XYCloneRangeValues[qDefs::YMAXIMUM]= XYRangeValues[qDefs::YMAXIMUM]; + + if(cloneplot1D){ + cloneplot1D->SetXMinMax(XYCloneRangeValues[qDefs::XMINIMUM],XYCloneRangeValues[qDefs::XMAXIMUM]); + cloneplot1D->SetYMinMax(XYCloneRangeValues[qDefs::YMINIMUM],XYCloneRangeValues[qDefs::YMAXIMUM]); + }else{ + cloneplot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM],XYRangeValues[qDefs::XMAXIMUM]); + cloneplot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM],XYRangeValues[qDefs::YMAXIMUM]); + cloneplot2D->GetPlot()->Update(); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +char* qCloneWidget::GetCurrentTimeStamp(){ + char output[30]; + char *result; + + //using sys cmds to get output or str + FILE* sysFile = popen("date", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + + result = output + 0; + return result; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qCloneWidget::SavePlot(){ + char cID[10]; + sprintf(cID,"%d",id); + //title + QString fName = QString(filePath.c_str()); + if(cloneBox->title().contains('.')){ + fName.append(QString('/')+cloneBox->title()); + fName.replace(".dat",".png"); + fName.replace(".raw",".png"); + }else fName.append(QString("/Snapshot_unknown_title.png")); + //save + QImage img(cloneBox->size().width(),cloneBox->size().height(),QImage::Format_RGB32); + QPainter painter(&img); + cloneBox->render(&painter); + + fName = QFileDialog::getSaveFileName(this,tr("Save Snapshot "),fName,tr("PNG Files (*.png);;XPM Files(*.xpm);;JPEG Files(*.jpg)"),0,QFileDialog::ShowDirsOnly); + if (!fName.isEmpty()) + if((img.save(fName))) + qDefs::Message(qDefs::INFORMATION,"The SnapShot has been successfully saved","qCloneWidget::SavePlot"); + else + qDefs::Message(qDefs::WARNING,"Attempt to save snapshot failed.\n" + "Formats: .png, .jpg, .xpm.","qCloneWidget::SavePlot"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qCloneWidget::SavePlotAutomatic(){ + char cID[10]; + sprintf(cID,"%d",id); + //title + QString fName = QString(filePath.c_str()); + if(cloneBox->title().contains('.')){ + fName.append(QString('/')+cloneBox->title()); + fName.replace(".dat",".png"); + fName.replace(".raw",".png"); + }else fName.append(QString("/Snapshot_unknown_title.png")); + cout<<"fname:"<size().width(),cloneBox->size().height(),QImage::Format_RGB32); + QPainter painter(&img); + cloneBox->render(&painter); + if(img.save(fName)) + return 0; + else return -1; + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qCloneWidget::closeEvent(QCloseEvent* event){ + emit CloneClosedSignal(id); + event->accept(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qCloneWidget::DisplayStats(bool enable, QString min, QString max, QString sum){ + if(enable){ + QWidget *widgetStatistics = new QWidget(this); + widgetStatistics->setFixedHeight(15); + QHBoxLayout *hl1 = new QHBoxLayout; + hl1->setSpacing(0); + hl1->setContentsMargins(0, 0, 0, 0); + QLabel *lblMin = new QLabel("Min: "); + lblMin->setFixedWidth(40); + lblMin->setAlignment(Qt::AlignRight); + QLabel *lblMax = new QLabel("Max: "); + lblMax->setFixedWidth(40); + lblMax->setAlignment(Qt::AlignRight); + QLabel *lblSum = new QLabel("Sum: "); + lblSum->setFixedWidth(40); + lblSum->setAlignment(Qt::AlignRight); + QLabel *lblMinDisp = new QLabel(min); + lblMinDisp->setAlignment(Qt::AlignLeft); + QLabel *lblMaxDisp = new QLabel(max); + lblMaxDisp->setAlignment(Qt::AlignLeft); + QLabel *lblSumDisp = new QLabel(sum); + lblSumDisp->setAlignment(Qt::AlignLeft); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + hl1->addWidget(lblMin); + hl1->addWidget(lblMinDisp); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); + hl1->addWidget(lblMax); + hl1->addWidget(lblMaxDisp); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); + hl1->addWidget(lblSum); + hl1->addWidget(lblSumDisp); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + widgetStatistics->setLayout(hl1); + mainLayout->addWidget(widgetStatistics,2,0); + widgetStatistics->show(); + + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + diff --git a/slsDetectorGui/src/qDetectorMain.cpp b/slsDetectorGui/src/qDetectorMain.cpp new file mode 100644 index 0000000000..3123f457f9 --- /dev/null +++ b/slsDetectorGui/src/qDetectorMain.cpp @@ -0,0 +1,898 @@ +/********************************************************************** + * TO DO + * 1. settcpsocket is done with slsdetector.maybe do for all detectors connected: mythen + * ********************************************************************/ +// Qt Project Class Headers +#include "qDetectorMain.h" +#include "qTabDataOutput.h" +#include "qTabPlot.h" +#include "qTabActions.h" +#include "qTabAdvanced.h" +#include "qTabSettings.h" +#include "qTabDebugging.h" +#include "qTabDeveloper.h" +#include "qTabMessages.h" +#include "qServer.h" +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +#include "sls_detector_defs.h" +#include "gitInfoGui.h" +// Qt Include Headers +#include +#include +#include +// C++ Include Headers +#include +#include +#include +using namespace std; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +int main (int argc, char **argv) { + QApplication *theApp = new QApplication(argc, argv); + // QApplication *theApp = new QApplication(argc, argv); + theApp->setStyle(new QPlastiqueStyle);//not default when desktop is windows + theApp->setWindowIcon(QIcon( ":/icons/images/mountain.png" )); + qDetectorMain *det=new qDetectorMain(argc, argv, theApp,0); + det->show(); + //theApp->connect( theApp, SIGNAL(lastWindowClosed()), theApp, SLOT(quit())); + return theApp->exec(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qDetectorMain::qDetectorMain(int argc, char **argv, QApplication *app, QWidget *parent) : + QMainWindow(parent), theApp(app),myDet(0),detID(0),myPlot(0),tabs(0),isDeveloper(0){ +// bool found; + int c; + string configFName = ""; + optind=1; + // Getting all the command line arguments + while(1) { + static struct option long_options[] = { + { "developer", no_argument, 0, 'd' }, + { "config", required_argument, 0, 'f' }, + { "id", required_argument, 0, 'i' }, + { "f", required_argument, 0, 'f' }, + { "help", no_argument, 0, 'h' }, + { 0, 0, 0, 0 } + }; + c = getopt_long (argc, argv, "hdf:i:", long_options, NULL); + if (c == -1) break; + + switch (c) { + case 'd' : + isDeveloper=1; + break; + case 'f' : + configFName=string(optarg); + break; + case 'i' : + detID=atoi(optarg); + break; + case 'h' : + default: + cout << endl; + cout << "\t" << argv[0] << " [ARGUMENT]..." << endl; + cout << endl; + cout << "Possible Arguments are:" << endl; + cout << "\t-d, --developer \t\t : \t Enables the developer tab" << endl; + cout << "\t-f, --f, --config fname\t\t : \t Loads config file fname" << endl; + cout << "\t-i, --id NUMBER \t\t : \t Sets the multi detector id to NUMBER (the default is 0). " + "Required only when more than one multi detector object is needed." << endl; + exit(-1); + } + } + if (optind < argc) { + cout << "invalid option, try --help" << endl; + exit(-1); + } +/* + for(int iarg=1; iargsetLayout(layoutTabs); + +//plot setup + myPlot = new qDrawPlot(dockWidgetPlot,myDet); cout<<"DockPlot ready"<setWidget(myPlot); + +//tabs setup + tabs = new MyTabWidget(this); + layoutTabs->addWidget(tabs); + + +// creating all the other tab widgets + tab_measurement = new qTabMeasurement (this, myDet,myPlot); cout<<"Measurement ready"<setFrameShape(QFrame::NoFrame); + } + // setting the tab widgets to the scrollareas + scroll[Measurement] ->setWidget(tab_measurement); + scroll[DataOutput] ->setWidget(tab_dataoutput); + scroll[Plot] ->setWidget(tab_plot); + scroll[Actions] ->setWidget(tab_actions); + scroll[Settings] ->setWidget(tab_settings); + scroll[Advanced] ->setWidget(tab_advanced); + scroll[Debugging] ->setWidget(tab_debugging); + scroll[Developer] ->setWidget(tab_developer); + // inserting all the tabs + tabs->insertTab(Measurement, scroll[Measurement], "Measurement"); + tabs->insertTab(DataOutput, scroll[DataOutput], "Data Output"); + tabs->insertTab(Plot, scroll[Plot], "Plot"); + tabs->insertTab(Actions, scroll[Actions], "Actions"); + tabs->insertTab(Settings, scroll[Settings], "Settings"); + tabs->insertTab(Advanced, scroll[Advanced], "Advanced"); + tabs->insertTab(Debugging, scroll[Debugging], "Debugging"); + tabs->insertTab(Developer, scroll[Developer], "Developer"); + //no scroll buttons this way + tabs->insertTab(Messages, tab_messages, "Messages"); + +//swap tabs so that messages is last tab + tabs->tabBar()->moveTab(tabs->indexOf(tab_measurement), Measurement); + tabs->tabBar()->moveTab(tabs->indexOf(tab_settings), Settings); + tabs->tabBar()->moveTab(tabs->indexOf(tab_dataoutput), DataOutput); + tabs->tabBar()->moveTab(tabs->indexOf(tab_plot), Plot); + tabs->tabBar()->moveTab(tabs->indexOf(tab_actions), Actions); + tabs->tabBar()->moveTab(tabs->indexOf(tab_advanced), Advanced); + tabs->tabBar()->moveTab(tabs->indexOf(tab_debugging), Debugging); + tabs->tabBar()->moveTab(tabs->indexOf(tab_developer), Developer); + tabs->tabBar()->moveTab(tabs->indexOf(tab_messages), Messages); + tabs->setCurrentIndex(Measurement); + +//other tab properties + // Default tab color + defaultTabColor = tabs->tabBar()->tabTextColor(DataOutput); + //Set the current tab(measurement) to blue as it is the current one + tabs->tabBar()->setTabTextColor(0,QColor(0,0,200,255)); + // increase the width so it uses all the empty space for the tab titles + tabs->tabBar()->setFixedWidth(width()+61); + + // mode setup - to set up the tabs initially as disabled, not in form so done here +#ifdef VERBOSE + cout << "Setting Debug Mode to 0\nSetting Expert Mode to 0\nSetting Developer Mode to " << isDeveloper << "\nSetting Dockable Mode to false\n" << endl; +#endif + tabs->setTabEnabled(Debugging,false); + tabs->setTabEnabled(Advanced,false); + tabs->setTabEnabled(Developer,isDeveloper); + actionLoadTrimbits->setVisible(false); + actionSaveTrimbits->setVisible(false); + actionLoadCalibration->setVisible(false); + actionSaveCalibration->setVisible(false); + + dockWidgetPlot->setFloating(false); + dockWidgetPlot->setFeatures(QDockWidget::NoDockWidgetFeatures); + +// Other setup + //Height of plot and central widget + heightPlotWindow = dockWidgetPlot->size().height(); + heightCentralWidget = centralwidget->size().height(); + // Default zoom Tool Tip + zoomToolTip = dockWidgetPlot->toolTip(); + + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::SetUpDetector(const string fName){ + + + //instantiate detector and set window title + myDet = new multiSlsDetector(detID); + + //create messages tab to capture config file loading logs + tab_messages = new qTabMessages (this); cout<<"Messages ready"<getHostname(); + qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); + + //if hostname doesnt exist even in shared memory + if(!host.length()){ + cout << endl << "No Detector Connected." << endl; + qDefs::Message(qDefs::CRITICAL,"No Detectors Connected. ","qDetectorMain::SetUpDetector"); + exit(-1); + } + + //check if the detector is not even connected + string offline = myDet->checkOnline(); + qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); + + if(!offline.empty()){ + qDefs::Message(qDefs::CRITICAL,string("The detector(s) ")+offline+string(" is/are not connected. Exiting GUI."),"qDetectorMain::SetUpDetector"); + cout << "The detector(s) " << host << " is/are not connected. Exiting GUI." << endl; + exit(-1); + } + + // Check if type valid. If not, exit + slsDetectorDefs::detectorType detType = myDet->getDetectorsType(); + qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); + + switch(detType){ + case slsDetectorDefs::MYTHEN: break; + case slsDetectorDefs::EIGER: break; + case slsDetectorDefs::GOTTHARD: + case slsDetectorDefs::AGIPD: + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::MOENCH: + case slsDetectorDefs::JUNGFRAU: + actionLoadTrimbits->setText("Load Settings"); actionSaveTrimbits->setText("Save Settings"); + break; + default: + string detName = myDet->slsDetectorBase::getDetectorType(detType); + qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); + cout << "ERROR: " + host + " has unknown detector type \"" + detName + "\". Exiting GUI." << endl; + string errorMess = host+string(" has unknown detector type \"")+ + detName+string("\". Exiting GUI."); + qDefs::Message(qDefs::CRITICAL,errorMess,"qDetectorMain::SetUpDetector"); + exit(-1); + } + setWindowTitle("SLS Detector GUI : "+ + QString(slsDetectorBase::getDetectorType(detType).c_str())+ " - "+QString(host.c_str())); +//#ifdef VERBOSE + cout << endl << "Type : " << slsDetectorBase::getDetectorType(detType) << "\nDetector : " << host << endl; +//#endif + myDet->setOnline(slsDetectorDefs::ONLINE_FLAG); + qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::Initialization(){ +// Dockable Plot + connect(dockWidgetPlot, SIGNAL(topLevelChanged(bool)), this,SLOT(ResizeMainWindow(bool))); +// tabs + connect(tabs, SIGNAL(currentChanged(int)), this, SLOT(Refresh(int)));//( QWidget*))); + // Measurement tab + connect(tab_measurement, SIGNAL(StartSignal()), this,SLOT(EnableTabs())); + connect(tab_measurement, SIGNAL(StopSignal()), myPlot,SLOT(StopAcquisition())); + connect(tab_measurement, SIGNAL(CheckPlotIntervalSignal()), tab_plot,SLOT(SetFrequency())); + // Data Output Tab + connect(tab_dataoutput, SIGNAL(AngularConversionSignal(bool)), tab_actions,SLOT(EnablePositions(bool))); + //enable scanbox( for angles) + connect(tab_dataoutput, SIGNAL(AngularConversionSignal(bool)), tab_plot,SLOT(EnableScanBox())); + // Plot tab + connect(tab_plot, SIGNAL(DisableZoomSignal(bool)), this,SLOT(SetZoomToolTip(bool))); + // Actions tab (only for scan) + connect(tab_actions, SIGNAL(EnableScanBox()), tab_plot,SLOT(EnableScanBox())); + //settings to advanced tab(int is always 0 to only refresh) + connect(tab_settings, SIGNAL(UpdateTrimbitSignal(int)), tab_advanced,SLOT(UpdateTrimbitPlot(int))); +// Plotting + // When the acquisition is finished, must update the meas tab + connect(myPlot, SIGNAL(UpdatingPlotFinished()), this, SLOT(EnableTabs())); + connect(myPlot, SIGNAL(UpdatingPlotFinished()), tab_measurement, SLOT(UpdateFinished())); + //This should not be called as it will change file name to measurement when run finished + //connect(myPlot, SIGNAL(UpdatingPlotFinished()), tab_plot, SLOT(Refresh())); + connect(myPlot, SIGNAL(SetCurrentMeasurementSignal(int)), tab_measurement, SLOT(SetCurrentMeasurement(int))); + + +// menubar + // Modes Menu + connect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); + // Utilities Menu + connect(menuUtilities, SIGNAL(triggered(QAction*)), this,SLOT(ExecuteUtilities(QAction*))); + // Help Menu + connect(menuHelp, SIGNAL(triggered(QAction*)), this,SLOT(ExecuteHelp(QAction*))); + + +//server + connect(myServer, SIGNAL(ServerStoppedSignal()), this,SLOT(UncheckServer())); +} + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::LoadConfigFile(const string fName){ +#ifdef VERBOSE + cout << "Loading config file at start up:" << fName << endl; +#endif + struct stat st_buf; + QString file = QString(fName.c_str()); + + //path doesnt exist + if(stat(fName.c_str(),&st_buf)) + qDefs::Message(qDefs::WARNING,string("Start up configuration failed to load. The following file does not exist:
")+fName,"qDetectorMain::LoadConfigFile"); + + //not a file + else if (!S_ISREG (st_buf.st_mode)) + qDefs::Message(qDefs::WARNING,string("Start up configuration failed to load. The following file is not a recognized file format:
")+fName,"qDetectorMain::LoadConfigFile"); + + else{ + //could not load config file + if(myDet->readConfigurationFile(fName)==slsDetectorDefs::FAIL) + qDefs::Message(qDefs::WARNING,string("Could not load all the Configuration Parameters from file:
")+fName,"qDetectorMain::LoadConfigFile"); + //successful + else + qDefs::Message(qDefs::INFORMATION,"
The Configuration Parameters have been loaded successfully at start up.","qDetectorMain::LoadConfigFile"); + + qDefs::checkErrorMessage(myDet,"qDetectorMain::LoadConfigFile"); + } +} + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::EnableModes(QAction *action){ + bool enable; + + //listen to gui client + if(action==actionListenGuiClient){ + + myServer->StartStopServer(actionListenGuiClient->isChecked()); + + //disconnect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); + //actionListenGuiClient->setChecked(myServer->StartStopServer(actionListenGuiClient->isChecked())); + //connect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); + } + //Set DebugMode + else if(action==actionDebug){ + enable = actionDebug->isChecked(); + tabs->setTabEnabled(Debugging,enable); +#ifdef VERBOSE + cout << "Setting Debug Mode to " << enable << endl; +#endif + } + + //Set ExpertMode(comes here only if its a digital detector) + else if(action==actionExpert){ + enable = actionExpert->isChecked(); + + tabs->setTabEnabled(Advanced,enable); + actionLoadTrimbits->setVisible(enable); + actionSaveTrimbits->setVisible(enable); + actionLoadCalibration->setVisible(enable); + actionSaveCalibration->setVisible(enable); + tab_measurement->SetExpertMode(enable); + tab_settings->SetExpertMode(enable); + tab_dataoutput->SetExpertMode(enable); +#ifdef VERBOSE + cout << "Setting Expert Mode to " << enable << endl; +#endif + } + + //Set DockableMode + else{ + enable = actionDockable->isChecked(); + if(enable) + dockWidgetPlot->setFeatures(QDockWidget::DockWidgetFloatable); + else{ + dockWidgetPlot->setFloating(false); + dockWidgetPlot->setFeatures(QDockWidget::NoDockWidgetFeatures); + } +#ifdef VERBOSE + cout << "Setting Dockable Mode to " << enable << endl; +#endif + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::ExecuteUtilities(QAction *action){ + bool refreshTabs = false; + if(action==actionOpenSetup){ +#ifdef VERBOSE + cout << "Loading Setup" << endl; +#endif + QString fName = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + fName = QFileDialog::getOpenFileName(this, + tr("Load Detector Setup"),fName, + tr("Detector Setup files (*.det);;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->retrieveDetectorSetup(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL){ + qDefs::Message(qDefs::INFORMATION,"The Setup Parameters have been loaded successfully.","qDetectorMain::ExecuteUtilities"); + refreshTabs=true; + }else qDefs::Message(qDefs::WARNING,string("Could not load the Setup Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + else if(action==actionSaveSetup){ +#ifdef VERBOSE + cout << "Saving Setup" << endl; +#endif + QString fName = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + fName = QFileDialog::getSaveFileName(this, + tr("Save Current Detector Setup"),fName, + tr("Detector Setup files (*.det);;All Files(*) ")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->dumpDetectorSetup(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Setup Parameters have been saved successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not save the Setup Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + else if(action==actionOpenConfiguration){ +#ifdef VERBOSE + cout << "Loading Configuration" << endl; +#endif + QString fName = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + fName = QFileDialog::getOpenFileName(this, + tr("Load Detector Configuration"),fName, + tr("Configuration files (*.config);;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->readConfigurationFile(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL){ + qDefs::Message(qDefs::INFORMATION,"The Configuration Parameters have been configured successfully.","qDetectorMain::ExecuteUtilities"); + refreshTabs=true; + }else qDefs::Message(qDefs::WARNING,string("Could not load all the Configuration Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + else if(action==actionSaveConfiguration){ +#ifdef VERBOSE + cout << "Saving Configuration" << endl; +#endif + QString fName = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + fName = QFileDialog::getSaveFileName(this, + tr("Save Current Detector Configuration"),fName, + tr("Configuration files (*.config) ;;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->writeConfigurationFile(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Configuration Parameters have been saved successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not save the Configuration Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + else if(action==actionLoadTrimbits){ + QString fName = QString(myDet->getSettingsDir()); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + //gotthard + if(actionLoadTrimbits->text().contains("Settings")){ +#ifdef VERBOSE + cout << "Loading Settings" << endl; +#endif + fName = QFileDialog::getOpenFileName(this, + tr("Load Detector Settings"),fName, + tr("Settings files (*.settings settings.sn*);;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->loadSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Settings have been loaded successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not load the Settings from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + + }//mythen and eiger + else{ +#ifdef VERBOSE + cout << "Loading Trimbits" << endl; +#endif + //so that even nonexisting files can be selected + QFileDialog *fileDialog = new QFileDialog(this, + tr("Load Detector Trimbits"),fName, + tr("Trimbit files (*.trim noise.sn*);;All Files(*)")); + fileDialog->setFileMode(QFileDialog::AnyFile ); + if ( fileDialog->exec() == QDialog::Accepted ) + fName = fileDialog->selectedFiles()[0]; + + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->loadSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Trimbits have been loaded successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not load the Trimbits from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + } + else if(action==actionSaveTrimbits){ + //gotthard + if(actionLoadTrimbits->text().contains("Settings")){ +#ifdef VERBOSE + cout << "Saving Settings" << endl; +#endif + //different output directory so as not to overwrite + QString fName = QString(myDet->getSettingsDir()); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + fName = QFileDialog::getSaveFileName(this, + tr("Save Current Detector Settings"),fName, + tr("Settings files (*.settings settings.sn*);;All Files(*) ")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->saveSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Settings have been saved successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not save the Settings to file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + }//mythen and eiger + else{ +#ifdef VERBOSE + cout << "Saving Trimbits" << endl; +#endif//different output directory so as not to overwrite + QString fName = QString(myDet->getSettingsDir()); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + fName = QFileDialog::getSaveFileName(this, + tr("Save Current Detector Trimbits"),fName, + tr("Trimbit files (*.trim noise.sn*) ;;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->saveSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Trimbits have been saved successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not save the Trimbits to file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + } + else if(action==actionLoadCalibration){ +#ifdef VERBOSE + cout << "Loading Calibration Data" << endl; +#endif + QString fName = QString(myDet->getCalDir()); + qDefs::checkErrorMessage(myDet); + + //so that even nonexisting files can be selected + QFileDialog *fileDialog = new QFileDialog(this, + tr("Load Detector Calibration Data"),fName, + tr("Calibration files (*.cal calibration.sn*);;All Files(*)")); + fileDialog->setFileMode(QFileDialog::AnyFile ); + if ( fileDialog->exec() == QDialog::Accepted ) + fName = fileDialog->selectedFiles()[0]; + + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->loadCalibrationFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Calibration Data have been loaded successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not load the Calibration data from file:\n")+ fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + else if(action==actionSaveCalibration){ +#ifdef VERBOSE + cout << "Saving Calibration Data" << endl; +#endif//different output directory so as not to overwrite + QString fName = QString(myDet->getCalDir()); + qDefs::checkErrorMessage(myDet); + fName = QFileDialog::getSaveFileName(this, + tr("Save Current Detector Calibration Data"),fName, + tr("Calibration files (*.cal calibration.sn*);;All Files(*) ")); + // Gets called when cancelled as well + if (!fName.isEmpty()){ + if(myDet->saveCalibrationFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) + qDefs::Message(qDefs::INFORMATION,"The Calibration Data have been saved successfully.","qDetectorMain::ExecuteUtilities"); + else qDefs::Message(qDefs::WARNING,string("Could not save the Calibration data to file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); + } + } + + Refresh(tabs->currentIndex()); + if(refreshTabs){ + tab_actions->Refresh(); + tab_measurement->Refresh(); + tab_settings->Refresh(); + tab_dataoutput->Refresh(); + if(tab_advanced->isEnabled()) tab_advanced->Refresh(); + if(tab_debugging->isEnabled()) tab_debugging->Refresh(); + if(tab_developer->isEnabled()) tab_developer->Refresh(); + + tab_plot->Refresh(); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::ExecuteHelp(QAction *action){ + if(action==actionAbout){ +#ifdef VERBOSE + cout << "About: Common GUI for Mythen, Eiger, Gotthard, Jungfrau, Moench and Propix detectors" << endl; +#endif + char version[200]; + int64_t retval= SVNREV; + retval= (retval <<32) | SVNDATE; + sprintf(version,"%llx",retval); + string thisGUIVersion = string(version); + + sprintf(version,"%llx",myDet->getId(slsDetectorDefs::THIS_SOFTWARE_VERSION)); + qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteHelp"); + string thisClientVersion = string(version); + + //

A heading

+ qDefs::Message(qDefs::INFORMATION,"

" + "SLS Detector GUI version:   " + thisGUIVersion+"
" + "SLS Detector Client version: "+thisClientVersion+"

" + "Common GUI to control the SLS Detectors: " + "Mythen, Eiger, Gotthard, Jungfrau, Moench and Propix.

" + "It can be operated in parallel with the command line interface:
" + "sls_detector_put,
sls_detector_get,
sls_detector_acquire and
sls_detector_help.

" + "The GUI Software is still in progress. " + "Please report bugs to dhanya.maliakal@psi.ch or anna.bergamaschi@psi.ch.<\\p>","qDetectorMain::ExecuteHelp"); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::Refresh(int index){ + myDet->setOnline(slsDetectorDefs::ONLINE_FLAG); + myDet->setReceiverOnline(slsDetectorDefs::ONLINE_FLAG); + qDefs::checkErrorMessage(myDet,"qDetectorMain::Refresh"); + if(!tabs->isTabEnabled(index)) + tabs->setCurrentIndex((index++)<(tabs->count()-1)?index:Measurement); + else{ + switch(tabs->currentIndex()){ + case Measurement: tab_measurement->Refresh(); break; + case Settings: tab_settings->Refresh(); break; + case DataOutput: tab_dataoutput->Refresh(); break; + case Plot: tab_plot->Refresh(); break; + case Actions: tab_actions->Refresh(); break; + case Advanced: tab_advanced->Refresh(); break; + case Debugging: tab_debugging->Refresh(); break; + case Developer: tab_developer->Refresh(); break; + case Messages: break; + } + } + for(int i=0;itabBar()->setTabTextColor(i,defaultTabColor); + tabs->tabBar()->setTabTextColor(index,QColor(0,0,200,255)); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::ResizeMainWindow(bool b){ +#ifdef VERBOSE + cout << "Resizing Main Window: height:" << height() << endl; +#endif + // undocked from the main window + if(b){ + // sets the main window height to a smaller maximum to get rid of space + setMaximumHeight(height()-heightPlotWindow-9); + dockWidgetPlot->setMinimumHeight(0); + cout << "undocking it from main window" << endl; + } + else{ + setMaximumHeight(QWIDGETSIZE_MAX); + // the minimum for plot will be set when the widget gets resized automatically + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::resizeEvent(QResizeEvent* event){ + if(!dockWidgetPlot->isFloating()){ + if(tabs->currentIndex()== Actions){ + dockWidgetPlot->setMinimumHeight(heightPlotWindow-100); + centralwidget->setMaximumHeight(QWIDGETSIZE_MAX); + + } + else{ + dockWidgetPlot->setMinimumHeight(height()-centralwidget->height()-50); + centralwidget->setMaximumHeight(heightCentralWidget); + } + } + + //adjusting tab width + if(width()>=800){ tabs->tabBar()->setFixedWidth(width()+61);} + else { tabs->tabBar()->setMinimumWidth(0); + tabs->tabBar()->setExpanding(true); + tabs->tabBar()->setUsesScrollButtons(true); + } + + event->accept(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::EnableTabs(){ +#ifdef VERBOSE + cout << "Entering EnableTabs function" << endl; +#endif + + + bool enable; + enable=!(tabs->isTabEnabled(DataOutput)); + + + // or use the Enable/Disable button + // normal tabs + tabs->setTabEnabled(DataOutput,enable); + tabs->setTabEnabled(Actions,enable); + tabs->setTabEnabled(Settings,enable); + tabs->setTabEnabled(Messages,enable); + + //actions check + actionOpenSetup->setEnabled(enable); + actionSaveSetup->setEnabled(enable); + actionOpenConfiguration->setEnabled(enable); + actionSaveConfiguration->setEnabled(enable); + actionMeasurementWizard->setEnabled(enable); + actionDebug->setEnabled(enable); + actionExpert->setEnabled(enable); + + + // special tabs + tabs->setTabEnabled(Debugging,enable && (actionDebug->isChecked())); + tabs->setTabEnabled(Developer,enable && isDeveloper); + //expert + bool expertTab = enable && (actionExpert->isChecked()); + tabs->setTabEnabled(Advanced,expertTab); + actionLoadTrimbits->setVisible(expertTab); + actionSaveTrimbits->setVisible(expertTab); + actionLoadCalibration->setVisible(expertTab); + actionSaveCalibration->setVisible(expertTab); + + + //moved to here, so that its all in order, instead of signals and different threads + if(!enable) { + myDet->setOnline(slsDetectorDefs::ONLINE_FLAG); + myDet->setReceiverOnline(slsDetectorDefs::ONLINE_FLAG); + qDefs::checkErrorMessage(myDet,"qDetectorMain::EnableTabs"); + //refresh all the required tabs + tab_actions->Refresh();// angular, positions, + + //too slow to refresh + /*tab_measurement->Refresh();*/ + + tab_settings->Refresh(); + tab_dataoutput->Refresh(); + if(tab_advanced->isEnabled()) tab_advanced->Refresh(); + if(tab_debugging->isEnabled()) tab_debugging->Refresh(); + if(tab_developer->isEnabled()) tab_developer->Refresh(); + + tab_plot->Refresh(); + + //stop the adc timer in gotthard + if(isDeveloper) + tab_developer->StopADCTimer(); + //set the plot type first(acccss shared memory) + tab_plot->SetScanArgument(); + //sets running to true + myPlot->StartStopDaqToggle(); + } + else{//to enable scan box + tab_plot->Refresh(); + //to start adc timer + if(tab_developer->isEnabled()) + tab_developer->Refresh(); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::SetZoomToolTip(bool disable){ + if(disable) + dockWidgetPlot->setToolTip("To Enable mouse-controlled zooming capabilities,\ndisable min and max for all axes. "); + else + dockWidgetPlot->setToolTip(zoomToolTip); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDetectorMain::StartStopAcquisitionFromClient(bool start){ +#ifdef VERBOSE + cout << "Start/Stop Acquisition From Client:" << start << endl; +#endif + + if (tab_measurement->GetStartStatus() != start){ + if(start){ + if(!myPlot->isRunning()){ + //refresh all the required tabs - all these are done in button click anyway + /* tab_actions->Refresh(); + //too slow to refresh + //tab_measurement->Refresh(); + tab_settings->Refresh(); + tab_dataoutput->Refresh(); + if(tab_advanced->isEnabled()) tab_advanced->Refresh(); + if(tab_debugging->isEnabled()) tab_debugging->Refresh(); + if(tab_developer->isEnabled()) tab_developer->Refresh(); + + tab_plot->Refresh();*/ + } + } + //click start/stop + tab_measurement->ClickStartStop(); + while(myPlot->GetClientInitiated()); + } + + return slsDetectorDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDetectorMain::UncheckServer(){ +#ifdef VERBOSE + cout << "Unchecking Mode : Listen to Gui Client" << endl; +#endif + disconnect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); + actionListenGuiClient->setChecked(false); + connect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +bool qDetectorMain::isCurrentlyTabDeveloper(){ + return (tabs->currentIndex()==Developer); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qDrawPlot.cpp b/slsDetectorGui/src/qDrawPlot.cpp new file mode 100644 index 0000000000..2db6f10588 --- /dev/null +++ b/slsDetectorGui/src/qDrawPlot.cpp @@ -0,0 +1,2057 @@ +/* + * qDrawPlot.cpp + * + * Created on: May 7, 2012 + * Author: Dhanya Maliakal + */ +// Qt Project Class Headers +#include "qDrawPlot.h" +#include "qCloneWidget.h" +#include "slsDetector.h" +#include"fileIOStatic.h" +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +#include "postProcessing.h" +// Qt Include Headers +#include +#include +#include +#include +//#include "qwt_double_interval.h" +#include "qwt_series_data.h" +// C++ Include Headers +#include +#include +#include +using namespace std; + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +const double qDrawPlot::PLOT_TIMER_MS = 200; + +qDrawPlot::qDrawPlot(QWidget *parent,multiSlsDetector*& detector): + QWidget(parent),myDet(detector),plot1D_hists(0){ + SetupWidgetWindow(); + Initialization(); + StartStopDaqToggle(); //as default +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qDrawPlot::~qDrawPlot(){ + // Clear plot + Clear1DPlot(); + for(QVector::iterator h = plot1D_hists.begin();h!=plot1D_hists.end();h++) delete *h; + plot1D_hists.clear(); + if(lastImageArray) delete[] lastImageArray; lastImageArray=0; + StartOrStopThread(0); + delete myDet; myDet = 0; + for(int i=0;igetDetectorsType(); + switch(detType){ + case slsDetectorDefs::MYTHEN: originally2D = false; break; + case slsDetectorDefs::EIGER: originally2D = true; break; + case slsDetectorDefs::GOTTHARD: originally2D = false; break; + case slsDetectorDefs::PROPIX: originally2D = true; break; + case slsDetectorDefs::MOENCH: originally2D = true; break; + case slsDetectorDefs::JUNGFRAU: originally2D = true; break; + default: + cout << "ERROR: Detector Type is Generic" << endl; + exit(-1); + } + + +//initialization + data_pause_over = true; + + currentMeasurement = 0; + currentFrame = 0; + numFactor = 0; + currentScanDivLevel = 0; + currentScanValue = 0; + number_of_exposures = 0; + number_of_frames = 0; + acquisitionPeriod = 0; + exposureTime = 0; + currentFileIndex = 0; + currentFrameIndex = 0; + + stop_signal = 0; + pthread_mutex_init(&last_image_complete_mutex,NULL); + + // Default titles- only for the initial picture + imageXAxisTitle="Pixel"; + imageYAxisTitle="Pixel"; + imageZAxisTitle="Intensity"; + histXAxisTitle="Channel Number"; + histYAxisTitle="Counts"; + for(int i=0;igetTotalNumberOfChannels(slsDetectorDefs::X); cout<<"nPixelsX:"<getTotalNumberOfChannels(slsDetectorDefs::Y); cout<<"nPixelsY:"<setStyle(QwtSymbol::Cross); + marker->setSize(5,5); + noMarker = new QwtSymbol(); + + //for save automatically, + saveAll = false; + saveError = false; + lastSavedFrame = -1; + lastSavedMeasurement = -1; + + // This is so that it initially stop and plots + running = 1; + + XYRangeChanged = false; + XYRangeValues[0] = 0; + XYRangeValues[1] = 0; + XYRangeValues[2] = 0; + XYRangeValues[3] = 0; + IsXYRange[0] = false; + IsXYRange[1] = false; + IsXYRange[2] = false; + IsXYRange[3] = false; + + timerValue = PLOT_TIMER_MS; + frameFactor=0; + isFrameEnabled = false; + isTriggerEnabled = false; + + scanArgument = qDefs::None; + histogramArgument = qDefs::Intensity; + anglePlot = false; + alreadyDisplayed = false; + + //filepath and file name + filePath = QString(myDet->getFilePath().c_str()); + fileName = QString(myDet->getFileName().c_str()); + + backwardScanPlot = false; + fileSaveEnable= myDet->enableWriteToFile(); + + //pedestal + pedestal = false; + pedestalVals = 0; + tempPedestalVals = 0; + pedestalCount = 0; + startPedestalCal = false; + + //accumulate + accumulate = false; + resetAccumulate = false; + + clientInitiated = false; + + //binary plot output + binary = false; + binaryFrom = 0; + binaryTo = 0; + + //histogram + histogram = false; + histFrom = 0; + histTo = 0; + histSize = 0; + /* + grid = new QwtPlotGrid; + grid->enableXMin(true); + grid->enableYMin(true); + grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine)); + grid->setMinPen(QPen(Qt::gray, 0 , Qt::DotLine)); + */ + plotHistogram = new QwtPlotHistogram(); + plotHistogram->setStyle(QwtPlotHistogram::Columns);//Options:Outline,Columns, Lines + + + plotRequired = false; + +//widget related initialization + + // clone + for(int i=0;isetLayout(layout); + + histFrameIndexTitle= histFrameIndexTitle = new QLabel(""); + + boxPlot = new QGroupBox(""); + layout->addWidget(boxPlot,1,0); + boxPlot->setAlignment(Qt::AlignHCenter); + boxPlot->setFont(QFont("Sans Serif",11,QFont::Normal)); + boxPlot->setTitle("Sample Plot"); + data_pause_timer = new QTimer(this); + connect(data_pause_timer, SIGNAL(timeout()), this, SLOT(UpdatePause())); + + + //display statistics + displayStatistics = false; + widgetStatistics = new QWidget(this); + widgetStatistics->setFixedHeight(15); + QHBoxLayout *hl1 = new QHBoxLayout; + hl1->setSpacing(0); + hl1->setContentsMargins(0, 0, 0, 0); + QLabel *lblMin = new QLabel("Min: "); + lblMin->setFixedWidth(40); + lblMin->setAlignment(Qt::AlignRight); + QLabel *lblMax = new QLabel("Max: "); + lblMax->setFixedWidth(40); + lblMax->setAlignment(Qt::AlignRight); + QLabel *lblSum = new QLabel("Sum: "); + lblSum->setFixedWidth(40); + lblSum->setAlignment(Qt::AlignRight); + lblMinDisp = new QLabel("-"); + lblMinDisp->setAlignment(Qt::AlignLeft); + lblMaxDisp = new QLabel("-"); + lblMaxDisp->setAlignment(Qt::AlignLeft); + lblSumDisp = new QLabel("-"); + lblSumDisp->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed); + lblSumDisp->setAlignment(Qt::AlignLeft); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + hl1->addWidget(lblMin); + hl1->addWidget(lblMinDisp); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); + hl1->addWidget(lblMax); + hl1->addWidget(lblMaxDisp); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); + hl1->addWidget(lblSum); + hl1->addWidget(lblSumDisp); + hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + widgetStatistics->setLayout(hl1); + layout->addWidget(widgetStatistics,2,0); + widgetStatistics->hide(); + + + // setting default plot titles and settings + plot1D = new SlsQt1DPlot(boxPlot); + + plot1D->setFont(QFont("Sans Serif",9,QFont::Normal)); + plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); + plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); + plot1D->hide(); + + SlsQtH1D* h; + histNBins = nPixelsX; + nHists = 1; + if(histXAxis) delete [] histXAxis; histXAxis = new double [nPixelsX]; + if(histYAxis[0]) delete [] histYAxis[0];histYAxis[0] = new double [nPixelsX]; + for(unsigned int px=0;px<(int)nPixelsX;px++) {histXAxis[px] = px;histYAxis[0][px] = 0;} + Clear1DPlot(); + plot1D->SetXTitle("X Axis"); + plot1D->SetYTitle("Y Axis"); + plot1D_hists.append(h=new SlsQtH1D("",histNBins,histXAxis,histYAxis[0])); + h->SetLineColor(0); + SetStyle(h); + h->Attach(plot1D); + Clear1DPlot(); + + plot2D = new SlsQt2DPlotLayout(boxPlot); + //default plot + lastImageArray = new double[nPixelsY*nPixelsX]; + for(unsigned int px=0;pxsetFont(QFont("Sans Serif",9,QFont::Normal)); + plot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,lastImageArray); + plot2D->setTitle(GetImageTitle()); + plot2D->SetXTitle(imageXAxisTitle); + plot2D->SetYTitle(imageYAxisTitle); + plot2D->SetZTitle(imageZAxisTitle); + plot2D->setAlignment(Qt::AlignLeft); + boxPlot->setFlat(true); + boxPlot->setContentsMargins(0,15,0,0); + + plotLayout = new QGridLayout(boxPlot); + plotLayout->setContentsMargins(0,0,0,0); + plotLayout->addWidget(plot1D,0,0,1,1); + plotLayout->addWidget(plot2D,0,0,1,1); + + +//callbacks + + // Setting the callback function to get data from detector class + myDet->registerDataCallback(&(GetDataCallBack),this); + //Setting the callback function to alert when acquisition finished from detector class + myDet->registerAcquisitionFinishedCallback(&(GetAcquisitionFinishedCallBack),this); + //Setting the callback function to alert when each measurement finished from detector class + myDet->registerMeasurementFinishedCallback(&(GetMeasurementFinishedCallBack),this); + //Setting the callback function to get progress from detector class(using receivers) + myDet->registerProgressCallback(&(GetProgressCallBack),this); + //stream data from receiver to the gui + if(detType != slsDetectorDefs::MYTHEN) + myDet->enableDataStreamingFromReceiver(1); + + + qDefs::checkErrorMessage(myDet,"qDrawPlot::SetupWidgetWindow"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::Initialization(){ + connect(this, SIGNAL(UpdatePlotSignal()), this, SLOT(UpdatePlot())); + connect(this, SIGNAL(InterpolateSignal(bool)),plot2D, SIGNAL(InterpolateSignal(bool))); + connect(this, SIGNAL(ContourSignal(bool)), plot2D, SIGNAL(ContourSignal(bool))); + connect(this, SIGNAL(LogzSignal(bool)), plot2D, SLOT(SetZScaleToLog(bool))); + connect(this, SIGNAL(LogySignal(bool)), plot1D, SLOT(SetLogY(bool))); + connect(this, SIGNAL(ResetZMinZMaxSignal(bool,bool,double,double)),plot2D, SLOT(ResetZMinZMax(bool,bool,double,double))); + + connect(this, SIGNAL(SetZRangeSignal(double,double)), plot2D, SLOT(SetZRange(double,double))); + + connect(this, SIGNAL(AcquisitionErrorSignal(QString)), this, SLOT(ShowAcquisitionErrorMessage(QString))); + + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::StartStopDaqToggle(bool stop_if_running){ +#ifdef VERYVERBOSE + cout << "Entering StartStopDaqToggle(" << stop_if_running << ")" <setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); + int numTriggers = (isTriggerEnabled)*((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); + numFrames = ((numFrames==0)?1:numFrames); + numTriggers = ((numTriggers==0)?1:numTriggers); + number_of_frames = numFrames * numTriggers; + cout << "\tNumber of Frames per Scan/Measurement:" << number_of_frames << endl; + //get #scansets for level 0 and level 1 + int numScan0 = myDet->getScanSteps(0); numScan0 = ((numScan0==0)?1:numScan0); + int numScan1 = myDet->getScanSteps(1); numScan1 = ((numScan1==0)?1:numScan1); + int numPos=myDet->getPositions(); + + number_of_exposures = number_of_frames * numScan0 * numScan1; + if(anglePlot) number_of_exposures = numScan0 * numScan1;// * numPos; + cout << "\tNumber of Exposures Per Measurement:" << number_of_exposures << endl; + */ + + // ExposureTime + exposureTime= ((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1))*1E-9); + cout << "\tExposure Time:" << setprecision (10) << exposureTime << endl; + // Acquisition Period + acquisitionPeriod= ((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1))*1E-9); + cout << "\tAcquisition Period:" << setprecision (10) << acquisitionPeriod << endl; + cout << "\tFile Index:" << myDet->getFileIndex() << endl; + //to take the first data if frameFactor + numFactor = 0; + + //for save automatically, + saveError = false; + lastSavedFrame = -1; + lastSavedMeasurement = -1; + + //update file path and file name + filePath = QString(myDet->getFilePath().c_str()); + fileName = QString(myDet->getFileName().c_str()); + //update index + currentFileIndex = myDet->getFileIndex(); + currentFrameIndex = 0; + + StartDaq(true); + running=!running; + + qDefs::checkErrorMessage(myDet,"qDrawPlot::StartStopDaqToggle"); + } + + /** if this is set during client initation */ + clientInitiated = false; + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::StartDaq(bool start){ + if(start){ +#ifdef VERBOSE + cout << "Start Daq(true) function" << endl; +#endif + ResetDaqForGui(); + StartDaqForGui(); + }else{ +#ifdef VERBOSE + cout << "Start Daq(false) function" << endl; +#endif + StopDaqForGui(); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::ResetDaqForGui(){ + if(!StopDaqForGui()) return 0; + cout << "Resetting image number" << endl; + lastImageNumber = 0; + return 1; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +bool qDrawPlot::StartOrStopThread(bool start){ +#ifdef VERYVERBOSE + cout << "StartOrStopThread:" << start << endl; +#endif + static bool firstTime = true; + static bool gui_acquisition_thread_running = 0; + static pthread_t gui_acquisition_thread; + static pthread_mutex_t gui_acquisition_start_stop_mutex = PTHREAD_MUTEX_INITIALIZER; + + pthread_mutex_lock(&gui_acquisition_start_stop_mutex); + //stop part, before start or restart + if(gui_acquisition_thread_running){ + cout << "Stopping current acquisition thread ...." << endl; + stop_signal = 1;//sorta useless right now + gui_acquisition_thread_running = 0; + } + + //start part + if(start){ + progress = 0; + //sets up the measurement parameters + SetupMeasurement(); + + //refixing all the zooming + plot2D->GetPlot()->SetXMinMax(-0.5,nPixelsX+0.5); + plot2D->GetPlot()->SetYMinMax(startPixel,endPixel); + plot2D->GetPlot()->SetZoom(-0.5,startPixel,nPixelsX,endPixel-startPixel); + plot2D->GetPlot()->UnZoom(); + /*XYRangeChanged = true;*/ + boxPlot->setTitle("Old_Plot.raw"); + + cout << "Starting new acquisition thread ...." << endl; + // Start acquiring data from server + if(!firstTime) pthread_join(gui_acquisition_thread,NULL);//wait until he's finished, ie. exits + pthread_create(&gui_acquisition_thread, NULL,DataStartAcquireThread, (void*) this); + // This is set here and later reset to zero when all the plotting is done + // This is manually done instead of keeping track of thread because + // this thread returns immediately after executing the acquire command + gui_acquisition_thread_running=1; + cout << "Started acquiring threaddd:" << endl; + } + pthread_mutex_unlock(&gui_acquisition_start_stop_mutex); + return gui_acquisition_thread_running; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SetScanArgument(int scanArg){ +#ifdef VERYVERBOSE + cout << "SetScanArgument function:" << scanArg << " running:" << running << endl; +#endif + scanArgument = scanArg; + + LockLastImageArray(); + + if(plot_in_scope==1) Clear1DPlot(); + + + // Number of Exposures - must be calculated here to get npixelsy for allframes/frameindex scans + int numFrames = (isFrameEnabled)*((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); + int numTriggers = (isTriggerEnabled)*((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); + numFrames = ((numFrames==0)?1:numFrames); + numTriggers = ((numTriggers==0)?1:numTriggers); + number_of_frames = numFrames * numTriggers; + cout << "\tNumber of Frames per Scan/Measurement:" << number_of_frames << endl; + //get #scansets for level 0 and level 1 + int numScan0 = myDet->getScanSteps(0); numScan0 = ((numScan0==0)?1:numScan0); + int numScan1 = myDet->getScanSteps(1); numScan1 = ((numScan1==0)?1:numScan1); + int numPos=myDet->getPositions(); + + number_of_exposures = number_of_frames * numScan0 * numScan1; + if(anglePlot) number_of_exposures = numScan0 * numScan1;// * numPos; + cout << "\tNumber of Exposures Per Measurement:" << number_of_exposures << endl; + + + maxPixelsY = 0; + minPixelsY = 0; + nPixelsX = myDet->getTotalNumberOfChannels(slsDetectorDefs::X); + nPixelsY = myDet->getTotalNumberOfChannels(slsDetectorDefs::Y); + //cannot do this in between measurements , so update instantly + if(scanArgument==qDefs::Level0){ + //no need to check if numsteps=0,cuz otherwise this mode wont be set in plot tab + int numSteps = myDet->getScanSteps(0); + double *values = new double[numSteps]; + myDet->getScanSteps(0,values); + + maxPixelsY = values[numSteps-1]; + minPixelsY = values[0]; + nPixelsY = numSteps; + }else if(scanArgument==qDefs::Level1) { + //no need to check if numsteps=0,cuz otherwise this mode wont be set in plot tab + int numSteps = myDet->getScanSteps(1); + double *values = new double[numSteps]; + myDet->getScanSteps(1,values); + + maxPixelsY = values[numSteps-1]; + minPixelsY = values[0]; + nPixelsY = numSteps; + }else if(scanArgument==qDefs::AllFrames) + nPixelsY = number_of_exposures; + else if(scanArgument==qDefs::FileIndex) + nPixelsY = number_of_frames; + + + if(minPixelsY>maxPixelsY){ + double temp = minPixelsY; + minPixelsY = maxPixelsY; + maxPixelsY = temp; + backwardScanPlot = true; + }else backwardScanPlot = false; + + + //1d + if(histXAxis) delete [] histXAxis; histXAxis = new double [nPixelsX]; + + if(histYAxis[0]) delete [] histYAxis[0]; histYAxis[0] = new double [nPixelsX]; + + //2d + if(lastImageArray) delete [] lastImageArray; lastImageArray = new double[nPixelsY*nPixelsX]; + + //initializing 1d x axis + for(unsigned int px=0;px<(int)nPixelsX;px++) histXAxis[px] = px;/*+10;*/ + + //initializing 2d array + for(int py=0;py<(int)nPixelsY;py++) + for(int px=0;px<(int)nPixelsX;px++) + lastImageArray[py*nPixelsX+px] = 0; + + + //histogram + if(histogram){ + int iloop = 0; + int numSteps = ((histTo-histFrom)/(histSize)) + 1;cout<<"numSteps:"<myDet->acquire(1); + return this_pointer; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::GetDataCallBack(detectorData *data, int fIndex, int subIndex, void *this_pointer){ + ((qDrawPlot*)this_pointer)->GetData(data,fIndex, subIndex); + return 0; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::GetData(detectorData *data,int fIndex, int subIndex){ +#ifdef VERYVERBOSE + cout << "******Entering GetDatafunction********" << endl; + cout << "fIndex " << fIndex << endl; + cout << "subIndex " << subIndex << endl; + cout << "fname " << data->fileName << endl; + cout << "npoints " << data->npoints << endl; + cout << "npy " << data->npy << endl; + cout << "npy " << data->progressIndex << endl; + cout << "values " << data->values << endl; + cout << "errors " << data->errors << endl; + cout << "angle " << data->angles << endl; +#endif + if(!stop_signal){ + + //set progress + progress=(int)data->progressIndex; + currentFrameIndex = fileIOStatic::getIndicesFromFileName(string(data->fileName),currentFileIndex); + //happens if receiver sends a null and empty file name + if(string(data->fileName).empty()){ + cout << "Received empty file name. Exiting function without updating data for plot." << endl; + return -1; + } +#ifdef VERYVERBOSE + cout << "progress:" << progress << endl; +#endif + // secondary title necessary to differentiate between frames when not saving data + char temp_title[2000]; + //findex is the frame index given by receiver, cannot be derived from file name + if(fIndex!=-1){ + currentFrameIndex=fIndex; + sprintf(temp_title,"#%d",fIndex); + if((detType==slsDetectorDefs::EIGER) && (subIndex != -1)) + sprintf(temp_title,"#%d %d",fIndex,subIndex); + }else{ + if(fileSaveEnable) strcpy(temp_title,"#%d"); + else sprintf(temp_title,"",currentFrame); + } + if(subIndex != -1) + sprintf(temp_title,"#%d %d",fIndex,subIndex); + + //Plot Disabled + if(!plotEnable) + return 0; + + + //angle plotting + if(anglePlot){ + LockLastImageArray(); + //set title + plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); + // Title + histTitle[0] = temp_title; + + if(data->angles==NULL){ + cout<<"\n\nWARNING:RETURNED NULL instead of angles."<values,nAnglePixelsX*sizeof(double)); + SetHistXAxisTitle("Channel Number"); + + } + else{ + lastImageNumber= currentFrame+1; + nAnglePixelsX = data->npoints; + histNBins = nAnglePixelsX; + nHists=1; + if(histXAngleAxis) delete [] histXAngleAxis; histXAngleAxis = new double[nAnglePixelsX]; + if(histYAngleAxis) delete [] histYAngleAxis; histYAngleAxis = new double[nAnglePixelsX]; +#ifdef CHECKINFERROR + int k = 0; + for(int i = 0; i < data->npoints; i++){ + if(isinf(data->values[i])){ + //cout << "*** ERROR: value at " << i << " infinity" << endl; + k++; + data->values[i] = -1; + } + } + if (k>0) { + cout << "*** ERROR: value at " << k << " places have infinity values!" << endl; + double m1,m2,s1; + GetStatistics(m1,m2,s1,data->angles,nAnglePixelsX); + cout << "angle min:" << m1 << endl; + cout << "angle max:" << m2 << endl; + cout << "angle sum:" << s1 << endl; + GetStatistics(m1,m2,s1,data->values,nAnglePixelsX); + cout << "value min:" << m1 << endl; + cout << "value max:" << m2 << endl; + cout << "value sum:" << s1 << endl; + } +#endif + memcpy(histXAngleAxis,data->angles,nAnglePixelsX*sizeof(double)); + memcpy(histYAngleAxis,data->values,nAnglePixelsX*sizeof(double)); + SetHistXAxisTitle("Angles"); + } + UnlockLastImageArray(); + currentFrame++; +#ifdef VERYVERBOSE + cout << "Exiting GetData Function " << endl; +#endif + emit UpdatePlotSignal(); + plotRequired = true; + return 0; + } + + + //nth frame or delay decision (data copied later on) + if (detType == slsDetectorDefs::MYTHEN){ + //Nth Frame + if(frameFactor){ + //plots if numfactor becomes 0 + if(!numFactor) numFactor=frameFactor-1; + //return if not + else{ + numFactor--; + return 0; + } + } + + //Not Nth Frame, to check time out(NOT for Scans and angle plots) + else{ + if (scanArgument == qDefs::None) { + //if the time is not over, RETURN + if(!data_pause_over){ + return 0; + } + data_pause_over=false; + data_pause_timer->start((int)(timerValue)); + } + } + } + + + //if scan + //alframes + if(scanArgument==qDefs::AllFrames){ + LockLastImageArray(); + //set title + plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); + //variables + lastImageNumber= currentFrame+1; + //title + imageTitle = temp_title; + //copy data + memcpy(lastImageArray+(currentScanDivLevel*nPixelsX),data->values,nPixelsX*sizeof(double)); + UnlockLastImageArray(); + currentFrame++; + currentScanDivLevel++; + emit UpdatePlotSignal(); + plotRequired = true; + return 0; + } + //file index + if(scanArgument==qDefs::FileIndex){ + LockLastImageArray(); + //set title + plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); + //variables + if(currentFrameIndex == 0) currentScanDivLevel = 0; + lastImageNumber= currentFrame+1; + //title + imageTitle = temp_title; + //copy data + for(unsigned int px=0;pxvalues[px]; + UnlockLastImageArray(); + currentFrame++; + currentScanDivLevel++; + emit UpdatePlotSignal(); + plotRequired = true; + return 0; + } + //level0 + if(scanArgument==qDefs::Level0){ + LockLastImageArray(); + //set title + plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); + //get scanvariable0 + int ci = 0, fi = 0, p = 0, di = 0; double cs0 = 0 , cs1 = 0; + fileIOStatic::getVariablesFromFileName(string(data->fileName), ci, fi, p, cs0, cs1, di); + //variables + if(cs0!=currentScanValue) { + if(backwardScanPlot) currentScanDivLevel--; + else currentScanDivLevel++; + } + currentScanValue = cs0; + lastImageNumber= currentFrame+1; + //title + imageTitle = temp_title; + //copy data + for(unsigned int px=0;pxvalues[px]; + UnlockLastImageArray(); + currentFrame++; + emit UpdatePlotSignal(); + plotRequired = true; + return 0; + } + //level1 + if(scanArgument==qDefs::Level1){ + LockLastImageArray(); + //set title + plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); + //get scanvariable1 + int ci = 0, fi = 0, p = 0, di = 0; double cs0 = 0 , cs1 = 0; + fileIOStatic::getVariablesFromFileName(string(data->fileName), ci, fi, p, cs0, cs1, di); + //variables + if(cs1!=currentScanValue){ + if(backwardScanPlot) currentScanDivLevel--; + else currentScanDivLevel++; + } + currentScanValue = cs1; + lastImageNumber= currentFrame+1; + //title + imageTitle = temp_title; + //copy data + for(unsigned int px=0;pxvalues[px]; + UnlockLastImageArray(); + currentFrame++; + emit UpdatePlotSignal(); + plotRequired = true; + return 0; + } + + + + //normal measurement or 1d scans + LockLastImageArray(); + /*if(!pthread_mutex_trylock(&(last_image_complete_mutex))){*/ + //set title + plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); + // only if you got the lock, do u need to remember lastimagenumber to plot + lastImageNumber= currentFrame+1; + //cout<<"got last imagenumber:"<values[i] < histFrom) || (data->values[i] > histTo)) + continue; + //check for intervals, increment if validates + for(int j=0;jvalues[i])) + histogramSamples[j].value += 1; + + } + } + //get sum of data pixels + else + val += data->values[i]; + + } + + + if(histogramArgument != qDefs::Intensity){ + val /= numValues; + + //find scan value + int ci = 0, fi = 0; double cs0 = 0 , cs1 = 0; + fileIOStatic::getVariablesFromFileName(string(data->fileName), ci, fi, cs0, cs1); + + int scanval=-1; + if(cs0 != -1) + scanval = cs0; + else scanval = cs1; + + //ignore outside limits + if ((scanval < histFrom) || (scanval > histTo) || (scanval == -1)) + scanval = -1; + //check for intervals, increment if validates + for(int j=0;j0;i--) + memcpy(histYAxis[i],histYAxis[i-1],nPixelsX*sizeof(double)); + + //recalculating pedestal + if(startPedestalCal){ + //start adding frames to get to the pedestal value + if(pedestalCountvalues[px]; + memcpy(histYAxis[0],data->values,nPixelsX*sizeof(double)); + pedestalCount++; + } + //calculate the pedestal value + if(pedestalCount==NUM_PEDESTAL_FRAMES){ + cout << "Pedestal Calculated" << endl; + for(unsigned int px=0;pxvalues,nPixelsX*sizeof(double)); + resetAccumulate = false; + } + //pedestal or accumulate + else{ + double temp;//cannot overwrite cuz of accumulate + for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++){ + temp = data->values[px]; + if(pedestal) + temp = data->values[px] - (pedestalVals[px]); + if(binary) { + if ((temp >= binaryFrom) && (temp <= binaryTo)) + temp = 1; + else + temp = 0; + } + if(accumulate) + temp += histYAxis[0][px]; + //after all processing + histYAxis[0][px] = temp; + } + } + } + } + //2d + else{ + // Titles + imageTitle = temp_title; + //recalculating pedestal + if(startPedestalCal){ + //start adding frames to get to the pedestal value + if(pedestalCountvalues[px]; + memcpy(lastImageArray,data->values,nPixelsX*nPixelsY*sizeof(double)); + pedestalCount++; + } + //calculate the pedestal value + if(pedestalCount==NUM_PEDESTAL_FRAMES){ + cout << "Pedestal Calculated" << endl; + for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++) + tempPedestalVals[px] = tempPedestalVals[px]/(double)NUM_PEDESTAL_FRAMES; + memcpy(pedestalVals,tempPedestalVals,nPixelsX*nPixelsY*sizeof(double)); + startPedestalCal = 0; + } + } + + //normal data + if(((!pedestal)&(!accumulate)&(!binary)) || (resetAccumulate)){ + memcpy(lastImageArray,data->values,nPixelsX*nPixelsY*sizeof(double)); + resetAccumulate = false; + } + //pedestal or accumulate or binary + else{ + double temp; + for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++){ + temp = data->values[px]; + if(pedestal) + temp = data->values[px] - (pedestalVals[px]); + if(binary) { + if ((temp >= binaryFrom) && (temp <= binaryTo)) + temp = 1; + else + temp = 0; + } + if(accumulate) + temp += lastImageArray[px]; + //after all processing + lastImageArray[px] = temp; + } + } + + } + /* pthread_mutex_unlock(&(last_image_complete_mutex)); + }*/ + UnlockLastImageArray(); + +#ifdef VERYVERBOSE + cprintf(BLUE,"currentframe:%d \tcurrentframeindex:%d\n",currentFrame,currentFrameIndex); +#endif + emit UpdatePlotSignal(); + plotRequired = true; + currentFrame++; + } + + +#ifdef VERYVERBOSE + cout << "Exiting GetData function" << endl; +#endif + return 0; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::GetAcquisitionFinishedCallBack(double currentProgress,int detectorStatus, void *this_pointer){ + ((qDrawPlot*)this_pointer)->AcquisitionFinished(currentProgress,detectorStatus); +#ifdef VERYVERBOSE + cout << "acquisition finished callback worked ok" << endl; +#endif + return 0; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::AcquisitionFinished(double currentProgress, int detectorStatus){ +#ifdef VERBOSE + cout << "\nEntering Acquisition Finished with status " ; +#endif + QString status = QString(slsDetectorBase::runStatusType(slsDetectorDefs::runStatus(detectorStatus)).c_str()); +#ifdef VERBOSE + cout << status.toAscii().constData() << " and progress " << currentProgress << endl; +#endif + //error or stopped + if((stop_signal)||(detectorStatus==slsDetectorDefs::ERROR)){ +#ifdef VERBOSE + cout << "Error in Acquisition" << endl << endl; +#endif + //stop_signal = 1;//just to be sure + emit AcquisitionErrorSignal(status); + } + + //all measurements are over + else if(currentProgress==100){ +#ifdef VERBOSE + cout << "Acquisition Finished" << endl << endl; +#endif + } + + StartStopDaqToggle(true); + //this lets the measurement tab know its over, and to enable tabs + emit UpdatingPlotFinished(); + + //calculate s curve inflection point + int l1=0,l2=0,j; + if((histogram)&&(histogramArgument != qDefs::Intensity)){ + for(j=0;j l2){ + cout << "***** s curve inflectionfound at " << histogramSamples[j].interval.maxValue() << "" + "or j at " << j << " with l1 " << l1 << " and l2 " << l2 << endl; + } + } + } + + return 0; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::GetProgressCallBack(double currentProgress, void *this_pointer){ + ((qDrawPlot*)this_pointer)->progress= currentProgress; + return 0; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::ShowAcquisitionErrorMessage(QString status){ + if(!alreadyDisplayed){ + alreadyDisplayed = true; + qDefs::Message(qDefs::WARNING,string("The acquisiton has ended abruptly. " + "Current Detector Status: ")+status.toAscii().constData()+ + string("."),"qDrawPlot::ShowAcquisitionErrorMessage"); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::GetMeasurementFinishedCallBack(int currentMeasurementIndex, int fileIndex, void *this_pointer){ + ((qDrawPlot*)this_pointer)->MeasurementFinished(currentMeasurementIndex, fileIndex); + return 0; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::MeasurementFinished(int currentMeasurementIndex, int fileIndex){ +#ifdef VERBOSE + cout << "Entering Measurement Finished with currentMeasurement " << currentMeasurementIndex << " and fileIndex " << fileIndex << endl; +#endif + + //to make sure it plots the last frame + while(plotRequired){ + usleep(2000); + } + + currentMeasurement = currentMeasurementIndex+1; + currentFileIndex = fileIndex; +#ifdef VERBOSE + cout << "currentMeasurement:" << currentMeasurement << endl; +#endif + emit SetCurrentMeasurementSignal(currentMeasurement); + SetupMeasurement(); + /*if((myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) && (myDet->getFramesCaughtByReceiver() == 0)) + boxPlot->setTitle("OLD_plot.raw");*/ + return 0; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SelectPlot(int i){ //1 for 1D otherwise 2D + if(i==1){ + //Clear1DPlot(); it clears the last measurement + plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); + plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); + plot1D->show(); + plot2D->hide(); + boxPlot->setFlat(false); + plot_in_scope=1; + layout->addWidget(histFrameIndexTitle,0,0); + plotLayout->setContentsMargins(10,10,10,10); + }else{ + plot2D->SetXTitle(imageXAxisTitle); + plot2D->SetYTitle(imageYAxisTitle); + plot2D->SetZTitle(imageZAxisTitle); + plot1D->hide(); + plot2D->show(); + boxPlot->setFlat(true); + plot_in_scope=2; + histFrameIndexTitle->setText(""); + layout->removeWidget(histFrameIndexTitle); + plotLayout->setContentsMargins(0,0,0,0); + + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::Clear1DPlot(){ + for(QVector::iterator h = plot1D_hists.begin(); h!=plot1D_hists.end();h++){ + (*h)->Detach(plot1D); + //do not delete *h or h. + } + + plotHistogram->detach(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::UpdatePlot(){ +#ifdef VERYVERBOSE + cout << "Entering UpdatePlot function" << endl; +#endif + // only if no plot isnt enabled + if(plotEnable && plotRequired){ + LockLastImageArray(); + //so that it doesnt plot every single thing +#ifdef VERYVERBOSE + cprintf(GREEN,"Updating Plot\n"); +#endif + //so as to not plot it again and to let measurment finished know its done plotting it + //1-d plot stuff + if(plot_in_scope==1){ +#ifdef VERYVERBOSE + cout << "Last Image Number:" << lastImageNumber << endl; +#endif + if(histNBins){ + Clear1DPlot(); + plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); + plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); + + //histogram + if(histogram){ + plotHistogram->setData(new QwtIntervalSeriesData(histogramSamples)); + plotHistogram->setPen(QPen(Qt::red)); + plotHistogram->setBrush(QBrush(Qt::red,Qt::Dense4Pattern));//Qt::SolidPattern + histFrameIndexTitle->setText(GetHistTitle(0)); + plotHistogram->attach(plot1D); + //refixing all the zooming + + plot1D->SetXMinMax(startPixel,endPixel); + plot1D->SetYMinMax(0,plotHistogram->boundingRect().height()); + plot1D->SetZoomBase(startPixel,0,endPixel-startPixel,plotHistogram->boundingRect().height()); + + } + //not histogram + else{ + for(int hist_num=0;hist_num<(int)nHists;hist_num++){ + SlsQtH1D* h; + if(hist_num+1>plot1D_hists.size()){ + if(anglePlot) + plot1D_hists.append(h=new SlsQtH1D("",histNBins,histXAngleAxis,histYAngleAxis)); + else + plot1D_hists.append(h=new SlsQtH1D("",histNBins,histXAxis,GetHistYAxis(hist_num))); + h->SetLineColor(hist_num); + }else{ + h=plot1D_hists.at(hist_num); + if(anglePlot) + h->SetData(histNBins,histXAngleAxis,histYAngleAxis); + else + h->SetData(histNBins,histXAxis,GetHistYAxis(hist_num)); + } + SetStyle(h); + histFrameIndexTitle->setText(GetHistTitle(0)); + //h->setTitle(GetHistTitle(hist_num)); + h->Attach(plot1D); + //refixing all the zooming + //if((firstPlot) || (anglePlot)){ + /*plot1D->SetXMinMax(h->minXValue(),h->maxXValue()); + plot1D->SetYMinMax(h->minYValue(),h->maxYValue()); + plot1D->SetZoomBase(h->minXValue(),h->minYValue(), + h->maxXValue()-h->minXValue(),h->maxYValue()-h->minYValue());*/ + // firstPlot = false; + //} + } + + /**moved from below (had applied to histograms as well) to here, */ + // update range if required + if(XYRangeChanged){ + if(!IsXYRange[qDefs::XMINIMUM]) XYRangeValues[qDefs::XMINIMUM]= plot1D->GetXMinimum(); + if(!IsXYRange[qDefs::XMAXIMUM]) XYRangeValues[qDefs::XMAXIMUM]= plot1D->GetXMaximum(); + if(!IsXYRange[qDefs::YMINIMUM]) XYRangeValues[qDefs::YMINIMUM]= plot1D->GetYMinimum(); + if(!IsXYRange[qDefs::YMAXIMUM]) XYRangeValues[qDefs::YMAXIMUM]= plot1D->GetYMaximum(); + plot1D->SetXMinMax(XYRangeValues[qDefs::XMINIMUM],XYRangeValues[qDefs::XMAXIMUM]); + plot1D->SetYMinMax(XYRangeValues[qDefs::YMINIMUM],XYRangeValues[qDefs::YMAXIMUM]); + //Should not be reset for histogram, + //that is the only way to zoom in (new plots are zoomed out as its different each time) + if(!histogram) + XYRangeChanged = false; + } + /**moved from below (had applied to histograms as well) to here, */ + //Display Statistics + if(displayStatistics){ + double min=0,max=0,sum=0; + if(anglePlot) + GetStatistics(min,max,sum,histYAngleAxis,histNBins); + else + GetStatistics(min,max,sum,histYAxis[0],histNBins); + lblMinDisp->setText(QString("%1").arg(min)); + lblMaxDisp->setText(QString("%1").arg(max)); + lblSumDisp->setText(QString("%1").arg(sum)); + } + } + + if(saveAll) SavePlotAutomatic(); + + } + }//2-d plot stuff + else{ + if(lastImageArray){ + if(nPixelsX>0&&nPixelsY>0){ + plot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,lastImageArray); + plot2D->setTitle(GetImageTitle()); + plot2D->SetXTitle(imageXAxisTitle); + plot2D->SetYTitle(imageYAxisTitle); + plot2D->SetZTitle(imageZAxisTitle); + plot2D->UpdateNKeepSetRangeIfSet(); //keep a "set" z range, and call Update(); + } + // update range if required + if(XYRangeChanged){ + if(!IsXYRange[qDefs::XMINIMUM]) XYRangeValues[qDefs::XMINIMUM]= plot2D->GetPlot()->GetXMinimum(); + if(!IsXYRange[qDefs::XMAXIMUM]) XYRangeValues[qDefs::XMAXIMUM]= plot2D->GetPlot()->GetXMaximum(); + if(!IsXYRange[qDefs::YMINIMUM]) XYRangeValues[qDefs::YMINIMUM]= plot2D->GetPlot()->GetYMinimum(); + if(!IsXYRange[qDefs::YMAXIMUM]) XYRangeValues[qDefs::YMAXIMUM]= plot2D->GetPlot()->GetYMaximum(); + plot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM],XYRangeValues[qDefs::XMAXIMUM]); + plot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM],XYRangeValues[qDefs::YMAXIMUM]); + XYRangeChanged = false; + } + plot2D->GetPlot()->Update(); + //Display Statistics + if(displayStatistics){ + double min=0,max=0,sum=0; + GetStatistics(min,max,sum,lastImageArray,nPixelsX*nPixelsY); + lblMinDisp->setText(QString("%1").arg(min)); + lblMaxDisp->setText(QString("%1").arg(max)); + lblSumDisp->setText(QString("%1").arg(sum)); + } + if(saveAll) SavePlotAutomatic(); + } + } + //set plot title + boxPlot->setTitle(plotTitle); + //to notify the measurement finished when its done + plotRequired = false; + UnlockLastImageArray(); + } + +#ifdef VERYVERBOSE + cout << "Exiting UpdatePlot function" << endl; +#endif +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::ClonePlot(){ + int i; + + //check for space for more clone widget references + bool found = false; + for(i=0;igetFilePath(); + qDefs::checkErrorMessage(myDet,"qDrawPlot::ClonePlot"); + } + + + + LockLastImageArray(); + + + // create clone & copy data + if(plot_in_scope==1){ + winClone[i] = new qCloneWidget(this,i,boxPlot->title(),histXAxisTitle,histYAxisTitle,"", + (int)plot_in_scope,sFilePath,displayStatistics,lblMinDisp->text(),lblMaxDisp->text(),lblSumDisp->text()); + if(!anglePlot) + winClone[i]->SetCloneHists((int)nHists,histNBins,histXAxis,histYAxis,histTitle,lines,markers); + else + winClone[i]->SetCloneHists((int)nHists,histNBins,histXAngleAxis,histYAngleAxis,histTitle,lines,markers); + + }else{ + winClone[i] = new qCloneWidget(this,i,boxPlot->title(),imageXAxisTitle, imageYAxisTitle, imageZAxisTitle, + (int)plot_in_scope,sFilePath,displayStatistics,lblMinDisp->text(),lblMaxDisp->text(),lblSumDisp->text()); + winClone[i]->SetCloneHists2D(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,lastImageArray); + } + + // update range + found =false; + for(int index=0;index<4;index++) + if(IsXYRange[index]){ + found=true; + break; + } + if(found) + winClone[i]->SetRange(IsXYRange,XYRangeValues); + + + UnlockLastImageArray(); + + winClone[i]->show(); + + // to remember which all clone widgets were closed + connect(winClone[i], SIGNAL(CloneClosedSignal(int)),this, SLOT(CloneCloseEvent(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SaveClones(){ + char errID[200]; + string errMessage= "The Snapshots with ID's: "; + bool success = true; + for(int i=0;iSavePlotAutomatic()){ + success = false; + sprintf(errID,"%d",i); + errMessage.append(string(errID)+string(", ")); + } + } + if(success) + qDefs::Message(qDefs::INFORMATION,"The Snapshots have all been saved successfully in .png.","Dock"); + else + qDefs::Message(qDefs::WARNING,errMessage + string("were not saved."),"qDrawPlot::SaveClones"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::CloseClones(){ + for(int i=0;iclose(); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::CloneCloseEvent(int id){ + winClone[id]=0; +#ifdef VERBOSE + cout << "Closing Clone Window id:" << id << endl; +#endif +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SavePlot(){ + // render image + QImage savedImage(size().width(),size().height(),QImage::Format_RGB32); + QPainter painter(&savedImage); + render(&painter); + + QString fName; + if(running) fName = filePath; + else { + fName = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet,"qDrawPlot::SavePlot"); + } + + if(boxPlot->title().contains('.')){ + fName.append(QString('/')+boxPlot->title()); + fName.replace(".dat",".png"); + fName.replace(".raw",".png"); + }else fName.append(QString("/Image.png")); + + fName = QFileDialog::getSaveFileName(0,tr("Save Image"),fName,tr("PNG Files (*.png);;XPM Files(*.xpm);;JPEG Files(*.jpg)"),0,QFileDialog::ShowDirsOnly); + + if (!fName.isEmpty()) + if(savedImage.save(fName)) + qDefs::Message(qDefs::INFORMATION,"The Image has been successfully saved","qDrawPlot::SavePlot"); + else + qDefs::Message(qDefs::WARNING,"Attempt to save image failed.\n" + "Formats: .png, .jpg, .xpm.","qDrawPlot::SavePlot"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SavePlotAutomatic(){ + //no need to save the same plot many times + if((currentFrame>lastSavedFrame)&&(currentMeasurement>=lastSavedMeasurement)){ + + QString qFilePath; + if(running) qFilePath = filePath; + else { + qFilePath = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet,"qDrawPlot::SavePlotAutomatic"); + } + + + lastSavedFrame = currentFrame; + lastSavedMeasurement = currentMeasurement; + char cID[10]; + sprintf(cID,"%d",lastSavedFrame); + //title + QString fName = qFilePath; + if(boxPlot->title().contains('.')){ + fName.append(QString('/')+boxPlot->title()); + fName.replace(".dat",".png"); + fName.replace(".raw",".png"); + }else fName.append(QString("/Image_unknown_title.png")); + //save + QImage img(size().width(),size().height(),QImage::Format_RGB32); + QPainter painter(&img); + render(&painter); + //if error while saving + if(!img.save(fName)){ + //mention the error only the first time + if(!saveError){ + //so it doesnt repeat again + saveError = true; + connect(this,SIGNAL(saveErrorSignal(QString)),this,SLOT(ShowSaveErrorMessage(QString))); + emit saveErrorSignal(fName); + } + } + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::ShowSaveErrorMessage(QString fileName){ + qDefs::Message(qDefs::WARNING,string("Automatic Saving: Could not save the first file:\n")+ + string(fileName.toAscii().constData()) + string("\n\nNote: Will not show future file save errors for this acquisition."),"qDrawPlot::ShowSaveErrorMessage"); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SetPersistency(int val){ + for(int i=0;i<=val;i++) + if(!histYAxis[i]) histYAxis[i] = new double [nPixelsX]; + persistency = val; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::EnablePlot(bool enable){ +#ifdef VERBOSE + cout << "Plotting set to:" << enable << endl; +#endif + plotEnable = enable; + //if no plot, cant do setting range. + // not true vice versa where plot was false and now set it to true + Clear1DPlot(); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::DisableZoom(bool disable){ + if(plot_in_scope==1) + plot1D->DisableZoom(disable); + else + plot2D->GetPlot()->DisableZoom(disable); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qDrawPlot::UpdateTrimbitPlot(bool fromDetector,bool Histogram){ + int ret,i,actualPixelsX; + double min=0,max=0,sum=0; +#ifdef VERBOSE + if(fromDetector) cout << "Geting Trimbits from Detector" << endl; + else cout << "Getting Trimbits from Shared Memory" << endl; +#endif + + LockLastImageArray(); + + if(detType == slsDetectorDefs::MYTHEN){ + + //get trimbits + actualPixelsX = myDet->getTotalNumberOfChannels(slsDetectorDefs::X); + if(histTrimbits) delete [] histTrimbits; histTrimbits = new double[actualPixelsX]; + ret = myDet->getChanRegs(histTrimbits,fromDetector); + // cout << "got it!" << endl; + if(!ret){ + qDefs::Message(qDefs::WARNING,"No Trimbit data found in shared memory.","qDrawPlot::UpdateTrimbitPlot"); + UnlockLastImageArray(); + return qDefs::FAIL; + } +#ifdef VERBOSE + cout << "Got Trimbits" << endl; +#endif + + qDefs::checkErrorMessage(myDet,"qDrawPlot::UpdateTrimbitPlot"); + + //clear/select plot and set titles + Select1DPlot(); + Clear1DPlot(); + + //Display Statistics + if(displayStatistics){ + GetStatistics(min,max,sum,histTrimbits,actualPixelsX); + lblMinDisp->setText(QString("%1").arg(min)); + lblMaxDisp->setText(QString("%1").arg(max)); + lblSumDisp->setText(QString("%1").arg(sum)); + } + + + if(!Histogram){ + cout << "Data Graph:" << nPixelsX << endl; + + //initialize + nPixelsX = actualPixelsX; + if(histXAxis) delete [] histXAxis; histXAxis = new double [nPixelsX]; + if(histYAxis[0]) delete [] histYAxis[0]; histYAxis[0]= new double [nPixelsX]; + //initializing + for(unsigned int px=0;px<(int)nPixelsX;px++) histXAxis[px] = px; + for(i=0;isetTitle("Trimbits_Plot_Data Graph"); + plot1D->SetXTitle("Channel Number"); + plot1D->SetYTitle("Trimbits"); + //set plot parameters + plot1D->SetXMinMax(0,nPixelsX); + /*plot1D->SetYMinMax(0,plotHistogram->boundingRect().height()); plot1D->SetZoomBase(0,0,nPixelsX,plot1D->GetYMaximum());*/ + //for some reason this plothistogram works as well. + plot1D->SetZoomBase(0,0,nPixelsX,plotHistogram->boundingRect().height()); + SlsQtH1D* h; + plot1D_hists.append(h=new SlsQtH1D("",nPixelsX,histXAxis,histYAxis[0])); + h->SetLineColor(0); + histFrameIndexTitle->setText(GetHistTitle(0)); + //attach plot + h->Attach(plot1D); + //refixing all the zooming + /*plot1D->SetXMinMax(h->minXValue(),h->maxXValue()); + plot1D->SetYMinMax(h->minYValue(),h->maxYValue()); + plot1D->SetZoomBase(h->minXValue(),h->minYValue(), + h->maxXValue()-h->minXValue(),h->maxYValue()-h->minYValue());*/ + } + + else{ + cout << "Histogram: " << TRIM_HISTOGRAM_XMAX << endl; + + //create intervals + histogramSamples.resize(TRIM_HISTOGRAM_XMAX+1); + for(i=0; i= 0)){//if(histogramSamples[j].interval.contains(data->values[i])) + value = (int) histTrimbits[i]; + histogramSamples[value].value += 1; + } + else cout<<"OUT OF BOUNDS:"<setTitle("Trimbits_Plot_Histogram"); + plot1D->SetXTitle("Trimbits"); + plot1D->SetYTitle("Frequency"); + plotHistogram->setData(new QwtIntervalSeriesData(histogramSamples)); + plotHistogram->setPen(QPen(Qt::red)); + plotHistogram->setBrush(QBrush(Qt::red,Qt::Dense4Pattern));//Qt::SolidPattern + histFrameIndexTitle->setText(GetHistTitle(0)); + plotHistogram->attach(plot1D); + //refixing all the zooming + plot1D->SetXMinMax(0,TRIM_HISTOGRAM_XMAX+1); + plot1D->SetYMinMax(0,plotHistogram->boundingRect().height()); + plot1D->SetZoomBase(0,0,actualPixelsX,plotHistogram->boundingRect().height()); + } + } + + + /**needs to be changed */ + else if(detType == slsDetectorDefs::EIGER){ + + //defining axes + nPixelsX = 100;/**??*/ + nPixelsY = 100; + if(lastImageArray) delete [] lastImageArray; lastImageArray = new double[nPixelsY*nPixelsX]; + //initializing 2d array + for(int py=0;py<(int)nPixelsY;py++) + for(int px=0;px<(int)nPixelsX;px++) + lastImageArray[py*nPixelsX+px] = 0; + //get trimbits + ret = 1;/*myDet->getChanRegs(lastImageArray,fromDetector);*/ + if(!ret){ + qDefs::Message(qDefs::WARNING,"No Trimbit data found in shared memory.","qDrawPlot::UpdateTrimbitPlot"); + UnlockLastImageArray(); + return qDefs::FAIL; + } + //clear/select plot and set titles + Select2DPlot(); + plot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,-0.5,nPixelsY-0.5,lastImageArray); + plot2D->setTitle("Image"); + plot2D->SetXTitle("Pixel"); + plot2D->SetYTitle("Pixel"); + plot2D->SetZTitle("Trimbits"); + plot2D->UpdateNKeepSetRangeIfSet(); +#ifdef VERBOSE + cout << "Trimbits Plot updated" << endl; +#endif + + //Display Statistics + if(displayStatistics){ + GetStatistics(min,max,sum,lastImageArray,nPixelsX*nPixelsY); + lblMinDisp->setText(QString("%1").arg(min)); + lblMaxDisp->setText(QString("%1").arg(max)); + lblSumDisp->setText(QString("%1").arg(sum)); + } + + } + + UnlockLastImageArray(); +#ifdef VERBOSE + cout << "Trimbits Plot updated" << endl; +#endif + return qDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SetPedestal(bool enable){ +#ifdef VERBOSE + cout << "Setting Pedestal to " << enable << endl; +#endif + if(enable){ + pedestal = true; + if(pedestalVals == 0) + RecalculatePedestal(); + }else{ + pedestal = false; + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::RecalculatePedestal(){ +#ifdef VERBOSE + cout << "Recalculating Pedestal" << endl; +#endif + LockLastImageArray(); + startPedestalCal = 1; + pedestalCount = 0; + + //create array + if(pedestalVals) delete [] pedestalVals; pedestalVals = new double[nPixelsX*nPixelsY]; + if(tempPedestalVals) delete [] tempPedestalVals; tempPedestalVals = new double[nPixelsX*nPixelsY]; + //reset all values + for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++) + pedestalVals[px] = 0; + for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++) + tempPedestalVals[px] = 0; + UnlockLastImageArray(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SetAccumulate(bool enable){ +#ifdef VERBOSE + cout << "Setting Accumulate to " << enable << endl; +#endif + accumulate = enable; +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::ResetAccumulate(){ +#ifdef VERBOSE + cout << "Resetting Accumulation" << endl; +#endif + LockLastImageArray(); + resetAccumulate = true; + UnlockLastImageArray(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SetPlotTimer(double time){ + timerValue = time; + if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ + time = myDet->setReceiverReadTimer(timerValue); +#ifdef VERBOSE + cout << "Receiver read timer set to : " << time << endl; +#endif + qDefs::checkErrorMessage(myDet,"qDrawPlot::SetPlotTimer"); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SetFrameFactor(int frame){ + frameFactor = frame; + if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ + frame = myDet->setReadReceiverFrequency(1,frame); + /*if(frame > 0) frameFactor = 1;*//**what is this*/ +#ifdef VERBOSE + cout << "Receiver read frequency set to : " << frame << endl; +#endif + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +void qDrawPlot::UpdateAfterCloning(bool points, bool logy, bool interpolate, bool contour, bool logz){ +#ifdef VERBOSE + cout << endl << "**Updating Plot After Cloning" << endl; +#endif + + //1d + if(plot_in_scope == 1){ + SetMarkers(points); + emit LogySignal(logy); + } + //2d + else{ + emit InterpolateSignal(interpolate); + emit ContourSignal(contour); + emit LogzSignal(logz); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::SetBinary(bool enable, int from, int to){ +#ifdef VERBOSE + if(!enable) + cout << "Disabling Binary output " << endl; + else + cout << "Enabling Binary output from " << from << " to " << to << endl; +#endif + binary = enable; + binaryFrom = from; + binaryTo = to; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::DisplayStatistics(bool enable){ +#ifdef VERBOSE + if(!enable) + cout << "Disabling Statistics Display" << endl; + else + cout << "Enabling Statistics Display" << endl; +#endif + if(enable) widgetStatistics->show(); + else widgetStatistics->hide(); + + displayStatistics = enable; + lblMinDisp->setText("-"); + lblMaxDisp->setText("-"); + lblSumDisp->setText("-"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qDrawPlot::GetStatistics(double &min, double &max, double &sum, double* array, int size){ +#ifdef VERYVERBOSE + cout << "Calculating Statistics" << endl; +#endif + + for(int i=0; i < size; i++){ + //calculate min + if(array[i] < min) + min = array[i]; + //calculate max + if(array[i] > max) + max = array[i]; + //calculate sum + sum += array[i]; + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qScanWidget.cpp b/slsDetectorGui/src/qScanWidget.cpp new file mode 100644 index 0000000000..df21eb056c --- /dev/null +++ b/slsDetectorGui/src/qScanWidget.cpp @@ -0,0 +1,1247 @@ +/* + * qScanWidget.cpp + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +// Qt Project Class Headers +#include "qScanWidget.h" +// Qt Include Headers +#include +#include + +// C++ Include Headers +#include +#include +#include +#include +using namespace std; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qScanWidget::NUM_SCAN_WIDGETS(0); +const string qScanWidget::modeNames[NumModes]={"","energy","threshold","trimbits","position","custom script"}; +//------------------------------------------------------------------------------------------------------------------------------------------------- + +qScanWidget::qScanWidget(QWidget *parent,multiSlsDetector*& detector): + QWidget(parent),myDet(detector),actualNumSteps(0){ + setupUi(this); + positions.resize(0); + SetupWidgetWindow(); + Initialization(); + LoadPositions(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qScanWidget::~qScanWidget(){ + delete myDet; + delete stackedLayout; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::SetupWidgetWindow(){ + id = NUM_SCAN_WIDGETS; + NUM_SCAN_WIDGETS++; + + setFixedHeight(125); + + btnGroup = new QButtonGroup(this); + btnGroup->addButton(radioRange,0); + btnGroup->addButton(radioCustom,1); + btnGroup->addButton(radioFile,2); + + + normal = radioCustom->palette(); + red = QPalette(); + red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + fileTip = radioFile->toolTip(); + customTip = radioCustom->toolTip(); + rangeTip = radioRange->toolTip(); + + //layout for the size widgets + stackedLayout = new QStackedLayout; + stackedLayout->setSpacing(0); + + + // Range Size Layout + QWidget *widgetRange = new QWidget; + QHBoxLayout *layoutRange = new QHBoxLayout(widgetRange); + layoutRange->setContentsMargins(0, 0, 0, 0); + lblFrom = new QLabel("from",widgetRange); + spinFrom = new QDoubleSpinBox(widgetRange); + lblTo = new QLabel("to",widgetRange); + spinTo = new QDoubleSpinBox(widgetRange); + lblSize = new QLabel("step size:",widgetRange); + spinSize = new QDoubleSpinBox(widgetRange); + lblFrom->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + lblFrom->setToolTip(rangeTip); + spinFrom->setValue(0); + spinFrom->setToolTip(rangeTip); + spinFrom->setMaximum(1000000); + spinFrom->setMinimum(-1000000); + spinFrom->setKeyboardTracking(false); + spinFrom->setFixedWidth(80); + spinFrom->setDecimals(2); + lblTo->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + lblTo->setToolTip(rangeTip); + lblTo->setFixedWidth(18); + spinTo->setValue(1); + spinTo->setToolTip(rangeTip); + spinTo->setMaximum(1000000); + spinTo->setMinimum(-1000000); + spinTo->setKeyboardTracking(false); + spinTo->setFixedWidth(80); + spinTo->setDecimals(2); + lblSize->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + lblSize->setToolTip(rangeTip); + lblSize->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + lblSize->setFixedWidth(67); + spinSize->setMaximum(1000000); + spinSize->setMinimum(-1000000); + spinSize->setValue(1); + spinSize->setSingleStep(0.1); + spinSize->setToolTip(rangeTip); + spinSize->setKeyboardTracking(false); + spinSize->setDecimals(2); + + //spinSize->setMinimum(0.0001); + layoutRange->addItem(new QSpacerItem(40,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + layoutRange->addWidget(lblFrom); + layoutRange->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + layoutRange->addWidget(spinFrom); + layoutRange->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + layoutRange->addWidget(lblTo); + layoutRange->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + layoutRange->addWidget(spinTo); + layoutRange->addItem(new QSpacerItem(30,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + layoutRange->addWidget(lblSize); + layoutRange->addWidget(spinSize); + layoutRange->addItem(new QSpacerItem(40,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + + + // Custom Values Layout + QWidget *widgetCustom = new QWidget; + QHBoxLayout *layoutCustom = new QHBoxLayout(widgetCustom); + layoutCustom->setContentsMargins(0, 0, 0, 0); + comboCustom = new QComboBox(widgetCustom); + btnCustom = new QPushButton("Delete ",widgetCustom); + btnCustom->setIcon(QIcon( ":/icons/images/close.png" )); + comboCustom->setEditable(true); + comboCustom->setCompleter(NULL); + comboCustom->setValidator(new QDoubleValidator(comboCustom)); + comboCustom->setToolTip(customTip); + btnCustom->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + btnCustom->setToolTip("Deletes current position from list and reduces Number of Positions by 1."); + layoutCustom->addItem(new QSpacerItem(160,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + layoutCustom->addWidget(comboCustom); + layoutCustom->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + layoutCustom->addWidget(btnCustom); + layoutCustom->addItem(new QSpacerItem(160,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + + // File values From a File Layout + QWidget *widgetFile = new QWidget; + QHBoxLayout *layoutFile = new QHBoxLayout(widgetFile); + layoutFile->setContentsMargins(0, 0, 0, 0); + layoutFile->addItem(new QSpacerItem(50,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + dispFile = new QLineEdit(widgetFile); + dispFile->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); + dispFile->setToolTip(fileTip); + layoutFile->addWidget(dispFile); + btnFile = new QPushButton("Browse",widgetFile); + btnFile->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + btnFile->setToolTip(fileTip); + layoutFile->addWidget(btnFile); + layoutFile->addItem(new QSpacerItem(50,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + + + stackedLayout->addWidget(widgetRange); + stackedLayout->addWidget(widgetCustom); + stackedLayout->addWidget(widgetFile); + stackedWidget->setLayout(stackedLayout); + + radioCustom->setChecked(true); + stackedLayout->setCurrentIndex(CustomValues); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::Initialization(){ + //mode + connect(comboScript, SIGNAL(currentIndexChanged(int)), this,SLOT(SetMode(int))); + //file + connect(dispScript, SIGNAL(editingFinished()), this, SLOT(SetScriptFile())); + connect(btnBrowse, SIGNAL(clicked()), this, SLOT(BrowsePath())); + //parameter + connect(dispParameter, SIGNAL(editingFinished()), this, SLOT(SetParameter())); + //sizewidgets + connect(btnGroup, SIGNAL(buttonClicked(QAbstractButton*)),this,SLOT(EnableSizeWidgets())); + //numsteps + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + //precision + connect(spinPrecision, SIGNAL(valueChanged(int)), this, SLOT(SetPrecision(int))); + //range values + connect(spinFrom, SIGNAL(valueChanged(double)), this, SLOT(RangeFromChanged())); + connect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); + connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); + //custom values + connect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); + connect(btnCustom, SIGNAL(clicked()), this, SLOT(DeleteCustomSteps())); + //file values + connect(dispFile, SIGNAL(editingFinished()), this, SLOT(SetFileSteps())); + connect(btnFile, SIGNAL(clicked()), this, SLOT(BrowseFileStepsPath())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::EnableSizeWidgets(){ +#ifdef VERYVERBOSE + cout << "Entering EnableSizeWidgets()" << endl; +#endif + //setting to defaults is not done here as this is called even if mode changes + //so only if its to change the size widget type, its set to default for the others + + //scan is none + if(!comboScript->currentIndex()){ + radioCustom->setText("Specific Values"); + radioCustom->setPalette(normal); + radioCustom->setToolTip(customTip); + comboCustom->setToolTip(customTip); + + radioFile->setPalette(normal); + radioFile->setText("Values from File:"); + radioFile->setToolTip(fileTip); + dispFile->setToolTip(fileTip); + btnFile->setToolTip(fileTip); + + lblTo->setPalette(normal); + lblTo->setText("to"); + lblTo->setToolTip(rangeTip); + spinTo->setToolTip(rangeTip); + } + else{ + //range values + if(radioRange->isChecked()){ +#ifdef VERBOSE + cout << "Constant Range Values" << endl; +#endif + + radioCustom->setText("Specific Values"); + radioCustom->setPalette(normal); + radioCustom->setToolTip(customTip); + comboCustom->setToolTip(customTip); + + radioFile->setPalette(normal); + radioFile->setText("Values from File:"); + radioFile->setToolTip(fileTip); + dispFile->setToolTip(fileTip); + btnFile->setToolTip(fileTip); + + stackedLayout->setCurrentIndex(RangeValues); + + //recaluculate number of steps + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + spinSteps->setValue(1+(int)(abs((spinTo->value() - spinFrom->value()) / spinSize->value()))); + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + + spinSteps->setMinimum(2); + RangeCheckToValid(); + SetRangeSteps(); + } + //custom values + else if(radioCustom->isChecked()){ +#ifdef VERBOSE + cout << "Custom Values" << endl; +#endif + spinSteps->setMinimum(0); + //defaults for other mode + radioFile->setPalette(normal); + radioFile->setText("Values from File:"); + radioFile->setToolTip(fileTip); + dispFile->setToolTip(fileTip); + btnFile->setToolTip(fileTip); + + lblTo->setPalette(normal); + lblTo->setText("to"); + lblTo->setToolTip(rangeTip); + spinTo->setToolTip(rangeTip); + + //change it back as this list is what will be loaded. + //also numstpes could have been changed in other modes too + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + spinSteps ->setValue(comboCustom->count()); + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + + stackedLayout->setCurrentIndex(CustomValues); + //only for custom steps out here because many signals go through + //custom steps and we want to give the info msg only when changig range types + if(SetCustomSteps()==qDefs::OK){ +#ifdef VERYVERBOSE + char cNum[200];sprintf(cNum,"%d",actualNumSteps); + char cId[5];sprintf(cId,"%d",id); + qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ + string(": Specific Values

Number of positions added: ")+ + string(cNum)+string(""),"qScanWidget::EnableSizeWidgets"); +#endif + } + } + + //file values + else{ +#ifdef VERBOSE + cout << "File Values" << endl; +#endif + spinSteps->setMinimum(0); + //defaults for other mode + radioCustom->setText("Specific Values"); + radioCustom->setPalette(normal); + radioCustom->setToolTip(customTip); + comboCustom->setToolTip(customTip); + + lblTo->setPalette(normal); + lblTo->setText("to"); + lblTo->setToolTip(rangeTip); + spinTo->setToolTip(rangeTip); + + stackedLayout->setCurrentIndex(FileValues); + SetFileSteps(); + } + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::SetMode(int mode){ +#ifdef VERYVERBOSE + cout << "Entering SetMode()" << endl; +#endif +#ifdef VERBOSE + cout << "Setting\tscan:" << id << "\tmode:" << mode << endl; +#endif + // defaults + dispScript->setEnabled(false); + btnBrowse->setEnabled(false); + lblParameter->setEnabled(false); + dispParameter->setEnabled(false); + group->setEnabled(false); + lblSteps->setEnabled(false); + spinSteps->setEnabled(false); + lblPrecision->setEnabled(false); + spinPrecision->setEnabled(false); + + // If anything other than None is selected + if(mode){ + lblSteps->setEnabled(true); + spinSteps->setEnabled(true); + // Custom Script only enables the first layout with addnl parameters etc + if(mode==CustomScript){ + dispScript->setEnabled(true); + btnBrowse->setEnabled(true); + lblParameter->setEnabled(true); + dispParameter->setEnabled(true); + } + group->setEnabled(true); + lblPrecision->setEnabled(true); + spinPrecision->setEnabled(true); + + } + + //set the group box widgets and also calls setscan + EnableSizeWidgets(); + + //set the mode if mode = none + if(!mode) SetScan(mode); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qScanWidget::SetScan(int mode){ +#ifdef VERYVERBOSE + cout << "Entering SetScan()" << endl; +#endif + string parameter = string(dispParameter->text().toAscii().constData()); + string script = string(dispScript->text().toAscii().constData()); +#ifdef VERBOSE + cout << "SETTING scan:" << id << "\tmode:" << comboScript->currentIndex() << + "\tnumSteps:" << actualNumSteps << + "\tscript:" << script << "\tparameter:" << parameter << endl; +#endif + double *values; + if(actualNumSteps) values = new double[actualNumSteps]; + else values = NULL; + for(int i=0;isetScan(id,script,actualNumSteps,values,parameter); + else + myDet->setScan(id,modeNames[mode],actualNumSteps,values,parameter); + + //custom script + int actualMode = myDet->getScanMode(id); + if((mode==CustomScript)&&((script=="")||(script=="none"))){ + return qDefs::OK; + }else{//mode NOT set + if((mode!=actualMode)&&(actualNumSteps)){ + qDefs::Message(qDefs::WARNING,"The mode could not be changed for an unknown reason.","qScanWidget::SetScan"); + comboScript->setCurrentIndex(actualMode); + return qDefs::FAIL; + } + } + + emit EnableScanBox(); + + qDefs::checkErrorMessage(myDet,"qScanWidget::SetScan"); + + return qDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qScanWidget::BrowsePath(){ +#ifdef VERYVERBOSE + cout << "Entering BrowsePath()" << endl; +#endif +#ifdef VERBOSE + cout << "Browsing Script File Path\tscan:" << id << endl; +#endif + QString fName = dispScript->text(); + QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); + if(dir.isEmpty()) dir = "/home/"; + //dialog + fName = QFileDialog::getOpenFileName(this, + tr("Load Script File"),dir, + tr("Script Files(*.awk);;All Files(*)")); + //if empty, set the file name and it calls setscriptfile, else ignore + if (!fName.isEmpty()){ + dispScript->setText(fName); + SetScriptFile(); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qScanWidget::SetScriptFile(){ +#ifdef VERYVERBOSE + cout << "Entering SetScriptFile()" << endl; +#endif + QString fName = dispScript->text(); +#ifdef VERBOSE + cout << "Setting\tscan:" << id << "\tscript:" << fName.toAscii().constData() << endl; +#endif + bool set = false; + struct stat st_buf; + + //blank + if(fName.isEmpty()) + set = true; + //none isnt in the modeNames list, so check separately + else if(!fName.compare("none")) + set = true; + else{//if one of the other modes + for(int i=1;isetText(QString(myDet->getScanScript(id).c_str())); + } + //if its not a file + else if (!S_ISREG (st_buf.st_mode)) { + qDefs::Message(qDefs::WARNING,"The script file path entered is not a file","qScanWidget::SetScriptFile"); + dispScript->setText(QString(myDet->getScanScript(id).c_str())); + } + else + set=true; + } + + //if blank or valid file + if(set){ + myDet->setScanScript(id,fName.toAscii().constData()); + if(fName.compare(QString(myDet->getScanScript(id).c_str()))){ + //did not get set, write what is was before + if(!fName.isEmpty()) + qDefs::Message(qDefs::WARNING,"The script file could not be set. Reverting to previous file.","qScanWidget::SetScriptFile"); + dispScript->setText(QString(myDet->getScanScript(id).c_str())); + } + + } + + //dont display if theres a none + fName = dispScript->text(); + //none isnt in the modeNames list, so check separately + if(!fName.compare("none")) + dispScript->setText(""); + for(int i=1;isetText(""); + + qDefs::checkErrorMessage(myDet,"qScanWidget::SetScriptFile"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::SetParameter(){ +#ifdef VERYVERBOSE + cout << "Entering SetParameter()" << endl; +#endif + QString parameter = dispParameter->text(); +#ifdef VERBOSE + cout << "Setting\tscan:" << id << "\tparameter:" << parameter.toAscii().constData() << endl; +#endif + + myDet->setScanParameter(id,parameter.toAscii().constData()); + //dont display if theres a none + parameter = dispParameter->text(); + //none isnt in the modeNames list, so check separately + if(!parameter.compare("none")) + dispParameter->setText(""); + for(int i=1;isetText(""); + + qDefs::checkErrorMessage(myDet,"qScanWidget::SetParameter"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::SetPrecision(int value){ +#ifdef VERYVERBOSE + cout << "Entering SetPrecision()" << endl; +#endif +#ifdef VERBOSE + cout << "Setting\tscan:" << id << "\tprecision:" << value << endl; +#endif + myDet->setScanPrecision(id,value); + if(myDet->getScanPrecision(id)!=value) + qDefs::Message(qDefs::WARNING,"The precision was not set for an unknown reason.","qScanWidget::SetPrecision");; + + qDefs::checkErrorMessage(myDet,"qScanWidget::SetPrecision"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::SetNSteps(){ +#ifdef VERYVERBOSE + cout << "Entering SetNSteps()" << endl; +#endif +#ifdef VERBOSE + cout << "Setting number of steps" << endl; +#endif + + //check if its ok + if(radioRange->isChecked()){ + disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); + spinSize->setValue( (spinTo->value()-spinFrom->value()) / (spinSteps->value()-1)); + connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); + RangeCheckToValid(); + SetRangeSteps(); + }else if(radioCustom->isChecked()){ + comboCustom->setMaxCount(spinSteps->value()); + SetCustomSteps(); + }else if(radioFile->isChecked()){ + SetFileSteps(); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qScanWidget::RangeCheckSizeZero(){ +#ifdef VERYVERBOSE + cout << "Entering RangeCheckSizeZero()" << endl; +#endif + if((spinTo->value()-spinFrom->value())/(spinSteps->value()-1)) + return qDefs::OK; + + return qDefs::FAIL; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qScanWidget::RangeCheckNumValid(int &num){ +#ifdef VERYVERBOSE + cout << "Entering RangeCheckNumValid()" << endl; +#endif + double div = abs(spinTo->value()-spinFrom->value())/(abs(spinSize->value())); + + //num = (to-from)/size +1 + num = (int)(div) + 1; + + if(num>=2) return qDefs::OK; + + return qDefs::FAIL; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qScanWidget::RangeCheckToValid(){ +#ifdef VERYVERBOSE + cout << "Entering RangeCheckToValid()" << endl; +#endif + double to = (spinSize->value() * spinSteps->value()) - spinSize->value() + spinFrom->value(); + + //not exact value + if (abs(to-spinTo->value())>0.01){ + lblTo->setPalette(red); + lblTo->setText("to*"); + QString tip = rangeTip + QString("

" + "To is not exact. Entering Size should recalculate To."); + lblTo->setToolTip(tip); + spinTo->setToolTip(tip); + return qDefs::FAIL; + } + + lblTo->setPalette(normal); + lblTo->setText("to"); + lblTo->setToolTip(rangeTip); + spinTo->setToolTip(rangeTip); + return qDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::RangeFromChanged(){ +#ifdef VERYVERBOSE + cout << "Entering RangeFromChanged()" << endl; +#endif + bool change = false; + int numSteps; + + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + disconnect(spinFrom, SIGNAL(valueChanged(double)), this, SLOT(RangeFromChanged())); + disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); + + + //check size validity + if(RangeCheckSizeZero()==qDefs::FAIL) + qDefs::Message(qDefs::WARNING,"From cannot be equal to To. Changing From back to previous value.","Scan"); + //check size validity + else if(RangeCheckNumValid(numSteps)==qDefs::FAIL) + qDefs::Message(qDefs::WARNING,"Number of Steps = 1 + ( To - From ) / Size.
" + "Number of Steps must be >= 2. Changing From back to previous value.","qScanWidget::RangeFromChanged"); + else change = true; + + //change it back from = to - size*num + size + if(!change) { + spinFrom->setValue(spinTo->value() - (spinSize->value() * spinSteps->value()) + spinSize->value()); +#ifdef VERBOSE + cout << "Changing From back:"<< spinFrom->value() << endl; +#endif + } + //change num steps + else{ + spinSteps->setValue(numSteps); + //size will lnever be zero here + //size should be positive + if(spinTo->value()>spinFrom->value()) + spinSize->setValue(abs(spinSize->value())); + //size should be negative + else if(spinSize->value()>0) + spinSize->setValue(-1*(spinSize->value())); + } + + RangeCheckToValid(); + SetRangeSteps(); + + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + connect(spinFrom, SIGNAL(valueChanged(double)), this, SLOT(RangeFromChanged())); + connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::RangeToChanged(){ +#ifdef VERYVERBOSE + cout << "Entering RangeToChanged()" << endl; +#endif + bool change = false; + int numSteps; + + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + disconnect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); + disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); + + //check size validity + if(RangeCheckSizeZero()==qDefs::FAIL) + qDefs::Message(qDefs::WARNING,"From cannot be equal to To. Changing To back to previous value.","qScanWidget::RangeToChanged"); + //check size validity + else if(RangeCheckNumValid(numSteps)==qDefs::FAIL) + qDefs::Message(qDefs::WARNING,"Number of Steps = 1 + ( To - From ) / Size.
" + "Number of Steps must be >= 2. Changing To back to previous value.","qScanWidget::RangeToChanged"); + else change = true; + + //change it back to = size*num - size + from + if(!change) { + spinTo->setValue((spinSize->value() * spinSteps->value()) - spinSize->value() + spinFrom->value()); +#ifdef VERBOSE + cout << "Changing To back:"<< spinTo->value() << endl; +#endif + } + //change num steps + else{ + spinSteps->setValue(numSteps); + //size will lnever be zero here + //size should be positive + if(spinTo->value()>spinFrom->value()) + spinSize->setValue(abs(spinSize->value())); + //size should be negative + else if(spinSize->value()>0) + spinSize->setValue(-1*(spinSize->value())); + + } + + RangeCheckToValid(); + SetRangeSteps(); + + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + connect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); + connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::RangeSizeChanged(){ +#ifdef VERYVERBOSE + cout << "Entering RangeSizeChanged()" << endl; +#endif + bool change = false; + int numSteps; + + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); + disconnect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); + + //check size validity + if(!spinSize->value()) + qDefs::Message(qDefs::WARNING,"Size cannot be 0. Changing Size back to previous value.","qScanWidget::RangeSizeChanged"); + //check size validity + else if(RangeCheckNumValid(numSteps)==qDefs::FAIL) + qDefs::Message(qDefs::WARNING,"Number of Steps = 1 + ( To - From ) / Size.
" + "Number of Steps must be >= 2. Changing Size back to previous value.","qScanWidget::RangeSizeChanged"); + else change = true; + + //change it back size = (to-from)/(num-1) + if(!change) { + spinSize->setValue((spinTo->value()-spinFrom->value())/(spinSteps->value()-1)); +#ifdef VERBOSE + cout << "Changing Size back:"<< spinSize->value() << endl; +#endif + } + //change num steps + else{ + spinSteps->setValue(numSteps); + //in case size changed to negative + spinTo->setValue((spinSize->value() * spinSteps->value()) - spinSize->value() + spinFrom->value()); + lblTo->setPalette(normal); + lblTo->setText("to"); + lblTo->setToolTip(rangeTip); + spinTo->setToolTip(rangeTip); + } + + RangeCheckToValid(); + SetRangeSteps(); + + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); + connect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::SetRangeSteps(){ +#ifdef VERYVERBOSE + cout << "Entering SetRangeSteps()" << endl; +#endif +#ifdef VERBOSE + cout << "Setting\tscan:" << id << "\trange\t"; +#endif + double fromVal = spinFrom->value(); + double sizeVal = spinSize->value(); + actualNumSteps = spinSteps->value(); + + +#ifdef VERBOSE + cout << "num pos:" << actualNumSteps << endl; +#endif + + //set the vector positions + positions.resize(actualNumSteps); + for(int i=0;icurrentIndex())==qDefs::OK){ + char cId[5];sprintf(cId,"%d",id); + QString script = dispScript->text(); + + + //positions wont be loaded if its custom script + if((comboScript->currentIndex()==CustomScript)&&((script=="")||(script=="none"))){ + qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ + string(": Constant Step Size

" + "Positions could not be loaded as the script file path is empty."),"qScanWidget::SetRangeSteps"); + }else{ + //error loading positions + if(myDet->getScanSteps(id)!=actualNumSteps){ + qDefs::Message(qDefs::WARNING,string("Scan Level ")+string(cId)+ + string(": Values From File

" + "The positions list was not set for an unknown reason."),"qScanWidget::SetRangeSteps"); + /*LoadPositions(); + comboScript->setCurrentIndex(myDet->getScanMode(id))*/ + } +#ifdef VERYVERBOSE + else{//SUCCESS + char cNum[200];sprintf(cNum,"%d",actualNumSteps); + qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ + string(": Constant Step Size

Number of positions added: ")+ + string(cNum)+string(""),"qScanWidget::SetRangeSteps"); + } +#endif + } + } + + qDefs::checkErrorMessage(myDet,"qScanWidget::SetRangeSteps"); +} +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qScanWidget::SetCustomSteps(){ +#ifdef VERYVERBOSE + cout << "Entering SetCustomSteps()" << endl; +#endif +#ifdef VERBOSE + cout << "Setting\tscan:" << id << "\tcustom\tnum pos:" << comboCustom->count() << endl; +#endif + disconnect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); + + //get number of positions + int numSteps = spinSteps->value(); + comboCustom->setMaxCount(numSteps); + comboCustom->setEnabled(numSteps); + btnCustom->setEnabled(numSteps); + + //deleting too many or not entering enough + if(numSteps>comboCustom->count()){ +#ifdef VERBOSE + cout << "Too few entries" << endl; +#endif + int diff = numSteps - (comboCustom->count()); + radioCustom->setPalette(red); + radioCustom->setText("Specific Values*"); + QString tip = customTip + QString("

Add ")+ + (QString("%1").arg(diff))+ + QString(" more positions to the list to match Number of Steps.
" + "
Or reduce Number of Steps.
"); + radioCustom->setToolTip(tip); + comboCustom->setToolTip(tip); + }else{ + radioCustom->setText("Specific Values"); + radioCustom->setPalette(normal); + radioCustom->setToolTip(customTip); + comboCustom->setToolTip(customTip); + } + + actualNumSteps = comboCustom->count(); + //delete existing positions + positions.resize(actualNumSteps); + //copying the list + for(int i=0;iitemText(i).toDouble(); +#ifdef VERBOSE + cout << "positions[" << i << "]:" << positions[i] << endl; +#endif + } + + //sets the scan + if(SetScan(comboScript->currentIndex())==qDefs::OK){ + char cId[5];sprintf(cId,"%d",id); + QString script = dispScript->text(); + //positions wont be loaded if its custom script + if((comboScript->currentIndex()==CustomScript)&&((script=="")||(script=="none"))){ + qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ + string(": Values From File

" + "Positions could not be loaded as the script file path is empty."),"qScanWidget::SetCustomSteps"); + return qDefs::FAIL; + }else{ + if(myDet->getScanSteps(id)!=actualNumSteps){ + qDefs::Message(qDefs::WARNING,"The positions list was not set for an unknown reason.","qScanWidget::SetCustomSteps"); + LoadPositions(); + comboScript->setCurrentIndex(myDet->getScanMode(id)); + qDefs::checkErrorMessage(myDet,"qScanWidget::qScanWidget::SetCustomSteps"); + return qDefs::FAIL; + } + //else success is checked in enabledsizewidgets , else it does this for every add, delete etc + } + } + + //if num of steps = 0 + if(!spinSteps->value()){ + comboCustom->setEnabled(false); + btnCustom->setEnabled(false); + radioCustom->setPalette(red); + radioCustom->setText("Specific Values*"); + QString tip = customTip + QString("

First, increase Number of Steps. " + "Then, enter values here."); + radioCustom->setToolTip(tip); + comboCustom->setToolTip(tip); + } + connect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); + + return qDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::DeleteCustomSteps(){ +#ifdef VERYVERBOSE + cout << "Entering DeleteCustomSteps()" << endl; +#endif + QString pos = comboCustom->currentText(); + bool found = false; + //loops through to find the index and to make sure its in the list + for(int i=0;icount();i++){ + if(!comboCustom->itemText(i).compare(pos)){ + found = true; + comboCustom->removeItem(i); + break; + } + } + if(found){ +#ifdef VERBOSE + cout << "Deleting Position " << endl; +#endif + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::SetFileSteps(){ +#ifdef VERYVERBOSE + cout << "Entering SetFileSteps()" << endl; +#endif + QString fName = dispFile->text(); +#ifdef VERBOSE + cout << "Setting\tscan:" << id << "\tfile\t:" << fName.toAscii().constData() << endl; +#endif + bool set = false; + struct stat st_buf; + + //blank + if(fName.isEmpty()){ +#ifdef VERBOSE + cout << "Empty file" << endl; +#endif + radioFile->setPalette(red); + radioFile->setText("Values from File:*"); + QString errTip = fileTip + QString("

The file path is empty.");; + radioFile->setToolTip(errTip);dispFile->setToolTip(errTip);btnFile->setToolTip(errTip); + } + //not a blank + else{ + QString file = dispFile->text().section('/',-1); + + //path doesnt exist + if(stat(file.toAscii().constData(),&st_buf)){ +#ifdef VERBOSE + cout << "The file entered does not exist." << endl; +#endif + radioFile->setPalette(red); + radioFile->setText("Values from File:*"); + QString errTip = fileTip + QString("

The file entered does not exist."); + radioFile->setToolTip(errTip);dispFile->setToolTip(errTip);btnFile->setToolTip(errTip); + } + //if its not a file + else if (!S_ISREG (st_buf.st_mode)) { +#ifdef VERBOSE + cout << "The file path entered is not a file." << endl; +#endif + radioFile->setPalette(red); + radioFile->setText("Values from File:*"); + QString errTip = fileTip + QString("

The file path entered is not a file."); + radioFile->setToolTip(errTip); dispFile->setToolTip(errTip);btnFile->setToolTip(errTip); + } + else + set = true; + } + + //if valid file + if(set){ + ifstream inFile;string sLine;char sArg[200]=""; + //open file + inFile.open(fName.toAscii().constData(), ifstream::in); + if(inFile.is_open()){ + //delete existing positions + positions.resize(0); + actualNumSteps = 0; +#ifdef VERBOSE + cout << "Opening file "<< fName.toAscii().constData() << endl; +#endif + while(inFile.good()) { + getline(inFile,sLine); + if(sLine.find('#')!=string::npos) continue;//commented out + else if(sLine.length()<2) continue;// empty line + else { + istringstream sstr(sLine); + if(sstr.good()){ + actualNumSteps++; + positions.resize(actualNumSteps); + sstr>>sArg; + if(!sscanf(sArg,"%lf",&positions[actualNumSteps-1])){ + actualNumSteps--; + positions.resize(actualNumSteps); + } + else cout << "value[" << actualNumSteps-1 << "]:" << positions[actualNumSteps-1] << endl; + } + } + } + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + spinSteps->setValue(actualNumSteps); + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + inFile.close(); + }else {//could not open file +#ifdef VERBOSE + cout << "Could not open file" << endl; +#endif + set = false; + radioFile->setPalette(red); + radioFile->setText("Values from File:*"); + QString errTip = fileTip + QString("

Could not read file."); + radioFile->setToolTip(errTip);dispFile->setToolTip(errTip); btnFile->setToolTip(errTip); + } + } + if(set){//no error while reading file + //sets the scan and positions + if(SetScan(comboScript->currentIndex())==qDefs::OK){ + char cId[5];sprintf(cId,"%d",id); + QString script = dispScript->text(); + radioFile->setPalette(normal); + radioFile->setText("Values from File:"); + radioFile->setToolTip(fileTip);dispFile->setToolTip(fileTip);btnFile->setToolTip(fileTip); + //positions wont be loaded if its custom script + if((comboScript->currentIndex()==CustomScript)&&((script=="")||(script=="none"))){ + qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ + string(": Values From File

" + "Positions could not be loaded as the script file path is empty."),"qScanWidget::SetFileSteps"); + }else{ + //error loading positions + if(myDet->getScanSteps(id)!=actualNumSteps){ + qDefs::Message(qDefs::WARNING,string("Scan Level ")+string(cId)+ + string(": Values From File

" + "The positions list was not set for an unknown reason."),"qScanWidget::SetFileSteps"); + } +#ifdef VERYVERBOSE + else{//SUCCESS + char cNum[200];sprintf(cNum,"%d",actualNumSteps); + qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ + string(": Values From File

Number of positions added: ")+ + string(cNum)+string(""),"qScanWidget::SetFileSteps"); + } +#endif + } + } + } + //ERROR IN WRITING FILENAME OR READING FILE + else{ + actualNumSteps=0; + positions.resize(0); + SetScan(comboScript->currentIndex()); + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + spinSteps->setValue(actualNumSteps); + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + } + + qDefs::checkErrorMessage(myDet,"qScanWidget::SetFileSteps"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::BrowseFileStepsPath(){ +#ifdef VERYVERBOSE + cout << "Entering BrowseFileStepsPath()" << endl; +#endif +#ifdef VERBOSE + cout << "Browsing Steps File Path\tscan:" << id << endl; +#endif + QString fName = dispFile->text(); + QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); + if(dir.isEmpty()) dir = "/home/"; + //dialog + fName = QFileDialog::getOpenFileName(this, + tr("Load Scan Steps Script File"),dir, + tr("Scan Steps Script Files(*.awk);;All Files(*)")); + //if empty, set the file name and it calls SetFileSteps, else ignore + if (!fName.isEmpty()){ + dispFile->setText(fName); + SetFileSteps(); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::LoadPositions(){ +#ifdef VERYVERBOSE + cout << "Entering LoadPositions()" << endl; +#endif + disconnect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); + disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + disconnect(btnGroup, SIGNAL(buttonClicked(QAbstractButton*)),this,SLOT(EnableSizeWidgets())); + + + int mode = myDet->getScanMode(id); + radioCustom->setChecked(true); + + int numSteps = myDet->getScanSteps(id); + actualNumSteps = numSteps; + comboCustom->setMaxCount(numSteps); + positions.resize(actualNumSteps); + + //set the number of steps in the gui + spinSteps->setValue(numSteps); + + //load the positions + double *values = NULL; + if(actualNumSteps){ + values = new double[actualNumSteps]; + myDet->getScanSteps(id,values); + } + for(int i=0;isetText("Specific Values"); + radioCustom->setPalette(normal); + radioCustom->setToolTip(customTip); + comboCustom->setToolTip(customTip); + }//no positions and has a mode + else if(mode){ + radioCustom->setPalette(red); + radioCustom->setText("Specific Values*"); + QString tip = customTip + QString("

First, increase Number of Steps. " + "Then, enter values here."); + radioCustom->setToolTip(tip); + comboCustom->setToolTip(tip); + } + for(int i=0;icount();i++) + comboCustom->removeItem(i); + for(int i=0;iinsertItem(i,QString("%1").arg(positions[i])); + + //delete the combolist and reload it + comboCustom->setEnabled(numSteps&&mode); + btnCustom->setEnabled(numSteps&&mode); + + connect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); + connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); + connect(btnGroup, SIGNAL(buttonClicked(QAbstractButton*)),this,SLOT(EnableSizeWidgets())); + + qDefs::checkErrorMessage(myDet,"qScanWidget::LoadPositions"); + //do not set the range variables because if the stepsize is by any chance 0.. + //then the number of steps should change to 1. so only set custom steps +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qScanWidget::Refresh(){ +#ifdef VERYVERBOSE + cout << "Entering Refresh()" << endl; +#endif + int mode = (myDet->getScanMode(id)); + string script = myDet->getScanScript(id); + string parameter = myDet->getScanParameter(id); + int precision = myDet->getScanPrecision(id); + + + //settings values and checking for none + if(QString(script.c_str()).compare("none")) + dispScript->setText(QString(script.c_str())); + if(mode) SetScriptFile(); + dispParameter->setText(QString(parameter.c_str())); + SetParameter(); + spinPrecision->setValue(precision); + + //set mode which also checks number of steps + //and enable size widgets and set the positions from combolist to server + comboScript->setCurrentIndex(mode); + + +#ifdef VERBOSE + cout << "Updated\tscan:" << id << "\t" + "mode:" << mode << "\t" + "script:" << script << "\t" + "numSteps:" << actualNumSteps << "\t" + //"values:" << arrSteps << "\t" + "parameter:" << parameter << "\t" + "precision:" << precision << "\t***" << endl; +#endif + + qDefs::checkErrorMessage(myDet,"qScanWidget::Refresh"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qServer.cpp b/slsDetectorGui/src/qServer.cpp new file mode 100644 index 0000000000..d818b88f8d --- /dev/null +++ b/slsDetectorGui/src/qServer.cpp @@ -0,0 +1,427 @@ +/* + * qServer.cpp + * + * Created on: Feb 27, 2013 + * Author: Dhanya Maliakal + */ +// Qt Project Class Headers +#include "qServer.h" +#include "qDetectorMain.h" +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +#include "MySocketTCP.h" +// C++ Include Headers +#include +#include +using namespace std; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qServer::gui_server_thread_running(0); + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qServer::qServer(qDetectorMain *t): + myMainTab(t), mySocket(NULL),myStopSocket(NULL),port_no(DEFAULT_GUI_PORTNO),lockStatus(0),checkStarted(0),checkStopStarted(0){ + strcpy(mess,""); + FunctionTable(); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qServer::~qServer(){ + delete myMainTab; + if(mySocket) delete mySocket; + if(myStopSocket) delete myStopSocket; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qServer::FunctionTable(){ + + flist[F_GET_RUN_STATUS] = &qServer::GetStatus; + flist[F_START_ACQUISITION] = &qServer::StartAcquisition; + flist[F_STOP_ACQUISITION] = &qServer::StopsAcquisition; + flist[F_START_AND_READ_ALL] = &qServer::Acquire; + flist[F_EXIT_SERVER] = &qServer::ExitServer; + + return qDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------ + + +int qServer::DecodeFunction(MySocketTCP* sock){ + int ret = qDefs::FAIL; + int n,fnum; +#ifdef VERYVERBOSE + cout << "receive data" << endl; +#endif + n = sock->ReceiveDataOnly(&fnum,sizeof(fnum)); + if (n <= 0) { +#ifdef VERYVERBOSE + cout << "ERROR reading from socket " << n << ", " << fnum << endl; +#endif + return qDefs::FAIL; + } +#ifdef VERYVERBOSE + else + cout << "size of data received " << n <ShutDownSocket(); + + myStopSocket->SendDataOnly(&ret,sizeof(ret)); + myStopSocket->SendDataOnly(mess,sizeof(mess)); + return GOODBYE; + } + + + //calling function + ret = (this->*flist[fnum])(); + if (ret==qDefs::FAIL) + cout << "Error executing the function = " << fnum << endl; + + return ret; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------ + + +int qServer::ExitServer(){ + + int ret = OK; + strcpy(mess," Gui Server closed successfully\n"); + + if(mySocket) + mySocket->ShutDownSocket(); + + myStopSocket->SendDataOnly(&ret,sizeof(ret)); + myStopSocket->SendDataOnly(mess,sizeof(mess)); + cout << mess << endl; + + return GOODBYE; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------ + + + +int qServer::StartStopServer(int start){ + + //start server + if(start){ +#ifdef VERBOSE + cout << endl << "Starting Gui Server" << endl; +#endif + + if(!gui_server_thread_running){ + gui_server_thread_running=1; + + + //error creating thread + checkStarted=1; + if (pthread_create(&gui_server_thread, NULL,StartServerThread, (void*) this)){ + gui_server_thread_running=0; + qDefs::Message(qDefs::WARNING,"Can't create gui server thread", "qServer::StartStopServer"); + cout << "ERROR: Can't create gui server thread" << endl; + return FAIL; + } + while(checkStarted); + checkStarted = 0; +#ifdef VERBOSE + if(gui_server_thread_running) + cout << "Server thread created successfully." << endl; +#endif + + + //error creating thread + checkStopStarted=1; + if (pthread_create(&gui_stop_server_thread, NULL,StopServerThread, (void*) this)){ + gui_server_thread_running=0; + qDefs::Message(qDefs::WARNING,"Can't create gui stop server thread", "qServer::StartStopServer"); + cout << "ERROR: Can't create gui stop server thread" << endl; + return FAIL; + } + while(checkStopStarted); + checkStopStarted=0; +#ifdef VERBOSE + if(gui_server_thread_running) + cout << "Server Stop thread created successfully." << endl; +#endif + } + } + + + //stop server + else{ +#ifdef VERBOSE + cout << "Stopping Gui Server" << endl; +#endif + + if(gui_server_thread_running){ + gui_server_thread_running=0; + + if(mySocket) + mySocket->ShutDownSocket(); + pthread_join(gui_server_thread,NULL); + if(mySocket){ + delete mySocket; + mySocket = NULL; + } + + if(myStopSocket) + myStopSocket->ShutDownSocket(); + pthread_join(gui_stop_server_thread,NULL); + if(myStopSocket){ + delete myStopSocket; + myStopSocket = NULL; + } + } +#ifdef VERBOSE + cout << "Server threads stopped successfully." << endl; +#endif + } + + return gui_server_thread_running; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void* qServer::StopServerThread(void* this_pointer){ + ((qServer*)this_pointer)->StopServer(); + return this_pointer; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +int qServer::StopServer(){ +#ifdef VERYVERBOSE + cout << "In StopServer()" << endl; +#endif + int ret = qDefs::OK; + + myStopSocket = new MySocketTCP(port_no+1); + if (myStopSocket->getErrorStatus()){ + gui_server_thread_running = 0; + qDefs::Message(qDefs::WARNING,"Could not start gui stop server socket","qServer::StopServer"); + } + checkStopStarted = 0; + + while ((gui_server_thread_running) && (ret!=GOODBYE)) { +#ifdef VERBOSE + cout<< endl; +#endif +#ifdef VERYVERBOSE + cout << "Waiting for client call" << endl; +#endif + if(myStopSocket->Connect()>=0){ +#ifdef VERYVERBOSE + cout << "Conenction accepted" << endl; +#endif + ret = DecodeFunction(myStopSocket); +#ifdef VERYVERBOSE + cout << "function executed" << endl; +#endif + myStopSocket->Disconnect(); +#ifdef VERYVERBOSE + cout << "connection closed" << endl; +#endif + } + } +#ifdef VERBOSE + cout << "Stopped gui stop server thread" << endl; +#endif + gui_server_thread_running = 0; + //delete socket(via exit server) + if(myStopSocket){ + delete myStopSocket; + myStopSocket = NULL; + } + + if(!gui_server_thread_running) + emit ServerStoppedSignal(); + + return qDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +void* qServer::StartServerThread(void* this_pointer){ + ((qServer*)this_pointer)->StartServer(); + return this_pointer; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +int qServer::StartServer(){ +#ifdef VERYVERBOSE + cout << "In StartServer()" << endl; +#endif + int ret = qDefs::OK; + + mySocket = new MySocketTCP(port_no); + if (mySocket->getErrorStatus()){ + gui_server_thread_running = 0; + qDefs::Message(qDefs::WARNING,"Could not start gui server socket","qServer::StartServer"); + } + checkStarted = 0; + + while ((gui_server_thread_running) && (ret!=GOODBYE)) { +#ifdef VERBOSE + cout<< endl; +#endif +#ifdef VERYVERBOSE + cout << "Waiting for client call" << endl; +#endif + if(mySocket->Connect()>=0){ +#ifdef VERYVERBOSE + cout << "Conenction accepted" << endl; +#endif + ret = DecodeFunction(mySocket); +#ifdef VERYVERBOSE + cout << "function executed" << endl; +#endif + mySocket->Disconnect(); +#ifdef VERYVERBOSE + cout << "connection closed" << endl; +#endif + } + } +#ifdef VERBOSE + cout << "Stopped gui server thread" << endl; +#endif + gui_server_thread_running = 0; + //delete socket(via exit server) + if(mySocket){ + delete mySocket; + mySocket = NULL; + } + + if(!gui_server_thread_running) + emit ServerStoppedSignal(); + + return qDefs::OK; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qServer::GetStatus(){ + + int ret = qDefs::OK; + enum slsDetectorDefs::runStatus retval; + int progress = 0; + + // execute action if the arguments correctly arrived + if(myMainTab->isPlotRunning()) + retval = slsDetectorDefs::RUNNING; + else + retval = slsDetectorDefs::IDLE; + + progress = myMainTab->GetProgress(); + + // send answer + myStopSocket->SendDataOnly(&ret,sizeof(ret)); + myStopSocket->SendDataOnly(&retval,sizeof(retval)); + myStopSocket->SendDataOnly(&progress,sizeof(progress)); + //return ok/fail + return ret; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------ + + +int qServer::StartAcquisition(){ + + strcpy(mess,"Could not start acquisition in gui. \n"); + + int ret = myMainTab->StartStopAcquisitionFromClient(true); + mySocket->SendDataOnly(&ret,sizeof(ret)); + if(ret==FAIL) + mySocket->SendDataOnly(mess,sizeof(mess)); + + return ret; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------ + + +int qServer::StopsAcquisition(){ + + strcpy(mess,"Could not stop acquisition in gui. \n"); + + int ret = myMainTab->StartStopAcquisitionFromClient(false); + myStopSocket->SendDataOnly(&ret,sizeof(ret)); + if(ret==FAIL) + myStopSocket->SendDataOnly(mess,sizeof(mess)); + + return ret; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------ + + +int qServer::Acquire(){ + + strcpy(mess,"Could not start blocking acquisition in gui. \n"); + + int ret = myMainTab->StartStopAcquisitionFromClient(true); + + usleep(5000); + while(myMainTab->isPlotRunning()); + + mySocket->SendDataOnly(&ret,sizeof(ret)); + if(ret==FAIL) + mySocket->SendDataOnly(mess,sizeof(mess)); + + return ret; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------ + diff --git a/slsDetectorGui/src/qTabActions.cpp b/slsDetectorGui/src/qTabActions.cpp new file mode 100644 index 0000000000..ebc0ee1403 --- /dev/null +++ b/slsDetectorGui/src/qTabActions.cpp @@ -0,0 +1,584 @@ +/* + * qTabActions.cpp + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ +// Qt Project Class Headers +#include "qTabActions.h" +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +// Qt Include Headers +#include +// C++ Include Headers +#include +using namespace std; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabActions::qTabActions(QWidget *parent,multiSlsDetector*& detector): + QWidget(parent),myDet(detector), + positionWidget(0), + lblNumPos(0), + lblPosList(0), + spinNumPos(0), + comboPos(0), + btnDelete(0), + chkInvert(0), + chkSeparate(0), + chkReturn(0), + positions(0), + iconPlus(0), + iconMinus(0){ + for(int i=0;i<6;i++) + actionWidget[i]=0; + for(int i=0;i<2;i++) + scanWidget[i]=0; + for(int i=0;isetWidget(this); + scroll->setWidgetResizable(true); + + // Layout Settings + gridLayout = new QGridLayout(scroll); + setLayout(gridLayout); + gridLayout->setContentsMargins(10,5,0,0); + gridLayout->setVerticalSpacing(2); + + // Buttongroup to know which +/- button was clicked + group = new QButtonGroup(this); + group->setExclusive(false); + palette = new QPalette(); + + QPalette p; + p.setColor(QPalette::Shadow,QColor(0,0,0,0)); + p.setColor(QPalette::Button,QColor(0,0,0,0)); +/*get rid of this vector*/ + char names[NumTotalActions][200] = { + "Action at Start", + "Scan Level 0", + "Scan Level 1", + "Action before each Frame", + "Positions", + "Header before Frame", + "Header after Frame", + "Action after each Frame", + "Action at Stop" + }; + + //creating the icons for the buttons + iconPlus = new QIcon(":/icons/images/add.png"); + iconMinus = new QIcon(":/icons/images/remove.png"); + + QString tip = "Click on the \"+\" to Expand or \"-\" to Collapse."; + + + + int hIndent=0, vIndent=0, colspan=6, posVal=0; + QLabel *lblReal; + // For each level of Actions + for(int i=0;isetToolTip(tip); + btnExpand[i]->setCheckable(true); + btnExpand[i]->setChecked(false); + btnExpand[i]->setFixedSize(16,16); + btnExpand[i]->setToolTip(tip); + btnExpand[i]->setIcon(*iconPlus); + btnExpand[i]->setFocusPolicy(Qt::NoFocus); + btnExpand[i]->setFlat(true); + btnExpand[i]->setIconSize(QSize(16,16)); + btnExpand[i]->setPalette(p); + group->addButton(btnExpand[i],i); + + + //add label and button to expand or collapse + gridLayout->addWidget(btnExpand[i],vIndent,hIndent,1,1); + gridLayout->addWidget(lblName[i],vIndent,hIndent+1,1,colspan); + + //creating the action/scan/position widgets and adding them + switch(i){ + case NumPositions: + CreatePositionsWidget(); + gridLayout->addWidget(positionWidget,vIndent+1,hIndent+1,1,colspan); + positionWidget->hide(); + break; + case Scan0: + case Scan1: + posVal = qScanWidget::NUM_SCAN_WIDGETS; + scanWidget[posVal] = new qScanWidget(this,myDet); + gridLayout->addWidget(scanWidget[posVal],vIndent+1,hIndent+1,1,colspan); + scanWidget[posVal]->hide(); + break; + default: + posVal = qActionsWidget::NUM_ACTION_WIDGETS; + actionWidget[posVal] = new qActionsWidget(this,myDet); + gridLayout->addWidget(actionWidget[posVal],vIndent+1,hIndent+1,1,colspan); + actionWidget[posVal]->hide(); + break; + } + + //incrementing the vertical and horizontal indent + vIndent+=2; + switch(i){ + case HeaderBefore: + //real time acquisition + palette->setColor(QPalette::Active,QPalette::WindowText,QColor(0,0,200,255)); + lblReal = new QLabel(" Real Time Acquisition"); + lblReal->setFixedHeight(25); + //lblReal->setPalette(*palette); + gridLayout->addWidget(lblReal,vIndent,hIndent+1,1,colspan); + vIndent++; + break; + case HeaderAfter: + hIndent-=2; + colspan+=2; + break; + case ActionAfter: + hIndent=0; + colspan=6; + break; + default: + hIndent++; + colspan--; + break; + } + + } + + + //Number of positions is only for mythen or gotthard + detType = myDet->getDetectorsType(); + if((detType == slsDetectorDefs::EIGER) || + (detType == slsDetectorDefs::AGIPD) || + (detType == slsDetectorDefs::PROPIX) || + (detType == slsDetectorDefs::JUNGFRAU) || + (detType == slsDetectorDefs::MOENCH)) { + lblName[NumPositions]->setEnabled(false); + btnExpand[NumPositions]->setEnabled(false); + }else{ + //disable positions if angular conversion is enabled + int ang; + if(!myDet->getAngularConversion(ang)){ + lblName[NumPositions]->setEnabled(false); + btnExpand[NumPositions]->setEnabled(false); + } + + } + + //load positions + if(lblName[NumPositions]->isEnabled()){ + //delete existing positions + if (positions) {delete [] positions; positions = NULL;} + //get number of positions + int numPos=myDet->getPositions(); + comboPos->setMaxCount(numPos); + + //set the number of positions in the gui + spinNumPos->setValue(numPos); + + positions=new double[numPos]; + //load the positions + myDet->getPositions(positions); + + //delete the combolist and reload it + comboPos->setEnabled(numPos); + lblPosList->setEnabled(numPos); + btnDelete->setEnabled(numPos); + lblPosList->setText("List of Positions: "); + lblPosList->setPalette(normal); + for(int i=0;icount();i++) comboPos->removeItem(i); + for(int i=0;iinsertItem(i,QString("%1").arg(positions[i])); + } + + + qDefs::checkErrorMessage(myDet,"qTabActions::SetupWidgetWindow"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabActions::CreatePositionsWidget(){ + positionWidget = new QWidget; + positionWidget->setFixedHeight(25); + positionWidget->setFixedWidth(680); + + QGridLayout *layout = new QGridLayout(positionWidget); + layout->setContentsMargins(0,0,0,0); + layout->setHorizontalSpacing(0); + layout->setVerticalSpacing(5); + + lblNumPos = new QLabel("Number of Positions: "); + lblNumPos->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + layout->addWidget(lblNumPos,0,0); + layout->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); + spinNumPos = new QSpinBox(this); + layout->addWidget(spinNumPos,0,2); + layout->addItem(new QSpacerItem(80,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,3); + lblPosList = new QLabel("List of Positions: "); + lblPosList->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + lblPosList->setFixedWidth(108); + lblPosList->setEnabled(false); + lblPosList->setToolTip("Enter the positions at which the detector should be moved.
" + "Number of entries is restricted to Number of Positions field."); + layout->addWidget(lblPosList,0,4); + comboPos = new QComboBox(this); + comboPos->setEditable(true); +// comboPos->setCompleter(false); + comboPos->setCompleter(NULL); + normal = comboPos->palette(); + comboPos->setEnabled(false); + QDoubleValidator *validate = new QDoubleValidator(comboPos); + comboPos->setValidator(validate); + layout->addWidget(comboPos,0,5); + layout->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,6); + btnDelete = new QPushButton("Delete "); + btnDelete->setEnabled(false); + btnDelete->setIcon(QIcon( ":/icons/images/close.png" )); + btnDelete->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + layout->addWidget(btnDelete,0,7); + + //might be included at some point +/* QGroupBox *w = new QGroupBox; + layout->addWidget(w,1,0,1,9); + QHBoxLayout *l1 = new QHBoxLayout(w); + l1->setContentsMargins(0,0,0,0); + l1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + chkInvert = new QCheckBox("Invert Angles"); + l1->addWidget(chkInvert); + chkSeparate = new QCheckBox("Separate Two Halves"); + l1->addWidget(chkSeparate); + chkReturn = new QCheckBox("Return to Start Position"); + chkReturn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + l1->addWidget(chkReturn); + l1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); + w->setLayout(l1);*/ + + positionWidget->setLayout(layout); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabActions::Initialization(){ + //expand + connect(group, SIGNAL(buttonClicked(QAbstractButton*)), this,SLOT(Expand(QAbstractButton*))); + //enable scan box in plot tab + for(int i=0;iid(button); + + // Collapse + if(!button->isChecked()){ + palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); + + + lblName[index]->setPalette(*palette); + button->setIcon(*iconPlus); + + if(index==NumPositions) { + positionWidget->hide(); + setFixedHeight(height()-30);//-80 if the checkboxes are included + if(myDet->getPositions()) { + palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); + lblName[index]->setPalette(*palette); + } + } + else if((index==Scan0)||(index==Scan1)) { + scanWidget[GetActualIndex(index)]->hide(); + setFixedHeight(height()-130); + if(myDet->getScanMode(GetActualIndex(index))){ + palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); + lblName[index]->setPalette(*palette); + } + } + else { + actionWidget[GetActualIndex(index)]->hide(); + setFixedHeight(height()-30); + if(myDet->getActionMode(GetActualIndex(index))){ + palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); + lblName[index]->setPalette(*palette); + } + } + }else{ + // Expand + //always set title color to blue for expan\d + + palette->setColor(QPalette::Active,QPalette::WindowText,QColor(0,0,200,255)); + + + lblName[index]->setPalette(*palette); + button->setIcon(*iconMinus); + + if(index==NumPositions){ + positionWidget->show(); + setFixedHeight(height()+30);//+80 if the checkboxes are included + } + else if((index==Scan0)||(index==Scan1)){ + scanWidget[GetActualIndex(index)]->show(); + setFixedHeight(height()+130); + } + else{ + actionWidget[GetActualIndex(index)]->show(); + setFixedHeight(height()+30); + } + } + + qDefs::checkErrorMessage(myDet,"qTabActions::Expand"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabActions::SetPosition(){ +#ifdef VERBOSE + cout << "Entering SetPosition\tnum Pos:" << spinNumPos->value() << "\tlist count:" << comboPos->count() << endl; +#endif + //get number of positions + int numPos = spinNumPos->value(); + comboPos->setMaxCount(numPos); + comboPos->setEnabled(numPos); + lblPosList->setEnabled(numPos); + btnDelete->setEnabled(numPos); + + //deleting too many or not entering enough + if(numPos>comboPos->count()){ + + QPalette red = QPalette(); + red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + lblPosList->setPalette(red); + QString tip = QString("Enter the positions at which the detector should be moved.
" + "Number of entries is restricted to Number of Positions field.

")+ + QString("Add ")+ + (QString("%1").arg(((numPos)-(comboPos->count()))))+ + QString(" more positions to the list to match Number of Positions.
" + "Or reduce Number of Positions.
"); + lblPosList->setToolTip(tip); + lblPosList->setText("List of Positions:*"); + }else{ + lblPosList->setText("List of Positions: "); + lblPosList->setPalette(normal); + lblPosList->setToolTip("Enter the positions at which the detector should be moved.
" + "Number of entries is restricted to Number of Positions field."); + } + + //delete existing positions + if (positions) {delete [] positions; positions = NULL;} + positions=new double[comboPos->count()]; + //copying the list + for(int i=0;icount();i++) + positions[i] = comboPos->itemText(i).toDouble(); + //setting the list and catching error + if(myDet->setPositions(comboPos->count(),positions)!=comboPos->count()) + qDefs::Message(qDefs::WARNING,"The positions list was not set for some reason.","qTabActions::SetPosition"); + + + qDefs::checkErrorMessage(myDet,"qTabActions::SetPosition"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabActions::DeletePosition(){ + QString pos = comboPos->currentText(); + bool found = false; + //loops through to find the index and to make sure its in the list + for(int i=0;icount();i++){ + if(!comboPos->itemText(i).compare(pos)){ + found = true; + comboPos->removeItem(i); + break; + } + } + if(found){ +#ifdef VERBOSE + cout << "Deleting Position " << endl; +#endif + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabActions::EnablePositions(bool enable){ +#ifdef VERBOSE + cout << "Enable Positions: " << enable << endl; +#endif + if(enable){ + lblName[NumPositions]->setEnabled(true); + btnExpand[NumPositions]->setEnabled(true); + }else{ + //deletes all positions + for(int i=0;icount();i++) + comboPos->removeItem(i); + cout<<"Number of Positions set to :"<getPositions()<isChecked()){ + disconnect(group, SIGNAL(buttonClicked(QAbstractButton*)), this,SLOT(Expand(QAbstractButton*))); + btnExpand[NumPositions]->setChecked(false); + connect(group, SIGNAL(buttonClicked(QAbstractButton*)), this,SLOT(Expand(QAbstractButton*))); + Expand(group->button(NumPositions)); + } + lblName[NumPositions]->setEnabled(false); + btnExpand[NumPositions]->setEnabled(false); + } + + qDefs::checkErrorMessage(myDet,"qTabActions::EnablePositions"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabActions::Refresh(){ +#ifdef VERBOSE + cout << endl <<"**Updating all action widgets: " << endl; +#endif + if((detType == slsDetectorDefs::MYTHEN) || (detType == slsDetectorDefs::GOTTHARD)){ + //positions is enabled only if angular conversion is enabled + int ang; if(!myDet->getAngularConversion(ang)) EnablePositions(false); + + if(lblName[NumPositions]->isEnabled()){ + //delete existing positions + if (positions) {delete [] positions; positions = NULL;} + //get number of positions + int numPos=myDet->getPositions(); + comboPos->setMaxCount(numPos); + + //set the number of positions in the gui + disconnect(spinNumPos, SIGNAL(valueChanged(int)), this, SLOT(SetPosition())); + spinNumPos->setValue(numPos); + connect(spinNumPos, SIGNAL(valueChanged(int)), this, SLOT(SetPosition())); + + positions=new double[numPos]; + //load the positions + myDet->getPositions(positions); + + //delete the combolist and reload it + disconnect(comboPos,SIGNAL(currentIndexChanged(int)), this, SLOT(SetPosition())); + comboPos->setEnabled(numPos); + lblPosList->setEnabled(numPos); + btnDelete->setEnabled(numPos); + lblPosList->setText("List of Positions: "); + lblPosList->setPalette(normal); + for(int i=0;icount();i++) + comboPos->removeItem(i); + for(int i=0;iinsertItem(i,QString("%1").arg(positions[i])); + connect(comboPos, SIGNAL(currentIndexChanged(int)), this, SLOT(SetPosition())); + + +#ifdef VERBOSE + cout << "Updated position widget\tnum:" << numPos << "\t***" << endl; +#endif + } + } + for(int i=0;iRefresh(); + for(int i=0;iRefresh(); + UpdateCollapseColors(); +#ifdef VERBOSE + cout << "**Updated all action widgets: " << endl << endl; +#endif + + qDefs::checkErrorMessage(myDet,"qTabActions::Refresh"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qTabActions::GetActualIndex(int index){ + switch(index){ + case 0: return slsDetectorDefs::startScript; + case Scan0: return 0; + case Scan1: return 1; + case 3: return slsDetectorDefs::scriptBefore; + case 5: return slsDetectorDefs::headerBefore; + case 6: return slsDetectorDefs::headerAfter; + case 7: return slsDetectorDefs::scriptAfter; + case 8: return slsDetectorDefs::stopScript; + default: return -1; + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabActions::UpdateCollapseColors(){ +#ifdef VERYVERBOSE + cout << "Updating Collapse Colors" << endl; +#endif + for(int i=0;igetPositions()) palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); + else palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); + lblName[i]->setPalette(*palette); + } + //scans + else if((i==Scan0)||(i==Scan1)){ + if(myDet->getScanMode(GetActualIndex(i))) palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); + else palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); + lblName[i]->setPalette(*palette); + } + //actions + else{ + if(myDet->getActionMode(GetActualIndex(i))) palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); + else palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); + lblName[i]->setPalette(*palette); + } + } + +} +//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qTabAdvanced.cpp b/slsDetectorGui/src/qTabAdvanced.cpp new file mode 100644 index 0000000000..6c4f290b5d --- /dev/null +++ b/slsDetectorGui/src/qTabAdvanced.cpp @@ -0,0 +1,1335 @@ +/* + * qTabAdvanced.cpp + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ +#include "qTabAdvanced.h" +#include "qDrawPlot.h" +/** Project Class Headers */ +#include "slsDetector.h" +#include "multiSlsDetector.h" +/** Qt Include Headers */ +#include +/** C++ Include Headers */ +#include +using namespace std; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabAdvanced::qTabAdvanced(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot): + QWidget(parent),myDet(detector),det(0),myPlot(plot),btnGroup(NULL),isEnergy(false),isAngular(false), + lblFromX(0), + spinFromX(0), + lblFromY(0), + spinFromY(0), + lblToX(0), + spinToX(0), + lblToY(0), + spinToY(0), + numRois(0){ + setupUi(this); + SetupWidgetWindow(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +qTabAdvanced::~qTabAdvanced(){ + delete myDet; + if(det) delete det; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetupWidgetWindow(){ + +//executed even for non digital, so make sure its necessary + + //Network + lblIP->setEnabled(false); + lblMAC->setEnabled(false); + dispIP->setEnabled(false); + dispMAC->setEnabled(false); + boxRxr->setEnabled(false); + boxSetAllTrimbits->setEnabled(false); + + + red = QPalette(); + red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + outputDirTip = dispFile->toolTip(); + errOutputTip = QString("

" + "Output Trim File should contain both existing directory and a file name.
" + "The extensions are automatically added.

" + "Enter valid Output Trim File to enable Start Trimming button.
"); + detOnlineTip = comboOnline->toolTip(); + rxrOnlineTip = comboRxrOnline->toolTip(); + errOnlineTip = QString("

It is offline!"); + + detType = myDet->getDetectorsType(); + switch(detType){ + case slsDetectorDefs::MYTHEN: + isEnergy = true; + isAngular = true; + break; + case slsDetectorDefs::EIGER: + isEnergy = true; + isAngular = false; + lblIP->setEnabled(true); + lblMAC->setEnabled(true); + dispIP->setEnabled(true); + dispMAC->setEnabled(true); + boxRxr->setEnabled(true); + boxSetAllTrimbits->setEnabled(true); + break; + case slsDetectorDefs::MOENCH: + isEnergy = false; + isAngular = false; + lblIP->setEnabled(true); + lblMAC->setEnabled(true); + dispIP->setEnabled(true); + dispMAC->setEnabled(true); + boxRxr->setEnabled(true); + break; + case slsDetectorDefs::GOTTHARD: + isEnergy = false; + isAngular = true; + lblIP->setEnabled(true); + lblMAC->setEnabled(true); + dispIP->setEnabled(true); + dispMAC->setEnabled(true); + boxRxr->setEnabled(true); + break; + case slsDetectorDefs::JUNGFRAU: + isEnergy = false; + isAngular = false; + lblIP->setEnabled(true); + lblMAC->setEnabled(true); + dispIP->setEnabled(true); + dispMAC->setEnabled(true); + boxRxr->setEnabled(true); + break; + default: break; + } + + + //logs and trimming + if(!isAngular && !isEnergy) boxLogs->setEnabled(false); + else{ + if(!isAngular) chkAngularLog->setEnabled(false); + if(!isEnergy){ + chkEnergyLog->setEnabled(false); + boxPlot->setEnabled(false); + boxTrimming->setEnabled(false); + }else{ + boxTrimming->setChecked(false); + SetOptimize(false); + + btnGroup = new QButtonGroup(this); + btnGroup->addButton(btnRefresh,0); + btnGroup->addButton(btnGetTrimbits,1); + } + } + trimmingMode = slsDetectorDefs::NOISE_TRIMMING; + + //network + + //add detectors + for(int i=0;igetNumberOfDetectors();i++) + comboDetector->addItem(QString(myDet->getHostname(i).c_str())); + + comboDetector->setCurrentIndex(0); + + det = myDet->getSlsDetector(comboDetector->currentIndex()); + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetupWidgetWindow"); + cout << "Getting ports" << endl; + spinControlPort->setValue(det->getControlPort()); + spinStopPort->setValue(det->getStopPort()); + spinTCPPort->setValue(det->getReceiverPort()); + spinUDPPort->setValue(atoi(det->getReceiverUDPPort())); + + cout << "Getting network information" << endl; + dispIP->setText(det->getDetectorIP()); + dispMAC->setText(det->getDetectorMAC()); + dispRxrHostname->setText(det->getReceiver()); + dispUDPIP->setText(det->getReceiverUDPIP()); + dispUDPMAC->setText(det->getReceiverUDPMAC()); + + + //check if its online and set it to red if offline +#ifdef VERYVERBOSE + cout << "online" << endl; +#endif + if(det->setOnline()==slsDetectorDefs::ONLINE_FLAG) + det->checkOnline(); + if(det->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) + det->checkReceiverOnline(); + comboOnline->setCurrentIndex(det->setOnline()); + comboRxrOnline->setCurrentIndex(det->setReceiverOnline()); + if(!comboOnline->currentIndex()){ + comboOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setPalette(red); + lblOnline->setText("Online:*"); + } + if((comboRxrOnline->isEnabled())&&(!comboRxrOnline->currentIndex())){ + comboRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setPalette(red); + lblRxrOnline->setText("Online:*"); + } + + + //updates roi + cout << "Getting ROI" << endl; + updateROIList(); + + // print receiver configurations + if(myDet->getDetectorsType() != slsDetectorDefs::MYTHEN){ + cout << endl; + myDet->printReceiverConfiguration(); + } + + Initialization(); + + qDefs::checkErrorMessage(det,"qTabAdvanced::SetupWidgetWindow"); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::Initialization(){ + + connect(tabAdvancedSettings,SIGNAL(currentChanged(int)), this, SLOT(Refresh())); + + //energy/angular logs + if(isAngular) + connect(chkEnergyLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); + + if(isEnergy){ + connect(chkAngularLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); + + //exptime + connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(SetExposureTime())); + connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetExposureTime())); + + //threshold dac + connect(spinThreshold, SIGNAL(valueChanged(double)), this, SLOT(SetThreshold())); + + //output directory + connect(dispFile, SIGNAL(editingFinished()), this, SLOT(SetOutputFile())); + connect(btnFile, SIGNAL(clicked()), this, SLOT(BrowseOutputFile())); + + //setalltrimbits + if(boxSetAllTrimbits->isEnabled()) + connect(spinSetAllTrimbits, SIGNAL(editingFinished()), this, SLOT(SetAllTrimbits())); + + //enable trimming method group box + connect(boxTrimming, SIGNAL(toggled(bool)), this, SLOT(EnableTrimming(bool))); + + //trimming method combo + connect(comboMethod, SIGNAL(currentIndexChanged(int)), this, SLOT(SetTrimmingMethod(int))); + + //method options + connect(chkOptimize, SIGNAL(toggled(bool)), this, SLOT(SetOptimize(bool))); + + //start Trimming + connect(btnStart, SIGNAL(clicked()), this, SLOT(StartTrimming())); + + //refresh + connect(btnGroup, SIGNAL(buttonClicked(int)), this, SLOT(UpdateTrimbitPlot(int))); + } + + //network + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(SetDetector(int))); + connect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); + connect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); + connect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); + + if((detType==slsDetectorDefs::GOTTHARD) || + (detType==slsDetectorDefs::MOENCH) || + (detType==slsDetectorDefs::PROPIX) || + (detType==slsDetectorDefs::PROPIX) || + (detType==slsDetectorDefs::JUNGFRAU)){ + + //network + connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); + connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); + connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + + connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + + connect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); + + } + + + //roi + + + connect(btnClearRoi, SIGNAL(clicked()), this, SLOT(clearROIinDetector())); + connect(btnGetRoi, SIGNAL(clicked()), this, SLOT(updateROIList())); + connect(btnSetRoi, SIGNAL(clicked()), this, SLOT(setROI())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetLogs(){ + QCheckBox *checkedBox = qobject_cast(sender()); + int index = ((!checkedBox->text().compare("Energy Calibration"))?slsDetectorDefs::enCalLog:slsDetectorDefs::angCalLog); + bool enable = checkedBox->isChecked(); +#ifdef VERBOSE + if(index==slsDetectorDefs::enCalLog) + cout << "Setting Energy Calibration Logs to " << enable << endl; + else + cout << "Setting Angular Calibration Logs to " << enable << endl; +#endif + //set/unset the log + myDet->setAction(index,(enable?"set":"none")); + //verify + if(myDet->getActionMode(index)!=(enable)){ +#ifdef VERBOSE + cout << "Could not set/reset Log." << endl; +#endif + qDefs::Message(qDefs::WARNING,"Could not set/reset Log.","qTabAdvanced::SetLogs"); + checkedBox->setChecked(!enable); + } + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetLogs"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetExposureTime(){ + //Get the value of timer in ns + double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(),spinExpTime->value()); +#ifdef VERBOSE + cout << "Setting Exposure Time to " << exptimeNS << " clocks" << "/" << spinExpTime->value() << qDefs::getUnitString((qDefs::timeUnit)comboExpUnit->currentIndex()) << endl; +#endif + myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,(int64_t)exptimeNS); + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetExposureTime"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetThreshold(){ +#ifdef VERBOSE + cout << "Setting Threshold DACu:" << spinThreshold->value() << endl; +#endif + spinThreshold->setValue((double)myDet->setDAC((dacs_t)spinThreshold->value(),slsDetectorDefs::THRESHOLD,0)); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetThreshold"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetOutputFile(){ +#ifdef VERBOSE + cout << "Setting Output File for Trimming:" << endl; +#endif + QString dirPath = dispFile->text().section('/',0,-2,QString::SectionIncludeLeadingSep); + cout << "Directory:" << dirPath.toAscii().constData() << "." << endl; + QString fName = dispFile->text().section('/',-1); + cout << "File Name:" << fName.toAscii().constData() << "." << endl; + //checks if directory exists and file name is not empty + if((QFile::exists(dirPath))&&(!fName.isEmpty())){ + + dispFile->setToolTip(outputDirTip); + lblFile->setToolTip(outputDirTip); + lblFile->setPalette(lblExpTime->palette()); + lblFile->setText("Output Trim File: "); + btnStart->setEnabled(true); + + + //check if you're overwriting original trimsettings + QDir dir; + //gets the clean absolute path + dirPath = dir.absoluteFilePath(dirPath); + dirPath = dir.cleanPath(dirPath); + QString trimdir = QString(myDet->getSettingsFile()).section('/',0,-2,QString::SectionIncludeLeadingSep); + trimdir = dir.absoluteFilePath(trimdir); + trimdir = dir.cleanPath(trimdir); + if(!dirPath.compare(trimdir)){ + int ret = qDefs::Message(qDefs::QUESTION,string("This will possibly overwrite your original trimbits.
" + "Proposed file path:") + string(dirPath.toAscii().constData())+ + string("
Do you still want to continue?"),"qTabAdvanced::SetOutputFile"); + if(ret==qDefs::FAIL){ + dispFile->setText(""); + dispFile->setToolTip(outputDirTip + errOutputTip); + lblFile->setToolTip(outputDirTip + errOutputTip); + lblFile->setPalette(red); + lblFile->setText("Output Trim File:*"); + btnStart->setEnabled(false); + } + } + + }//if the directory doesnt exist or if file name is empty + else{ + cout<<"Invalid Trimming output File"<setToolTip(outputDirTip + errOutputTip); + lblFile->setToolTip(outputDirTip + errOutputTip); + lblFile->setPalette(red); + lblFile->setText("Output Trim File:*"); + btnStart->setEnabled(false); + } + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetOutputFile"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::BrowseOutputFile(){ +#ifdef VERBOSE + cout << "Browsing Output Dir for Trimming" << endl; +#endif + QString fName = dispFile->text(); + //dialog + QFileDialog *fileDialog = new QFileDialog(this, + tr("Save Trimbits"),fName, + tr("Trimbit files (*.trim noise.sn*);;All Files(*) ")); + fileDialog->setFileMode(QFileDialog::AnyFile ); + if ( fileDialog->exec() == QDialog::Accepted ) + fName = fileDialog->selectedFiles()[0]; + + //if empty, set the file name and it calls SetFileSteps, else ignore + if (!fName.isEmpty()){ + dispFile->setText(fName); + SetOutputFile(); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::EnableTrimming(bool enable){ +#ifdef VERBOSE + cout << "Enable Trimming set to:" << enable << endl; +#endif + if(enable){ + //show error label if invalid output dir + SetOutputFile(); + SetTrimmingMethod(comboMethod->currentIndex()); + }else{ + //error label shouldnt show when disabled + dispFile->setToolTip(outputDirTip); + lblFile->setToolTip(outputDirTip); + lblFile->setPalette(lblExpTime->palette()); + lblFile->setText("Output Trim File: "); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabAdvanced::SetOptimize(bool enable){ +#ifdef VERBOSE + cout << "Setting Optimize to:" << enable << endl; +#endif + //trimming method is adjust to count + if(!comboMethod->currentIndex()){ + lblCounts->setEnabled(true); + spinCounts->setEnabled(true); + lblResolution->setEnabled(enable); + spinResolution->setEnabled(enable); + }//trimming method is equalize to median + else{ + lblCounts->setEnabled(false); + spinCounts->setEnabled(false); + lblResolution->setEnabled(true); + spinResolution->setEnabled(true); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetTrimmingMethod(int mode){ +#ifdef VERBOSE + cout << "Setting Trimming method to :" << mode << endl; +#endif + //make sure the right resolution/Counts is enabled + SetOptimize(chkOptimize->isChecked()); + + //set mode + switch(mode){ + case 0: trimmingMode = slsDetectorDefs::NOISE_TRIMMING; break; + case 1: trimmingMode = slsDetectorDefs::IMPROVE_TRIMMING; break; + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qTabAdvanced::validateBeforeTrimming(){ +#ifdef VERBOSE + cout << "Validating conditions before Trimming" << endl; +#endif + char temp[100]; + string message = "All conditions satisfied for Trimming.
"; + switch(detType){ + case slsDetectorDefs::MYTHEN: + + //dynamic range + if(myDet->setDynamicRange(-1) != TRIMMING_DYNAMIC_RANGE){ + sprintf(temp,"%d",TRIMMING_DYNAMIC_RANGE); + if(myDet->setDynamicRange(TRIMMING_DYNAMIC_RANGE) != TRIMMING_DYNAMIC_RANGE){ + qDefs::Message(qDefs::WARNING, + string("Trimming Pre-condition not satisfied:
" + "Could not set dynamic range to ") + string(temp)+string(".
" + "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); + return slsDetectorDefs::FAIL; + }else + message.append(string("Dynamic Range has been changed to ") + string(temp) + string(".
")); + } + //frames + if((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1) != TRIMMING_FRAME_NUMBER){ + sprintf(temp,"%d",TRIMMING_FRAME_NUMBER); + if((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,TRIMMING_FRAME_NUMBER) != TRIMMING_FRAME_NUMBER){ + qDefs::Message(qDefs::WARNING, + string("
Trimming Pre-condition not satisfied:
" + "Could not set Number of Frames to ") + string(temp)+string(".
" + "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); + return slsDetectorDefs::FAIL; + }else + message.append(string("Number of Frames has been changed to ") + string(temp) + string(".
")); + } + //trigger + if((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1) != TRIMMING_TRIGGER_NUMBER){ + sprintf(temp,"%d",TRIMMING_TRIGGER_NUMBER); + if((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,TRIMMING_TRIGGER_NUMBER) != TRIMMING_TRIGGER_NUMBER){ + qDefs::Message(qDefs::WARNING, + string("
Trimming Pre-condition not satisfied:
" + "Could not set Number of Triggers to ") + string(temp)+string(".
" + "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); + return slsDetectorDefs::FAIL; + }else + message.append(string("Number of Triggers has been changed to ") + string(temp) + string(".
")); + } + //probes + if((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1) != TRIMMING_PROBE_NUMBER){ + sprintf(temp,"%d",TRIMMING_PROBE_NUMBER); + if((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,TRIMMING_PROBE_NUMBER) != TRIMMING_PROBE_NUMBER){ + qDefs::Message(qDefs::WARNING, + string("
Trimming Pre-condition not satisfied:
" + "Could not set Number of Probes to ") + string(temp)+string(".
" + "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); + return slsDetectorDefs::FAIL; + }else + message.append(string("Number of Probes has been changed to ") + string(temp) + string(".
")); + } + //Setting + if(myDet->getSettings() == slsDetectorDefs::UNINITIALIZED){ + if(qDefs::Message(qDefs::QUESTION, + string("
Trimming Pre-condition not satisfied:
")+ + string("Settings cannot be Uninitialized to start Trimming.
" + "Change it to Standard and proceed?"),"qTabAdvanced::validateBeforeTrimming") == slsDetectorDefs::FAIL){ + qDefs::Message(qDefs::INFORMATION, + "Please change the Settings in the Settings tab to your choice.
" + "Aborting Trimming.","qTabAdvanced::validateBeforeTrimming"); + return slsDetectorDefs::FAIL; + } + //user asked to change settings to standard + else{ + if((int)myDet->setSettings(slsDetectorDefs::STANDARD) != slsDetectorDefs::STANDARD){ + qDefs::Message(qDefs::WARNING, + string("Trimming Pre-condition not satisfied:
" + "Could not change Settings to Standard
" + "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); + return slsDetectorDefs::FAIL; + }else + message.append(string("Settings has been changed to Standard.
")); + } + } + break; + default: + return slsDetectorDefs::FAIL; + + } + + message.append("
Initiating Trimming..."); + qDefs::Message(qDefs::INFORMATION,message,"qTabAdvanced::validateBeforeTrimming"); + return slsDetectorDefs::OK; + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::StartTrimming(){ + //check a few conditions before trimming + if(validateBeforeTrimming() == slsDetectorDefs::FAIL) + return; + +#ifdef VERBOSE + cout << "Starting Trimming" << endl; +#endif + int parameter1=0, parameter2=0; + //optimize + bool optimize = chkOptimize->isChecked(); + + //set the mode again and also set resolution, counts + switch(trimmingMode){ + + case slsDetectorDefs::NOISE_TRIMMING: + //define parameters + parameter1 = spinCounts->value(); + parameter2 = spinResolution->value(); + if(!optimize){ + parameter2 = -1; + trimmingMode = slsDetectorDefs::FIXEDSETTINGS_TRIMMING; +#ifdef VERBOSE + cout << "Trimming Mode: FIXEDSETTINGS_TRIMMING" << endl; +#endif + }else{ +#ifdef VERBOSE + cout << "Trimming Mode: NOISE_TRIMMING" << endl; +#endif + } + break; + + case slsDetectorDefs::IMPROVE_TRIMMING: +#ifdef VERBOSE + cout << "Trimming Mode: IMPROVE_TRIMMING" << endl; +#endif + //define parameters + parameter1 = spinResolution->value(); + parameter2 = 1; + if(!optimize) parameter2 = 0; + break; + default: + cout << "Should never come here. Start Trimming will have only 2 methods. Trimming Method:" << trimmingMode << endl; + return; + } + + //execute + int ret = myDet->executeTrimming(trimmingMode,parameter1,parameter2,-1); + + if((ret!=slsDetectorDefs::FAIL)&&(ret!=-1)); + else + qDefs::Message(qDefs::WARNING,"Atleast 1 channel could not be trimmed.","qTabAdvanced::StartTrimming"); + //save trim file + ret = myDet->saveSettingsFile(string(dispFile->text().toAscii().constData()),-1); + if((ret!=slsDetectorDefs::FAIL)&&(ret!=-1)){ + qDefs::Message(qDefs::INFORMATION,"The Trimbits have been saved successfully.","qTabAdvanced::StartTrimming"); + //updates plots + myPlot->UpdateTrimbitPlot(false,radioHistogram->isChecked()); + } + else qDefs::Message(qDefs::WARNING,string("Could not Save the Trimbits to file:\n")+dispFile->text().toAscii().constData(),"qTabAdvanced::StartTrimming"); + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::StartTrimming"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::UpdateTrimbitPlot(int id){ + if(boxPlot->isChecked()){ + //refresh + if(!id) myPlot->UpdateTrimbitPlot(false,radioHistogram->isChecked()); + //from detector + else myPlot->UpdateTrimbitPlot(true,radioHistogram->isChecked()); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetControlPort(int port){ +#ifdef VERBOSE + cout << "Setting Control Port:" << port << endl; +#endif + disconnect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); + spinControlPort->setValue(det->setPort(slsDetectorDefs::CONTROL_PORT,port)); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetControlPort"); + connect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetStopPort(int port){ +#ifdef VERBOSE + cout << "Setting Stop Port:" << port << endl; +#endif + disconnect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); + spinStopPort->setValue(det->setPort(slsDetectorDefs::STOP_PORT,port)); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetStopPort"); + connect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetRxrTCPPort(int port){ +#ifdef VERBOSE + cout << "Setting Receiver TCP Port:" << port << endl; +#endif + disconnect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); + spinTCPPort->setValue(det->setPort(slsDetectorDefs::DATA_PORT,port)); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetRxrTCPPort"); + connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetRxrUDPPort(int port){ +#ifdef VERBOSE + cout << "Setting Receiver UDP Port:" << port << endl; +#endif + + disconnect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); + spinUDPPort->setValue(det->setReceiverUDPPort(port)); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetRxrUDPPort"); + connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetReceiverOnline(int index){ +#ifdef VERBOSE + cout << "Setting Reciever Online to :" << index << endl; +#endif + disconnect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + if(index) + SetReceiver(); + else + comboRxrOnline->setCurrentIndex(det->setReceiverOnline(index)); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetReceiverOnline"); + connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + //highlight in red if offline + if(!comboRxrOnline->currentIndex()){ + comboRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setPalette(red); + lblRxrOnline->setText("Online:*"); + }else{ + comboRxrOnline->setToolTip(rxrOnlineTip); + lblRxrOnline->setToolTip(rxrOnlineTip); + lblRxrOnline->setPalette(lblHostname->palette()); + lblRxrOnline->setText("Online:"); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetOnline(int index){ +#ifdef VERBOSE + cout << "Setting Detector Online to " << index << endl; +#endif + disconnect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); + comboOnline->setCurrentIndex(det->setOnline(index)); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetOnline"); + connect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); + //highlight in red if offline + if(!comboOnline->currentIndex()){ + comboOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setPalette(red); + lblOnline->setText("Online:*"); + }else{ + comboOnline->setToolTip(detOnlineTip); + lblOnline->setToolTip(detOnlineTip); + lblOnline->setPalette(lblHostname->palette()); + lblOnline->setText("Online:"); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetNetworkParameters(){ +#ifdef VERBOSE + cout << "Setting Network Parametrs" << endl; +#endif + disconnect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + + dispIP->setText(QString(det->setDetectorIP(dispIP->text().toAscii().constData()))); + dispMAC->setText(QString(det->setDetectorMAC(dispMAC->text().toAscii().constData()))); + dispUDPIP->setText(QString(det->setReceiverUDPIP(dispUDPIP->text().toAscii().constData()))); + dispUDPMAC->setText(QString(det->setReceiverUDPMAC(dispUDPMAC->text().toAscii().constData()))); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetNetworkParameters"); + + connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetReceiver(){ +#ifdef VERBOSE + cout << "Setting Receiver" << endl; +#endif + string outdir = myDet->getFilePath(); + dispRxrHostname->setText(QString(det->setReceiver(dispRxrHostname->text().toAscii().constData()))); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetReceiver"); + det->setFilePath(outdir); + qDefs::checkErrorMessage(det,"qTabAdvanced::SetReceiver"); + Refresh(); +} + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::updateROIList(){ +#ifdef VERYVERBOSE + cout<<"in updateROIList() " << endl; +#endif + clearROI(); + + int n,i; + slsDetectorDefs::ROI* temp = myDet->getROI(n); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::updateROIList"); + + if((temp!=NULL)&&(n>0)){ + //assign into array, else it loses values cuz of memory + slsDetectorDefs::ROI allroi[n]; + for(i=0;isetValue(allroi[i].xmin); + spinFromY[i]->setValue(allroi[i].ymin); + spinToX[i]->setValue(allroi[i].xmax); + spinToY[i]->setValue(allroi[i].ymax); + } + cout << "ROIs populated: " << n << endl; + } + + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::AddROIInput(int num){ +#ifdef VERVERBOSE + cout<<"in AddROIInput() " << num << endl; +#endif + if((int)lblFromX.size()){ + disconnect(spinFromX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + disconnect(spinFromY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + disconnect(spinToX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + disconnect(spinToY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + } + + int exists = numRois+1; + int total = exists+num; + //if cleared, addding just one + if ((num==0) && (numRois==0)){ + exists = 0; + total = 1; + }/*else{ + gridRoi->removeWidget + }*/ + + for (int i=exists;i= ((int)lblFromX.size())){ + lblFromX.resize(i+1); spinFromX.resize(i+1); + lblFromY.resize(i+1); spinFromY.resize(i+1); + lblToX.resize(i+1); spinToX.resize(i+1); + lblToY.resize(i+1); spinToY.resize(i+1); + + lblFromX[i] = new QLabel("x min:"); + lblFromY[i] = new QLabel("y min:"); + lblToX[i] = new QLabel("x max:"); + lblToY[i] = new QLabel("y max:"); + spinFromX[i] = new QSpinBox(); + spinFromY[i] = new QSpinBox(); + spinToX[i] = new QSpinBox(); + spinToY[i] = new QSpinBox(); + + + lblFromX[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); lblFromX[i]->setFixedWidth(50); + lblFromY[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); lblFromY[i]->setFixedWidth(50); + lblToX[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); lblToX[i]->setFixedWidth(50); + lblToY[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); lblToY[i]->setFixedWidth(50); + spinFromX[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); spinFromX[i]->setFixedWidth(80); + spinFromY[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); spinFromY[i]->setFixedWidth(80); + spinToX[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); spinToX[i]->setFixedWidth(80); + spinToY[i]->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); spinToY[i]->setFixedWidth(80); + spinFromX[i]->setFixedHeight(19); + spinFromY[i]->setFixedHeight(19); + spinToX[i]->setFixedHeight(19); + spinToY[i]->setFixedHeight(19); + + spinFromX[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::X)-1); + spinToX[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::X)-1); + spinFromY[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::Y)-1); + spinToY[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::Y)-1); + spinFromX[i]->setMinimum(-1); + spinToX[i]->setMinimum(-1); + spinFromY[i]->setMinimum(-1); + spinToY[i]->setMinimum(-1); + spinFromX[i]->setValue(-1); + spinFromY[i]->setValue(-1); + spinToX[i]->setValue(-1); + spinToY[i]->setValue(-1); + } + + gridRoi->addWidget(lblFromX[i], i,0,Qt::AlignTop); + gridRoi->addWidget(spinFromX[i],i,1,Qt::AlignTop); + gridRoi->addItem(new QSpacerItem(40,20,QSizePolicy::Expanding,QSizePolicy::Fixed), i,2,Qt::AlignTop); + gridRoi->addWidget(lblToX[i], i,3,Qt::AlignTop); + gridRoi->addWidget(spinToX[i], i,4,Qt::AlignTop); + gridRoi->addItem(new QSpacerItem(40,20,QSizePolicy::Expanding,QSizePolicy::Fixed), i,5,Qt::AlignTop); + gridRoi->addWidget(lblFromY[i], i,6,Qt::AlignTop); + gridRoi->addWidget(spinFromY[i],i,7,Qt::AlignTop); + gridRoi->addItem(new QSpacerItem(40,20,QSizePolicy::Expanding,QSizePolicy::Fixed), i,8,Qt::AlignTop); + gridRoi->addWidget(lblToY[i], i,9,Qt::AlignTop); + gridRoi->addWidget(spinToY[i], i,10,Qt::AlignTop); + + lblFromX[i]->show(); + spinFromX[i]->show(); + lblToX[i]->show(); + spinToX[i]->show(); + lblFromY[i]->show(); + spinFromY[i]->show(); + lblToY[i]->show(); + spinToY[i]->show(); + } + + numRois += num; + + connect(spinFromX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + connect(spinFromY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + connect(spinToX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + connect(spinToY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + +#ifdef VERYVERBOSE + cout<<"ROI Inputs added " << num << endl; +#endif + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::AddROIInput"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::clearROI(){ +#ifdef VERYVERBOSE + cout<<"in clearROI() " << endl; +#endif + if((int)lblFromX.size()){ + disconnect(spinFromX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + disconnect(spinFromY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + disconnect(spinToX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + disconnect(spinToY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); + + } + + + for (int i=0;isetValue(-1); + spinFromY[i]->setValue(-1); + spinToX[i]->setValue(-1); + spinToY[i]->setValue(-1); + } + + + //hide widget because they are still visible even when removed and layout deleted + QLayoutItem *item; + while((item = gridRoi->takeAt(0))) { + if (item->widget()){ + item->widget()->hide(); + gridRoi->removeWidget(item->widget()); + } + //if (item->spacerItem()) + } + + numRois = 0; + AddROIInput(0); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::setROI(){ +#ifdef VERYVERBOSE + cout<<"in setROI() " << endl; +#endif + + slsDetectorDefs::ROI allroi[MAX_ROIS]; + + for (int i=0;ivalue(); + allroi[i].ymin = spinFromY[i]->value(); + allroi[i].xmax = spinToX[i]->value(); + allroi[i].ymax = spinToY[i]->value(); + } + + myDet->setROI(numRois,allroi); + //qDefs::checkErrorMessage(myDet); + cout<<"ROIs set" << endl; + //get the correct list back + updateROIList(); + //configuremac + myDet->configureMAC(); + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::setROI"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::clearROIinDetector(){ +#ifdef VERYVERBOSE + cout<<"in clearROIinDetector() " << endl; +#endif + + if (QMessageBox::warning(this, "Clear ROI", + "Are you sure you want to clear all the ROI in detector?", + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes){ + + clearROI(); + setROI(); +#ifdef VERBOSE + cout << "ROIs cleared" << endl; +#endif + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetDetector(int index){ +#ifdef VERYVERBOSE + cout<<"in SetDetector: " << index << endl; +#endif + det = myDet->getSlsDetector(comboDetector->currentIndex()); + + + spinControlPort->setValue(det->getControlPort()); + spinStopPort->setValue(det->getStopPort()); + spinTCPPort->setValue(det->getReceiverPort()); + spinUDPPort->setValue(atoi(det->getReceiverUDPPort())); + + dispIP->setText(det->getDetectorIP()); + dispMAC->setText(det->getDetectorMAC()); + dispRxrHostname->setText(det->getReceiver()); + dispUDPIP->setText(det->getReceiverUDPIP()); + dispUDPMAC->setText(det->getReceiverUDPMAC()); + + + //check if its online and set it to red if offline + if(det->setOnline()==slsDetectorDefs::ONLINE_FLAG) + det->checkOnline(); + if(det->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) + det->checkReceiverOnline(); + comboOnline->setCurrentIndex(det->setOnline()); + comboRxrOnline->setCurrentIndex(det->setReceiverOnline()); + //highlight in red if detector or receiver is offline + if(!comboOnline->currentIndex()){ + comboOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setPalette(red); + lblOnline->setText("Online:*"); + }else{ + comboOnline->setToolTip(detOnlineTip); + lblOnline->setToolTip(detOnlineTip); + lblOnline->setPalette(lblHostname->palette()); + lblOnline->setText("Online:"); + } + if(comboRxrOnline->isEnabled()){ + if(!comboRxrOnline->currentIndex()){ + comboRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setPalette(red); + lblRxrOnline->setText("Online:*"); + }else{ + comboRxrOnline->setToolTip(rxrOnlineTip); + lblRxrOnline->setToolTip(rxrOnlineTip); + lblRxrOnline->setPalette(lblHostname->palette()); + lblRxrOnline->setText("Online:"); + } + } + + qDefs::checkErrorMessage(det,"qTabAdvanced::SetDetector"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::SetAllTrimbits(){ +#ifdef VERBOSE + cout<<"Set all trimbits to " << spinSetAllTrimbits->value() << endl; +#endif + myDet->setAllTrimbits(spinSetAllTrimbits->value()); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetAllTrimbits"); + updateAllTrimbitsFromServer(); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::updateAllTrimbitsFromServer(){ +#ifdef VERBOSE + cout<<"Getting all trimbits value" << endl; +#endif + disconnect(spinSetAllTrimbits, SIGNAL(editingFinished()), this, SLOT(SetAllTrimbits())); + + int ret = myDet->setAllTrimbits(-1); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::updateAllTrimbitsFromServer"); + if(ret<0){ + qDefs::Message(qDefs::WARNING,"Inconsistent value from alltrimbits value.\n" + "Setting it for all detectors involved to 0.","qTabAdvanced::updateAllTrimbitsFromServer"); + //set to default + spinSetAllTrimbits->setValue(0); + myDet->setAllTrimbits(0); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::updateAllTrimbitsFromServer"); + }else + spinSetAllTrimbits->setValue(ret); + + connect(spinSetAllTrimbits, SIGNAL(editingFinished()), this, SLOT(SetAllTrimbits())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabAdvanced::Refresh(){ + + +#ifdef VERBOSE + cout << endl << "**Updating Advanced Tab" << endl; +#endif + //setting color of tab + //void setTabBar ( QTabBar * tb ) + //QTabBar * tabBar () const + /* + for(int i=0;itabBar()->setTabTextColor(i,defaultTabColor); + tabAdvancedSettings->tabBar()->setTabTextColor(index,QColor(0,0,200,255)); + */ + + if(isAngular){ +#ifdef VERBOSE + cout << "Angular Calibration Log set to " << chkAngularLog->isChecked() << endl; +#endif + + disconnect(chkAngularLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); + + chkAngularLog->setChecked(myDet->getActionMode(slsDetectorDefs::angCalLog)); + + connect(chkAngularLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); + } + + + if(isEnergy){ + //disconnect + disconnect(chkEnergyLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); + disconnect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(SetExposureTime())); + disconnect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetExposureTime())); + disconnect(spinThreshold, SIGNAL(valueChanged(double)), this, SLOT(SetThreshold())); + + + //energy/angular logs + chkEnergyLog->setChecked(myDet->getActionMode(slsDetectorDefs::enCalLog)); +#ifdef VERBOSE + cout << "Energy Calibration Log set to " << chkEnergyLog->isChecked() << endl; +#endif + + + //exptime + qDefs::timeUnit unit; + double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-9)))); +#ifdef VERBOSE + cout << "Getting acquisition time : " << time << qDefs::getUnitString(unit) << endl; +#endif + spinExpTime->setValue(time); + comboExpUnit->setCurrentIndex((int)unit); + + + //threshold + double threshold = (double)myDet->setDAC(-1,slsDetectorDefs::THRESHOLD,0); +#ifdef VERBOSE + cout << "Getting Threshold DACu : " << threshold << endl; +#endif + spinThreshold->setValue(threshold); + + + //connect + connect(chkEnergyLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); + connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(SetExposureTime())); + connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetExposureTime())); + connect(spinThreshold, SIGNAL(valueChanged(double)), this, SLOT(SetThreshold())); + } + + + //network + det = myDet->getSlsDetector(comboDetector->currentIndex()); + + qDefs::checkErrorMessage(myDet,"qTabAdvanced::Refresh"); + + + +#ifdef VERBOSE + cout << "Getting Detector Ports" << endl; +#endif + //disconnect + disconnect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); + disconnect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); + disconnect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); + + //so that updated status + if(det->setOnline()==slsDetectorDefs::ONLINE_FLAG) + det->checkOnline(); + comboOnline->setCurrentIndex(det->setOnline()); + spinControlPort->setValue(det->getControlPort()); + spinStopPort->setValue(det->getStopPort()); + + //connect + connect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); + connect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); + connect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); + + +#ifdef VERBOSE + cout << "Getting Receiver Network Information" << endl; +#endif + if ((detType==slsDetectorDefs::GOTTHARD) || + (detType==slsDetectorDefs::MOENCH)|| + (detType==slsDetectorDefs::PROPIX)|| + (detType==slsDetectorDefs::JUNGFRAU)|| + (detType==slsDetectorDefs::EIGER)){ + //disconnect + disconnect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); + disconnect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); + disconnect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + disconnect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); + + dispIP->setText(det->getDetectorIP()); + dispMAC->setText(det->getDetectorMAC()); + + //so that updated status + if(det->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) + det->checkReceiverOnline(); + comboRxrOnline->setCurrentIndex(det->setReceiverOnline()); + + dispRxrHostname->setText(det->getReceiver()); + spinTCPPort->setValue(det->getReceiverPort()); + spinUDPPort->setValue(atoi(det->getReceiverUDPPort())); + + dispUDPIP->setText(det->getReceiverUDPIP()); + dispUDPMAC->setText(det->getReceiverUDPMAC()); + + //connect + connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); + connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); + connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); + + } + + //highlight in red if detector or receiver is offline + if(!comboOnline->currentIndex()){ + comboOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setToolTip(detOnlineTip + errOnlineTip); + lblOnline->setPalette(red); + lblOnline->setText("Online:*"); + }else{ + comboOnline->setToolTip(detOnlineTip); + lblOnline->setToolTip(detOnlineTip); + lblOnline->setPalette(lblHostname->palette()); + lblOnline->setText("Online:"); + } + if(comboRxrOnline->isEnabled()){ + if(!comboRxrOnline->currentIndex()){ + comboRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setToolTip(rxrOnlineTip + errOnlineTip); + lblRxrOnline->setPalette(red); + lblRxrOnline->setText("Online:*"); + }else{ + comboRxrOnline->setToolTip(rxrOnlineTip); + lblRxrOnline->setToolTip(rxrOnlineTip); + lblRxrOnline->setPalette(lblHostname->palette()); + lblRxrOnline->setText("Online:"); + } + } + + //roi +#ifdef VERBOSE + cout << "Getting ROI" << endl; +#endif + updateROIList(); + + //update alltirmbits from server + if(boxSetAllTrimbits->isEnabled()) + updateAllTrimbitsFromServer(); + +#ifdef VERBOSE + cout << "**Updated Advanced Tab" << endl << endl; +#endif + + qDefs::checkErrorMessage(det,"qTabAdvanced::Refresh"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + diff --git a/slsDetectorGui/src/qTabDataOutput.cpp b/slsDetectorGui/src/qTabDataOutput.cpp new file mode 100644 index 0000000000..1f4974e431 --- /dev/null +++ b/slsDetectorGui/src/qTabDataOutput.cpp @@ -0,0 +1,1011 @@ +/* + * qTabDataOutput.cpp + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ +/********************************************************************** + * ********************************************************************/ + +#include "qTabDataOutput.h" +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +// Qt Include Headers +#include +// C++ Include Headers +#include +#include +using namespace std; + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +qTabDataOutput::qTabDataOutput(QWidget *parent,multiSlsDetector*& detector): + QWidget(parent),myDet(detector){ + setupUi(this); + SetupWidgetWindow(); + Refresh(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabDataOutput::~qTabDataOutput(){ + delete myDet; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetupWidgetWindow(){ + // Detector Type + detType=myDet->getDetectorsType(); + widgetEiger->setVisible(false); + + //rate correction - not for charge integrating detectors + if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::EIGER)) + chkRate->setEnabled(true); + + if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::GOTTHARD)) + chkAngular->setEnabled(true); + + if(detType == slsDetectorDefs::EIGER){ + chkRate->setEnabled(true); + chkTenGiga->setEnabled(true); + widgetEiger->setVisible(true); + } + + /** error message **/ + red = QPalette(); + red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + black = QPalette(); + black.setColor(QPalette::Active,QPalette::WindowText,Qt::black); + + red1 = new QPalette(); + red1->setColor(QPalette::Text,Qt::red); + black1 = new QPalette(); + black1->setColor(QPalette::Text,Qt::black); + + flatFieldTip = dispFlatField->toolTip(); + errFlatFieldTip = QString("Flat field corrections.
" + " #flatfield# filename

")+ + QString("" + "Enter a valid file to enable Flat Field."); + outDirTip = boxOutDir->toolTip(); + + + //expert mode is not enabled initially + chkCompression->setEnabled(false); + + Initialization(); + + disconnect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + PopulateDetectors(); + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + + //flat field correction from server +#ifdef VERBOSE + cout << "Getting flat field" << endl; +#endif + UpdateFlatFieldFromServer(); + + + //rate correction - not for charge integrating detectors + if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::EIGER)){ +#ifdef VERBOSE + cout << "Getting rate correction" << endl; +#endif + UpdateRateCorrectionFromServer(); + } + + + //update angular conversion from server + if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::GOTTHARD)){ +#ifdef VERBOSE + cout << "Getting angular conversion" << endl; +#endif + int ang; + if(myDet->getAngularConversion(ang)) + chkAngular->setChecked(true); + emit AngularConversionSignal(chkAngular->isChecked()); + } + + + //discard bad channels from server +#ifdef VERBOSE + cout << "Getting bad channel correction:" << myDet->getBadChannelCorrection() << endl; +#endif + disconnect(chkDiscardBad, SIGNAL(toggled(bool))); + if(myDet->getBadChannelCorrection()) + chkDiscardBad->setChecked(true); + else + chkDiscardBad->setChecked(false); + connect(chkDiscardBad, SIGNAL(toggled(bool)), this, SLOT(DiscardBadChannels())); + +/* + if(detType == slsDetectorDefs::MYTHEN){ + comboDetector->hide(); + } +*/ + qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetupWidgetWindow"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::Initialization(){ + //output dir + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + + + connect(btnOutputBrowse, SIGNAL(clicked()), this, SLOT(browseOutputDir())); + //flat field correction + connect(chkFlatField, SIGNAL(toggled(bool)), this, SLOT(SetFlatField())); + connect(btnFlatField, SIGNAL(clicked()), this, SLOT(BrowseFlatFieldPath())); + //rate correction + connect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); + connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); + + //angular correction + connect(chkAngular, SIGNAL(toggled(bool)), this, SLOT(SetAngularCorrection())); + //discard bad channels + connect(chkDiscardBad, SIGNAL(toggled(bool)), this, SLOT(DiscardBadChannels())); + //compression + connect(chkCompression, SIGNAL(toggled(bool)), this, SLOT(SetCompression(bool))); + //10GbE + connect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); + + //eiger + if(widgetEiger->isVisible()){ + //speed + connect(comboEigerClkDivider,SIGNAL(currentIndexChanged(int)), this, SLOT(setSpeed())); + //flags + connect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(setFlags())); + connect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(setFlags())); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetExpertMode(bool enable){ + if((detType == slsDetectorDefs::GOTTHARD) || (detType == slsDetectorDefs::MOENCH)){ + chkCompression->setEnabled(enable); + GetCompression(); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::browseOutputDir() +{ + QString directory = QFileDialog::getExistingDirectory(this,tr("Choose Output Directory "),dispOutputDir->text()); + if (!directory.isEmpty()) + dispOutputDir->setText(directory); + SetOutputDir(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetFlatField(){ +#ifdef VERYVERBOSE + cout << "Entering Set Flat Field Correction Function" << endl; +#endif + // so that it doesnt call it twice + disconnect(dispFlatField, SIGNAL(editingFinished()), this, SLOT(SetFlatField())); + + //enable/disable + dispFlatField->setEnabled(chkFlatField->isChecked()); + btnFlatField->setEnabled(chkFlatField->isChecked()); + + if(chkFlatField->isChecked()){ + if(dispFlatField->text().isEmpty()){ + chkFlatField->setToolTip(errFlatFieldTip); + dispFlatField->setToolTip(errFlatFieldTip); + chkFlatField->setPalette(red); + chkFlatField->setText("Flat Field File:*"); +#ifdef VERBOSE + cout << "Flat Field File is not set." << endl; +#endif + }else{ + QString fName = dispFlatField->text(); + QString file = fName.section('/',-1); + QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); + + chkFlatField->setToolTip(flatFieldTip); + dispFlatField->setToolTip(flatFieldTip); + chkFlatField->setPalette(chkDiscardBad->palette()); + chkFlatField->setText("Flat Field File:"); + //set ff dir + myDet->setFlatFieldCorrectionDir(dir.toAscii().constData()); + //set ff file and catch error if -1 + if(myDet->setFlatFieldCorrectionFile(file.toAscii().constData())<0){ + string sDir = dir.toAscii().constData(),sFile = file.toAscii().constData(); + if(sDir.length()<1) {sDir = string(QDir::current().absolutePath().toAscii().constData()); /*"/home/";*/} + qDefs::Message(qDefs::WARNING,"Invalid Flat Field file: "+sDir+"/"+sFile+ + ".\nUnsetting Flat Field.","qTabDataOutput::SetFlatField"); + + //Unsetting flat field + myDet->setFlatFieldCorrectionFile(""); + dispFlatField->setText(""); + chkFlatField->setToolTip(errFlatFieldTip); + dispFlatField->setToolTip(errFlatFieldTip); + chkFlatField->setPalette(red); + chkFlatField->setText("Flat Field File:*"); +#ifdef VERBOSE + cout << "Invalid Flat Field File - "<< sDir << sFile << ". Unsetting Flat Field." << endl; +#endif + } + else{ +#ifdef VERBOSE + cout << "Setting flat field file to "<< dispFlatField->text().toAscii().constData() << endl; +#endif + } + } + }else{ + chkFlatField->setToolTip(flatFieldTip); + dispFlatField->setToolTip(flatFieldTip); + chkFlatField->setPalette(chkDiscardBad->palette()); + chkFlatField->setText("Flat Field File:"); + //Unsetting flat field + myDet->setFlatFieldCorrectionFile(""); + dispFlatField->setText(""); +#ifdef VERBOSE + cout << "Unsetting flat field correction file" << endl; +#endif + } + + connect(dispFlatField,SIGNAL(editingFinished()),this,SLOT(SetFlatField())); + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetFlatField"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabDataOutput::UpdateFlatFieldFromServer(){ + disconnect(dispFlatField, SIGNAL(editingFinished()), this, SLOT(SetFlatField())); + + dispFlatField->setText(QString(myDet->getFlatFieldCorrectionDir().c_str())+"/"+QString(myDet->getFlatFieldCorrectionFile().c_str())); +#ifdef VERBOSE + cout << "Getting flat field correction file" << dispFlatField->text().toAscii().constData() << endl; +#endif + //calls setflatfield to ensure the file still exists or disable it + if(!QString(myDet->getFlatFieldCorrectionFile().c_str()).compare("none")){ + dispFlatField->setText(""); + chkFlatField->setChecked(false); +#ifdef VERBOSE + cout << "Flat Field is not set." << endl; +#endif + } + else + chkFlatField->setChecked(true); + + chkFlatField->setToolTip(flatFieldTip); + dispFlatField->setToolTip(flatFieldTip); + chkFlatField->setPalette(chkDiscardBad->palette()); + chkFlatField->setText("Flat Field File:"); + + connect(dispFlatField, SIGNAL(editingFinished()), this, SLOT(SetFlatField())); + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::UpdateFlatFieldFromServer"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabDataOutput::BrowseFlatFieldPath(){ + QString fName = dispFlatField->text(); + QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); + if(dir.isEmpty()) dir = QString(myDet->getFlatFieldCorrectionDir().c_str());/*"/home/";*/ + fName = QFileDialog::getOpenFileName(this, + tr("Load Flat Field Correction File"),dir, + tr("Data Files(*.raw *.dat);; All Files (*.*)"),0,QFileDialog::ShowDirsOnly); + if (!fName.isEmpty()){ + dispFlatField->setText(fName); + SetFlatField(); + } + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::BrowseFlatFieldPath"); + +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetRateCorrection(int deadtime){ + disconnect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + disconnect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); + +#ifdef VERBOSE + cout << "Entering Set Rate Correction function" << endl; +#endif + + if(chkRate->isChecked()){ + if(!btnDefaultRate->isEnabled()){ + btnDefaultRate->setEnabled(true); + lblDeadTime->setEnabled(true); + spinDeadTime->setEnabled(true); + } + + if(deadtime!=-1){ + deadtime = (double)spinDeadTime->value(); +#ifdef VERBOSE + cout << "Setting rate corrections with custom dead time: " << deadtime << endl; +#endif + }else{; +#ifdef VERBOSE + cout << "Setting rate corrections with default dead time" << endl; +#endif + } + myDet->setRateCorrection(deadtime); + + }//unsetting rate correction + else{ + btnDefaultRate->setEnabled(false); + lblDeadTime->setEnabled(false); + spinDeadTime->setEnabled(false); + myDet->setRateCorrection(0); +#ifdef VERBOSE + cout << "Unsetting rate correction" << endl; +#endif + } + qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetRateCorrection"); + + //update just the value + double rate = (double)myDet->getRateCorrectionTau(); + spinDeadTime->setValue((double)rate); + if(rate == -1){ + qDefs::Message(qDefs::WARNING,"Dead time is inconsistent for all detectors. Returned Value: -1.","qTabDataOutput::UpdateRateCorrectionFromServer"); + QString errorTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

")+ + QString("" + "Dead time is inconsistent for all detectors."); + chkRate->setToolTip(errorTip); + spinDeadTime->setToolTip(errorTip); + chkRate->setPalette(red); + chkRate->setText("Rate:*"); + }else{ + QString normalTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

"); + chkRate->setToolTip(normalTip); + spinDeadTime->setToolTip(normalTip); + chkRate->setPalette(chkDiscardBad->palette()); + chkRate->setText("Rate:"); + } + + connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetDefaultRateCorrection(){ + SetRateCorrection(-1); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::UpdateRateCorrectionFromServer(){ + disconnect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); + disconnect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + disconnect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); + + double rate; + rate = (double)myDet->getRateCorrectionTau(); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::UpdateRateCorrectionFromServer"); +#ifdef VERBOSE + cout << "Getting rate correction from server: " << rate << endl; +#endif + if(rate==0){ + chkRate->setChecked(false); + btnDefaultRate->setEnabled(false); + lblDeadTime->setEnabled(false); + spinDeadTime->setEnabled(false); + } + + else{ + chkRate->setChecked(true); + btnDefaultRate->setEnabled(true); + lblDeadTime->setEnabled(true); + spinDeadTime->setEnabled(true); + spinDeadTime->setValue((double)rate); + } + + if(rate == -1){ + qDefs::Message(qDefs::WARNING,"Dead time is inconsistent for all detectors. Returned Value: -1.","qTabDataOutput::UpdateRateCorrectionFromServer"); + QString errorTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

")+ + QString("" + "Dead time is inconsistent for all detectors."); + chkRate->setToolTip(errorTip); + spinDeadTime->setToolTip(errorTip); + chkRate->setPalette(red); + chkRate->setText("Rate:*"); + }else{ + QString normalTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

"); + chkRate->setToolTip(normalTip); + spinDeadTime->setToolTip(normalTip); + chkRate->setPalette(chkDiscardBad->palette()); + chkRate->setText("Rate:"); + } + + connect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); + connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetAngularCorrection(){ + disconnect(chkAngular, SIGNAL(toggled(bool)), this, SLOT(SetAngularCorrection())); +#ifdef VERYVERBOSE + cout << "Entering Set Angular Correction function" << endl; +#endif + bool enabled = chkAngular->isChecked(); + //set + if(myDet->setAngularCorrectionMask(enabled) == enabled){ +#ifdef VERBOSE + cout << "Angular Conversion mask:" << enabled << endl; +#endif + } + //error + else{ +#ifdef VERBOSE + cout << "Could not set angular conversion to default" << endl; +#endif + qDefs::Message(qDefs::WARNING,"Angular Conversion could not be set/reset. Please set the default file name using the command line, if you want to set it.","qTabDataOutput::SetAngularCorrection"); + chkAngular->setChecked(!enabled); + } + + emit AngularConversionSignal(chkAngular->isChecked()); + connect(chkAngular, SIGNAL(toggled(bool)), this, SLOT(SetAngularCorrection())); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetAngularCorrection"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::DiscardBadChannels(){ +#ifdef VERBOSE + cout << "Entering Discard bad channels function" << endl; +#endif + if(chkDiscardBad->isChecked()){ +#ifdef VERBOSE + cout << "Setting bad channel correction to default" << endl; +#endif + myDet->setBadChannelCorrection("default"); + }else{ +#ifdef VERBOSE + cout << "Unsetting bad channel correction" << endl; +#endif + myDet->setBadChannelCorrection(""); + } + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::DiscardBadChannels"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::PopulateDetectors(){ +#ifdef VERBOSE + cout << "Populating detectors" << endl; +#endif + comboDetector->clear(); + comboDetector->addItem("All"); + boxOutDir->setTitle("Output Directory"); + //add specific detector options only if more than 1 detector + if(myDet->getNumberOfDetectors()>1){ + for(int i=0;igetNumberOfDetectors();i++) + comboDetector->addItem(QString(myDet->getHostname(i).c_str())); + } + GetOutputDir(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::GetOutputDir(){ +#ifdef VERBOSE + cout << "Getting output directory" << endl; +#endif + //all + if(!comboDetector->currentIndex()) + dispReadOutputDir->setText(QString(myDet->getFilePath().c_str())); + + //specific + else{ + slsDetector *det = myDet->getSlsDetector(comboDetector->currentIndex()-1); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::GetOutputDir"); + dispReadOutputDir->setText(QString(det->getFilePath().c_str())); + } + + + VerifyOutputDirectory(); + + //clear field to write + disconnect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + dispOutputDir->setText(""); + dispOutputDir->setPalette(*black1); + connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +int qTabDataOutput::VerifyOutputDirectory(){ +#ifdef VERBOSE + cout << "Verifying output directory" << endl; +#endif + bool error = false; + QString errTip = outDirTip; + string path = ""; + string inputpath = string(dispReadOutputDir->text().toAscii().constData()); + string detName = ""; + string mess = ""; + + //for each detector + for(int i=0;igetNumberOfDetectors();i++){ + slsDetector *det = myDet->getSlsDetector(i); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::VerifyOutputDirectory"); + detName = string("\n - ") + string(comboDetector->itemText(i+1).toAscii().constData()); + if(!comboDetector->currentIndex()) + path = inputpath; + else + path = det->getFilePath(); + + //verify if specific outdir works for each det + if(det->setFilePath(path).empty()){ + mess. append(detName); + error = true; + }else if(!qDefs::checkErrorMessage(det,"qTabDataOutput::VerifyOutputDirectory",false).empty()){ + mess. append(detName); + error = true; + } + /* + //verify all paths are the same for no receiver + if ((!receiver) && (path != det->getFilePath())){ + error = true; + qDefs::Message(qDefs::WARNING,string("Enter a valid output directory ") + detName,"Data Output Verify"); + }*/ + //myDet->setFilePath(det->getFilePath()); + } + + + //set the read output dir text anyway + //specific + if(comboDetector->currentIndex()) + path = myDet->getSlsDetector(comboDetector->currentIndex()-1)->getFilePath(); + //all + else + path = myDet->getFilePath(); + dispReadOutputDir->setText(QString(path.c_str())); + + + //if error, display in red + if(error){ +#ifdef VERBOSE + cout << "The output path doesnt exist anymore" << endl; +#endif + qDefs::Message(qDefs::WARNING,string("Invalid Output Directory ")+ mess ,"qTabDataOutput::VerifyOutputDirectory"); + dispReadOutputDir->setPalette(*red1); + boxOutDir->setPalette(red); + + //replace all \n with
+ size_t pos = 0; + while((pos = mess.find("\n", pos)) != string::npos){ + mess.replace(pos, 1, "
"); + pos += 1; + } + errTip = errTip + + QString("
" + "Invalid Output Directory") + QString(mess.c_str()) + + QString( "."); + boxOutDir->setToolTip(errTip); + boxOutDir->setTitle("Output Directory*"); + + return slsDetectorDefs::FAIL; + } + + //no error + else{ +#ifdef VERBOSE + cout << "The output path has been verified" << endl; +#endif + dispReadOutputDir->setPalette(*black1); + boxOutDir->setPalette(black); + boxOutDir->setToolTip(outDirTip); + boxOutDir->setTitle("Output Directory"); + } + + return slsDetectorDefs::OK; + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetOutputDir(){ + +#ifdef VERBOSE + cout << "Setting output directory" << endl; +#endif + + bool error = false; + QString path = dispOutputDir->text(); + + if(path.isEmpty()) + return; + + disconnect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + + + //gets rid of the end '/'s + while(path.endsWith('/')) path.chop(1); + dispOutputDir->setText(path); + + //specific + if(comboDetector->currentIndex()){ + slsDetector *det = myDet->getSlsDetector(comboDetector->currentIndex()-1); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetOutputDir"); + det->setFilePath(string(dispOutputDir->text().toAscii().constData())); + //if error, set it to what it was set before + if(!qDefs::checkErrorMessage(det,"qTabDataOutput::SetOutputDir").empty()){ +#ifdef VERBOSE + cout << "The output path could not be set" << endl; +#endif + det->setFilePath(string(dispReadOutputDir->text().toAscii().constData())); + dispReadOutputDir->setText(QString(det->getFilePath().c_str())); + error = true; + } + } + + + else{ + if(myDet->setFilePath(string(path.toAscii().constData())).empty()) + error = true; + else if(!qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetOutputDir").empty()) + error = true; + myDet->setFilePath(string(dispReadOutputDir->text().toAscii().constData())); + dispReadOutputDir->setText(QString(myDet->getFilePath().c_str())); + } + + + + if(error){ +#ifdef VERBOSE + cout << "The output path could not be set" << endl; +#endif + dispOutputDir->setPalette(*red1); + } + else{ +#ifdef VERBOSE + cout << "The output path has been modified" << endl; +#endif + dispOutputDir->setPalette(*black1); + dispReadOutputDir->setText(dispOutputDir->text()); + dispOutputDir->setText(""); + //VerifyOutputDirectory(); + } + + + connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::GetCompression(){ + disconnect(chkCompression, SIGNAL(toggled(bool)), this, SLOT(SetCompression(bool))); + int ret = myDet->enableReceiverCompression(); + if(ret > 0) chkCompression->setChecked(true); + else chkCompression->setChecked(false); + connect(chkCompression, SIGNAL(toggled(bool)), this, SLOT(SetCompression(bool))); + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::GetCompression"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::SetCompression(bool enable){ + disconnect(chkCompression, SIGNAL(toggled(bool)), this, SLOT(SetCompression(bool))); + int ret = myDet->enableReceiverCompression(enable); + if(ret > 0) chkCompression->setChecked(true); + else chkCompression->setChecked(false); + connect(chkCompression, SIGNAL(toggled(bool)), this, SLOT(SetCompression(bool))); + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetCompression"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::EnableTenGigabitEthernet(bool enable,int get){ +#ifdef VERBOSE + cout << endl << "Enabling/Disabling 10GbE" << endl; +#endif + disconnect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); + int ret; + if(get) + ret = myDet->enableTenGigabitEthernet(-1); + else + ret = myDet->enableTenGigabitEthernet(enable); + if(ret > 0) chkTenGiga->setChecked(true); + else chkTenGiga->setChecked(false); + connect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::EnableTenGigabitEthernet"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::setSpeed(){ +#ifdef VERBOSE + cout << endl << "Setting Speed" << endl; +#endif + if(widgetEiger->isVisible()){ + myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER,comboEigerClkDivider->currentIndex()); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::setSpeed"); + updateSpeedFromServer(); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::setFlags(){ +#ifdef VERBOSE + cout << endl << "Setting Readout Flags" << endl; +#endif + slsDetectorDefs::readOutFlags val = slsDetectorDefs::GET_READOUT_FLAGS; + if(widgetEiger->isVisible()){ + + //set to continous or storeinram + switch(comboEigerFlags1->currentIndex()){ + case Storeinram: val = slsDetectorDefs::STORE_IN_RAM; break; + default: val = slsDetectorDefs::CONTINOUS_RO; break; + } + myDet->setReadOutFlags(val); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::setFlags"); + + //set to parallel, nonparallel or safe + switch(comboEigerFlags2->currentIndex()){ + case Parallel: val = slsDetectorDefs::PARALLEL; break; + case Safe: val = slsDetectorDefs::SAFE; break; + default: val = slsDetectorDefs::NONPARALLEL; break; + } + myDet->setReadOutFlags(val); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::setFlags"); + + //update flags + updateFlagsFromServer(); + } + +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::updateSpeedFromServer(){ + int ret; + if(widgetEiger->isVisible()){ + disconnect(comboEigerClkDivider, SIGNAL(currentIndexChanged(int)), this, SLOT(setSpeed())); + + //get speed + ret = myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER, -1); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateSpeedFromServer"); + + //valid speed + if(ret >= 0 && ret < NumberofSpeeds) + comboEigerClkDivider->setCurrentIndex(ret); + + //invalid speed + else{ + qDefs::Message(qDefs::WARNING,"Inconsistent value from clock divider.\n" + "Setting it for all detectors involved to half speed.","qTabDataOutput::updateSpeedFromServer"); + //set to default + comboEigerClkDivider->setCurrentIndex(HalfSpeed); + myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER,HalfSpeed); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateSpeedFromServer"); + + } + connect(comboEigerClkDivider, SIGNAL(currentIndexChanged(int)), this, SLOT(setSpeed())); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::updateFlagsFromServer(){ + int ret; + if(widgetEiger->isVisible()){ + disconnect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(setFlags())); + disconnect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(setFlags())); + + //get speed + ret = myDet->setReadOutFlags(slsDetectorDefs::GET_READOUT_FLAGS); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateFlagsFromServer"); + + //invalid flags + if(ret==-1){ + qDefs::Message(qDefs::WARNING,"Inconsistent value for readout flags.\n" + "Setting it for all detectors involved to continous nonparallel mode.", + "qTabDataOutput::updateFlagsFromServer"); + //set to default + comboEigerFlags1->setCurrentIndex(Continous); + myDet->setReadOutFlags(slsDetectorDefs::CONTINOUS_RO); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateFlagsFromServer"); + comboEigerFlags2->setCurrentIndex(NonParallel); + myDet->setReadOutFlags(slsDetectorDefs::NONPARALLEL); + qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateFlagsFromServer"); + } + + //valid flags + else{ + if(ret & slsDetectorDefs::STORE_IN_RAM) + comboEigerFlags1->setCurrentIndex(Storeinram); + else if(ret & slsDetectorDefs::CONTINOUS_RO) + comboEigerFlags1->setCurrentIndex(Continous); + if(ret & slsDetectorDefs::PARALLEL) + comboEigerFlags2->setCurrentIndex(Parallel); + else if(ret & slsDetectorDefs::NONPARALLEL) + comboEigerFlags2->setCurrentIndex(NonParallel); + else if(ret & slsDetectorDefs::SAFE) + comboEigerFlags2->setCurrentIndex(Safe); + } + + connect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(setFlags())); + connect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(setFlags())); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDataOutput::Refresh(){ +#ifdef VERBOSE + cout << endl << "**Updating DataOutput Tab" << endl; +#endif + + + // output dir +#ifdef VERBOSE + cout << "Getting output directory" << endl; +#endif + disconnect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + PopulateDetectors(); + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + + + //flat field correction from server +#ifdef VERBOSE + cout << "Getting flat field" << endl; +#endif + UpdateFlatFieldFromServer(); + + + //rate correction - not for charge integrating detectors + if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::EIGER)){ +#ifdef VERBOSE + cout << "Getting rate correction" << endl; +#endif + UpdateRateCorrectionFromServer(); + } + + + //update angular conversion from server + if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::GOTTHARD)){ +#ifdef VERBOSE + cout << "Getting angular conversion" << endl; +#endif + int ang; + if(myDet->getAngularConversion(ang)) + chkAngular->setChecked(true); + emit AngularConversionSignal(chkAngular->isChecked()); + } + + + //discard bad channels from server +#ifdef VERBOSE + cout << "Getting bad channel correction" << endl;//cout << "ff " << myDet->getBadChannelCorrection() << endl; +#endif + + + disconnect(chkDiscardBad, SIGNAL(toggled(bool))); + if(myDet->getBadChannelCorrection()) + chkDiscardBad->setChecked(true); + else + chkDiscardBad->setChecked(false); + connect(chkDiscardBad, SIGNAL(toggled(bool)), this, SLOT(DiscardBadChannels())); + + if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ + btnOutputBrowse->setEnabled(false); + btnOutputBrowse->setToolTip("This button is disabled as receiver PC is different from " + "client PC and hence different directory structures.

" + dispOutputDir->toolTip()); + }else{ + btnOutputBrowse->setEnabled(true); + btnOutputBrowse->setToolTip(dispOutputDir->toolTip()); + } + + //getting compression + if(chkCompression->isEnabled()){ +#ifdef VERBOSE + cout << "Getting compression" << endl; +#endif + GetCompression(); + } + + //getting 10GbE + if(chkTenGiga->isEnabled()){ +#ifdef VERBOSE + cout << "Getting 10GbE enable" << endl; +#endif + EnableTenGigabitEthernet(-1,1); + } + + //Eiger specific + if(widgetEiger->isVisible()){ + //speed +#ifdef VERBOSE + cout << "Getting Speed" << endl; +#endif + updateSpeedFromServer(); + //flags +#ifdef VERBOSE + cout << "Getting Readout Flags" << endl; +#endif + updateFlagsFromServer(); + + + + } + + +#ifdef VERBOSE + cout << "**Updated DataOutput Tab" << endl << endl; +#endif + + qDefs::checkErrorMessage(myDet,"qTabDataOutput::Refresh"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + diff --git a/slsDetectorGui/src/qTabDebugging.cpp b/slsDetectorGui/src/qTabDebugging.cpp new file mode 100644 index 0000000000..150f8dbe71 --- /dev/null +++ b/slsDetectorGui/src/qTabDebugging.cpp @@ -0,0 +1,613 @@ +/* + * qTabDebugging.cpp + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ +#include "qTabDebugging.h" +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +// Qt Include Headers +#include +#include +// C++ Include Headers +#include +using namespace std; + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabDebugging::qTabDebugging(QWidget *parent,multiSlsDetector*& detector): + QWidget(parent), + myDet(detector), + det(0), + treeDet(0), + dispFrame(0), + lblDetectorId(0), + lblDetectorSerial(0), + lblDetectorFirmware(0), + lblDetectorSoftware(0), + lblModuleId(0), + lblModuleFirmware(0), + lblModuleSerial(0){ + setupUi(this); + SetupWidgetWindow(); + Initialization(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabDebugging::~qTabDebugging(){ + delete myDet; + if(det) delete det; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDebugging::SetupWidgetWindow(){ + + blue = new QPalette(); + blue->setColor(QPalette::Active,QPalette::WindowText,Qt::darkBlue); + + + // Detector Type + detType=myDet->getDetectorsType(); + ///change module label + switch(detType){ + case slsDetectorDefs::EIGER: + lblDetector->setText("Half Module:"); + chkDetectorFirmware->setText("Half Module Firmware:"); + chkDetectorSoftware->setText("Half Module Software:"); + chkDetectorMemory->setText("Half Module Memory:"); + chkDetectorBus->setText("Half Module Bus:"); + lblModule->hide(); + comboModule->hide(); + chkModuleFirmware->hide(); + chkChip->setEnabled(false); + chkModuleFirmware->setEnabled(false); + break; + case slsDetectorDefs::JUNGFRAU: + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::GOTTHARD: + lblDetector->setText("Module:"); + chkDetectorFirmware->setText("Module Firmware:"); + chkDetectorSoftware->setText("Module Software:"); + chkDetectorMemory->setText("Module Memory:"); + chkDetectorBus->setText("Module Bus:"); + lblModule->hide(); + comboModule->hide(); + chkModuleFirmware->hide(); + chkChip->setEnabled(false); + chkModuleFirmware->setEnabled(false); + break; + case slsDetectorDefs::MOENCH: + lblDetector->setText("Module:"); + chkDetectorFirmware->setText("Module Firmware:"); + chkDetectorSoftware->setText("Module Software:"); + chkDetectorMemory->setText("Module Memory:"); + chkDetectorBus->setText("Module Bus:"); + lblModule->hide(); + comboModule->hide(); + chkModuleFirmware->hide(); + chkChip->setEnabled(false); + chkModuleFirmware->setEnabled(false); + break; + case slsDetectorDefs::MYTHEN: + break; + default: + //leave everything as it is(mythen is default) + break; + } + + + //add detectors + for(int i=0;igetNumberOfDetectors();i++){ + comboDetector->addItem(QString(myDet->getHostname(i).c_str())); + } + + + //add modules and status for current detector + if(detType==slsDetectorDefs::MYTHEN) UpdateModuleList(); + UpdateStatus(); + + qDefs::checkErrorMessage(myDet,"qTabDebugging::SetupWidgetWindow"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDebugging::Initialization(){ + if(detType==slsDetectorDefs::MYTHEN) + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateModuleList())); + + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateStatus())); + connect(btnGetInfo, SIGNAL(clicked()), this, SLOT(GetInfo())); + connect(btnTest, SIGNAL(clicked()), this, SLOT(TestDetector())); +} + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDebugging::UpdateModuleList(){ +#ifdef VERBOSE + cout << "Getting Module List" << endl; +#endif + det = myDet->getSlsDetector(comboDetector->currentIndex()); + qDefs::checkErrorMessage(myDet,"qTabDebugging::UpdateModuleList"); + //deletes all modules except "all modules" + for(int i=0;icount()-1;i++) + comboModule->removeItem(i); + for(int i=0;igetNMods();i++){ + comboModule->addItem(QString("Module %1").arg(i)); + } + + qDefs::checkErrorMessage(det,"qTabDebugging::UpdateModuleList"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDebugging::UpdateStatus(){ +#ifdef VERBOSE + cout << "Getting Status" << endl; +#endif + det = myDet->getSlsDetector(comboDetector->currentIndex()); + qDefs::checkErrorMessage(myDet,"qTabDebugging::UpdateStatus"); + int detStatus = (int)det->getRunStatus(); + string status = slsDetectorBase::runStatusType(slsDetectorDefs::runStatus(detStatus)); + lblStatus->setText(QString(status.c_str()).toUpper()); + + qDefs::checkErrorMessage(det,"qTabDebugging::UpdateStatus"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDebugging::GetInfo(){ +#ifdef VERBOSE + cout << "Getting Info" << endl; +#endif + //window + QFrame* popup1 = new QFrame(this, Qt::Popup | Qt::SubWindow ); + QList items; + + + + //layout + QGridLayout *layout = new QGridLayout(popup1); + //treewidget + treeDet = new QTreeWidget(popup1); + layout->addWidget(treeDet,0,0); + //display the details + dispFrame = new QFrame(popup1); + QGridLayout *formLayout = new QGridLayout(dispFrame); + lblDetectorId = new QLabel(""); lblDetectorId->setPalette(*blue); + lblDetectorSerial = new QLabel(""); lblDetectorSerial->setPalette(*blue); + lblDetectorFirmware = new QLabel(""); lblDetectorFirmware->setPalette(*blue); + lblDetectorSoftware = new QLabel(""); lblDetectorSoftware->setPalette(*blue); + lblModuleId = new QLabel(""); lblModuleId->setPalette(*blue); + lblModuleSerial = new QLabel(""); lblModuleSerial->setPalette(*blue); + lblModuleFirmware = new QLabel(""); lblModuleFirmware->setPalette(*blue); + //to make sure the size is constant + lblDetectorFirmware->setFixedWidth(100); + layout->addWidget(dispFrame,0,1); + + switch(detType){ + + case slsDetectorDefs::MYTHEN: + //display widget + formLayout->addWidget(new QLabel("Readout:"),0,0); + formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); + formLayout->addWidget(lblDetectorId,0,2); + formLayout->addWidget(new QLabel("Readout MAC Address:"),1,0); + formLayout->addWidget(lblDetectorSerial,1,2); + formLayout->addWidget(new QLabel("Readout Firmware Version:"),2,0); + formLayout->addWidget(lblDetectorFirmware,2,2); + formLayout->addWidget(new QLabel("Readout Software Version:"),3,0); + formLayout->addWidget(lblDetectorSoftware,3,2); + formLayout->addWidget(new QLabel("Module:"),4,0); + formLayout->addWidget(lblModuleId,4,2); + formLayout->addWidget(new QLabel("Module Serial Number:"),5,0); + formLayout->addWidget(lblModuleSerial,5,2); + formLayout->addWidget(new QLabel("Module Firmware Version:"),6,0); + formLayout->addWidget(lblModuleFirmware,6,2); + + + //tree widget + treeDet->setHeaderLabel("Mythen Detector"); + //gets det names + for (int i=0;icount();i++) + items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Readout (%1)").arg(comboDetector->itemText(i))))); + treeDet->insertTopLevelItems(0, items); + //gets module names + for (int i=0;icount();i++){ + QList childItems; + det = myDet->getSlsDetector(i); + qDefs::checkErrorMessage(myDet,"qTabDebugging::GetInfo"); + for(int j=0;jgetNMods();j++) + childItems.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module %1").arg(j)))); + treeDet->topLevelItem(i)->insertChildren(0,childItems); + qDefs::checkErrorMessage(det,"qTabDebugging::GetInfo"); + } + + break; + + + + + case slsDetectorDefs::EIGER: + //display widget + formLayout->addWidget(new QLabel("Half Module:"),0,0); + formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); + formLayout->addWidget(lblDetectorId,0,2); + formLayout->addWidget(new QLabel("Half Module MAC Address:"),1,0); + formLayout->addWidget(lblDetectorSerial,1,2); + formLayout->addWidget(new QLabel("Half Module Firmware Version:"),2,0); + formLayout->addWidget(lblDetectorFirmware,2,2); + formLayout->addWidget(new QLabel("Half Module Software Version:"),3,0); + formLayout->addWidget(lblDetectorSoftware,3,2); + + //tree widget + treeDet->setHeaderLabel("Eiger Detector"); + //get num modules + for (int i=0;icount()/2;i++) + items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module %1").arg(i)))); + treeDet->insertTopLevelItems(0, items); + //gets det names + for (int i=0;icount();i++){ + QList childItems; + childItems.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Half Module (%1)").arg(comboDetector->itemText(i))))); + treeDet->topLevelItem(i*2)->insertChildren(0,childItems); + } + break; + + + + case slsDetectorDefs::MOENCH: + + //display widget + formLayout->addWidget(new QLabel("Module:"),0,0); + formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); + formLayout->addWidget(lblDetectorId,0,2); + formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); + formLayout->addWidget(lblDetectorSerial,1,2); + formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); + formLayout->addWidget(lblDetectorFirmware,2,2); + formLayout->addWidget(new QLabel("Module Software Version:"),3,0); + formLayout->addWidget(lblDetectorSoftware,3,2); + //tree widget + treeDet->setHeaderLabel("Moench Detector"); + //gets det names + for (int i=0;icount();i++) + items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); + treeDet->insertTopLevelItems(0, items); + + break; + + + + case slsDetectorDefs::PROPIX: + + //display widget + formLayout->addWidget(new QLabel("Module:"),0,0); + formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); + formLayout->addWidget(lblDetectorId,0,2); + formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); + formLayout->addWidget(lblDetectorSerial,1,2); + formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); + formLayout->addWidget(lblDetectorFirmware,2,2); + formLayout->addWidget(new QLabel("Module Software Version:"),3,0); + formLayout->addWidget(lblDetectorSoftware,3,2); + //tree widget + treeDet->setHeaderLabel("Propix Detector"); + //gets det names + for (int i=0;icount();i++) + items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); + treeDet->insertTopLevelItems(0, items); + + break; + + + + case slsDetectorDefs::GOTTHARD: + + //display widget + formLayout->addWidget(new QLabel("Module:"),0,0); + formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); + formLayout->addWidget(lblDetectorId,0,2); + formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); + formLayout->addWidget(lblDetectorSerial,1,2); + formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); + formLayout->addWidget(lblDetectorFirmware,2,2); + formLayout->addWidget(new QLabel("Module Software Version:"),3,0); + formLayout->addWidget(lblDetectorSoftware,3,2); + //tree widget + treeDet->setHeaderLabel("Gotthard Detector"); + //gets det names + for (int i=0;icount();i++) + items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); + treeDet->insertTopLevelItems(0, items); + + break; + + + case slsDetectorDefs::JUNGFRAU: + + //display widget + formLayout->addWidget(new QLabel("Module:"),0,0); + formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); + formLayout->addWidget(lblDetectorId,0,2); + formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); + formLayout->addWidget(lblDetectorSerial,1,2); + formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); + formLayout->addWidget(lblDetectorFirmware,2,2); + formLayout->addWidget(new QLabel("Module Software Version:"),3,0); + formLayout->addWidget(lblDetectorSoftware,3,2); + //tree widget + treeDet->setHeaderLabel("JungFrau Detector"); + //gets det names + for (int i=0;icount();i++) + items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); + treeDet->insertTopLevelItems(0, items); + + break; + + + default: + break; + } + + //show and center widget + + int x = ((parentWidget()->width()) - (popup1->frameGeometry().width())) / 2; + int y = ((parentWidget()->height()) - (popup1->frameGeometry().height())) / 2; + QDesktopWidget *desktop = QApplication::desktop(); + int screen = desktop->screenNumber(this); + popup1->setWindowModality(Qt::WindowModal); + popup1->move( (desktop->screenGeometry(screen).x())+x, (desktop->screenGeometry(screen).y())+y ); + popup1->show(); + + //put the first parameters + SetParameters(treeDet->topLevelItem(0)); + + //initializations + connect(treeDet, SIGNAL(itemDoubleClicked(QTreeWidgetItem *,int)) , this, SLOT(SetParameters(QTreeWidgetItem *))); + +} +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabDebugging::SetParameters(QTreeWidgetItem *item){ + char value[200]; + int i; + + + switch(detType){ + + case slsDetectorDefs::MYTHEN: + if(item->text(0).contains("Readout")){ + //find index + for(i=0;icount();i++) + if(item== treeDet->topLevelItem(i)) + break; + + det = myDet->getSlsDetector(i); + qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); + lblDetectorId->setText(comboDetector->itemText(i)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); + lblDetectorSerial->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); + lblDetectorFirmware ->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); + lblDetectorSoftware->setText(QString(value)); + qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); + + lblModuleId->setText(""); + lblModuleSerial->setText(""); + lblModuleFirmware->setText(""); + }else{ + //find index + for(i=0;icount();i++) + if(item->parent() == treeDet->topLevelItem(i)) + break; + int im = item->parent()->indexOfChild(item); + + det = myDet->getSlsDetector(i); + qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); + lblDetectorId->setText(comboDetector->itemText(i)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); + lblDetectorSerial->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); + lblDetectorFirmware ->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); + lblDetectorSoftware->setText(QString(value)); + + lblModuleId->setText(QString("%1").arg(im)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::MODULE_SERIAL_NUMBER,im)); + lblModuleSerial->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::MODULE_FIRMWARE_VERSION,im)); + lblModuleFirmware->setText(QString(value)); + + qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); + } + break; + + + + + + case slsDetectorDefs::EIGER: + //only if half module clicked + if(item->text(0).contains("Half Module")){ + //find index + for(i=0;icount();i++) + if(item== treeDet->topLevelItem(i)) + break; + + det = myDet->getSlsDetector(i); + qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); + lblDetectorId->setText(comboDetector->itemText(i)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); + lblDetectorSerial->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); + lblDetectorFirmware ->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); + lblDetectorSoftware->setText(QString(value)); + + qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); + } + break; + + + case slsDetectorDefs::JUNGFRAU: + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::MOENCH: + case slsDetectorDefs::GOTTHARD: + //find index + for(i=0;icount();i++) + if(item== treeDet->topLevelItem(i)) + break; + + det = myDet->getSlsDetector(i); + qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); + lblDetectorId->setText(comboDetector->itemText(i)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); + lblDetectorSerial->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); + lblDetectorFirmware ->setText(QString(value)); + sprintf(value,"%llx",det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); + lblDetectorSoftware->setText(QString(value)); + + qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); + break; + + + + + default: + break; + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDebugging::TestDetector(){ +#ifdef VERBOSE + cout << "Testing" << endl; +#endif + + int retval=slsDetectorDefs::FAIL; + QString message; + QString Detector = "Detector"; + + //main messagebox title + switch(detType){ + case slsDetectorDefs::MYTHEN: + message = QString("Test Results for %1 and %2:

").arg(comboDetector->currentText(),comboModule->currentText()); + break; + case slsDetectorDefs::EIGER: Detector = "Half Module"; break; + case slsDetectorDefs::JUNGFRAU: + case slsDetectorDefs::MOENCH: + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::GOTTHARD: Detector = "Module"; break; + default: break; + } + + + if(detType==slsDetectorDefs::MYTHEN) + message = QString("Test Results for %1 and %2:

").arg(comboDetector->currentText(),comboModule->currentText()); + else message = QString("Test Results for %1:

").arg(comboDetector->currentText()); + + //get sls det object + det = myDet->getSlsDetector(comboDetector->currentIndex()); + qDefs::checkErrorMessage(myDet,"qTabDebugging::TestDetector"); + + //detector firmware + if(chkDetectorFirmware->isChecked()){ + retval = det->digitalTest(slsDetectorDefs::DETECTOR_FIRMWARE_TEST); + if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Firmware: FAIL
").arg(Detector)); + else message.append(QString("%1 Firmware: %2
").arg(Detector,QString::number(retval))); +#ifdef VERBOSE + cout<<"Detector Firmware: "<isChecked()){ + retval = det->digitalTest(slsDetectorDefs::DETECTOR_SOFTWARE_TEST); + if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Software: FAIL
").arg(Detector)); + else message.append(QString("%1 Software: %2
").arg(Detector,QString::number(retval))); +#ifdef VERBOSE + cout<<"Detector Software: "<isChecked()){ + retval = det->digitalTest(slsDetectorDefs::DETECTOR_BUS_TEST); + if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Bus:     FAIL
").arg(Detector)); + else message.append(QString("%1 Bus:     %2
").arg(Detector,QString::number(retval))); +#ifdef VERBOSE + cout<<"Detector Bus: "<isChecked()){ + retval = det->digitalTest(slsDetectorDefs::DETECTOR_MEMORY_TEST); + if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Memory:  FAIL
").arg(Detector)); + else message.append(QString("%1 Memory:  %2
").arg(Detector,QString::number(retval))); +#ifdef VERBOSE + cout<<"Detector Memory: "<isChecked()){ + retval = det->digitalTest(slsDetectorDefs::CHIP_TEST,comboModule->currentIndex()); + if(retval== slsDetectorDefs::FAIL) message.append("
Chip: FAIL
"); + else message.append(QString("Chip: %1
").arg(retval)); +#ifdef VERBOSE + cout<<"Chip: "<isChecked()){ + retval = det->digitalTest(slsDetectorDefs::MODULE_FIRMWARE_TEST,comboModule->currentIndex()); + if(retval== slsDetectorDefs::FAIL) message.append("Module Firmware: FAIL
"); + else message.append(QString("Module Firmware: %1
").arg(retval)); +#ifdef VERBOSE + cout<<"Module Firmware: "< +#include +#include +//C++ Include Headers +#include +using namespace std; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +int qTabDeveloper::NUM_DAC_WIDGETS(0); +int qTabDeveloper::NUM_ADC_WIDGETS(0); + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabDeveloper::qTabDeveloper(qDetectorMain *parent,multiSlsDetector*& detector): + thisParent(parent), + myDet(detector), + det(0), + boxDacs(0), + boxAdcs(0), + lblHV(0), + comboHV(0), + adcTimer(0), + dacLayout(0){ + for(int i=0;i<20;i++){ + lblDacs[i]=0; + lblAdcs[i]=0; + spinDacs[i]=0; + spinAdcs[i]=0; + lblDacsmV[i]=0; + } + SetupWidgetWindow(); + Initialization(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabDeveloper::~qTabDeveloper(){ + delete myDet; + if(det) delete det; + if(thisParent) delete thisParent; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDeveloper::SetupWidgetWindow(){ + //Detector Type + detType=myDet->getDetectorsType(); + + //palette + red = QPalette(); + red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + + + //the number of dacs and adcs + switch(detType){ + case slsDetectorDefs::MYTHEN: + NUM_DAC_WIDGETS = 6; + NUM_ADC_WIDGETS = 0; + dacNames.push_back("v Trimbit:"); + dacNames.push_back("v Threshold:"); + dacNames.push_back("v Shaper1:"); + dacNames.push_back("v Shaper2:"); + dacNames.push_back("v Calibration:"); + dacNames.push_back("v Preamp:"); + break; + case slsDetectorDefs::EIGER: + NUM_DAC_WIDGETS = 17; + NUM_ADC_WIDGETS = 6; + + dacNames.push_back("v SvP:"); + dacNames.push_back("v SvN"); + dacNames.push_back("v Vrf:"); + dacNames.push_back("v Vrs:"); + dacNames.push_back("v Vtr:"); + dacNames.push_back("v Vtgstv:"); + dacNames.push_back("v cal:"); + dacNames.push_back("v Vcp"); + dacNames.push_back("v Vcn:"); + dacNames.push_back("v Vis:"); + dacNames.push_back("v rxb_lb:"); + dacNames.push_back("v rxb_rb:"); + dacNames.push_back("v Vcmp_ll:"); + dacNames.push_back("v Vcmp_lr:"); + dacNames.push_back("v Vcmp_rl:"); + dacNames.push_back("v Vcmp_rr:"); + dacNames.push_back("v threshold:"); + + adcNames.push_back("Temperature FPGA Ext:"); + adcNames.push_back("Temperature 10GE:"); + adcNames.push_back("Temperature DCDC:"); + adcNames.push_back("Temperature SODL:"); + adcNames.push_back("Temperature SODR:"); + adcNames.push_back("Temperature FPGA:"); + + break; + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::GOTTHARD: + NUM_DAC_WIDGETS = 8; + NUM_ADC_WIDGETS = 2; + dacNames.push_back("v Reference:"); + dacNames.push_back("v Cascode n:"); + dacNames.push_back("v Cascode p:"); + dacNames.push_back("v Comp. Output:"); + dacNames.push_back("v Cascode out"); + dacNames.push_back("v Comp. Input:"); + dacNames.push_back("v Comp. Ref:"); + dacNames.push_back("i Base Test:"); + + adcNames.push_back("Temperature ADC:"); + adcNames.push_back("Temperature FPGA:"); + + break; + case slsDetectorDefs::MOENCH: + NUM_DAC_WIDGETS = 8; + NUM_ADC_WIDGETS = 2; + dacNames.push_back("v Dac 0:"); + dacNames.push_back("v Dac 1:"); + dacNames.push_back("v Dac 2:"); + dacNames.push_back("v Dac 3:"); + dacNames.push_back("v Dac 4:"); + dacNames.push_back("v Dac 5:"); + dacNames.push_back("v Dac 6:"); + dacNames.push_back("i Dac 7:"); + + adcNames.push_back("Temperature ADC:"); + adcNames.push_back("Temperature FPGA:"); + + break; + + + case slsDetectorDefs::JUNGFRAU: + NUM_DAC_WIDGETS = 16; + NUM_ADC_WIDGETS = 0; + dacNames.push_back("v Dac 0:"); + dacNames.push_back("v Dac 1:"); + dacNames.push_back("v Dac 2:"); + dacNames.push_back("v Dac 3:"); + dacNames.push_back("v Dac 4:"); + dacNames.push_back("v Dac 5:"); + dacNames.push_back("v Dac 6:"); + dacNames.push_back("i Dac 7:"); + dacNames.push_back("v Dac 8:"); + dacNames.push_back("v Dac 9:"); + dacNames.push_back("v Dac 10:"); + dacNames.push_back("v Dac 11:"); + dacNames.push_back("v Dac 12:"); + dacNames.push_back("v Dac 13:"); + dacNames.push_back("v Dac 14:"); + dacNames.push_back("i Dac 15:"); + + + break; + + default: + cout << "ERROR: Unknown detector type: " + myDet->slsDetectorBase::getDetectorType(detType) << endl; + qDefs::Message(qDefs::CRITICAL,string("Unknown detector type:")+myDet->slsDetectorBase::getDetectorType(detType),"qTabDeveloper::SetupWidgetWindow"); + exit(-1); + break; + } + + + //layout + setFixedWidth(765); + setFixedHeight(20+50+(NUM_DAC_WIDGETS/2)*35); + //setHeight(340); + + scroll = new QScrollArea; + //scroll->setFrameShape(QFrame::NoFrame); + scroll->setWidget(this); + scroll->setWidgetResizable(true); + + layout = new QGridLayout(scroll); + layout->setContentsMargins(20,10,10,5); + setLayout(layout); + + //readout + comboDetector = new QComboBox(this); + //comboDetector->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + comboDetector->addItem("All"); + //add detectors + for(int i=1;igetNumberOfDetectors()+1;i++) + comboDetector->addItem(QString(myDet->getHostname(i-1).c_str())); + comboDetector->setCurrentIndex(0); + + + //dacs + boxDacs = new QGroupBox("Dacs",this); + boxDacs->setFixedHeight(25+(NUM_DAC_WIDGETS/2)*35); + CreateDACWidgets(); + + //HV for gotthard + if ((detType==slsDetectorDefs::GOTTHARD) || + (detType==slsDetectorDefs::PROPIX) || + (detType==slsDetectorDefs::MOENCH)){ + boxDacs->setFixedHeight(boxDacs->height()+35); + + lblHV = new QLabel("High Voltage",boxDacs); + comboHV = new QComboBox(boxDacs); + comboHV->addItem("0"); + comboHV->addItem("90"); + comboHV->addItem("110"); + comboHV->addItem("120"); + comboHV->addItem("150"); + comboHV->addItem("180"); + comboHV->addItem("200"); + tipHV = "Set high voltage to 0, 90, 110, 120, 150 or 200V."; + lblHV->setToolTip(tipHV); + comboHV->setToolTip(tipHV); + dacLayout->addWidget(lblHV,(int)(NUM_DAC_WIDGETS/2),1); + dacLayout->addWidget(comboHV,(int)(NUM_DAC_WIDGETS/2),2); + connect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + } + layout->addWidget(comboDetector,0,0); + layout->addWidget(boxDacs,1,0); + + + //adcs + if((detType==slsDetectorDefs::GOTTHARD) || + (detType==slsDetectorDefs::PROPIX) || + (detType==slsDetectorDefs::MOENCH)|| + (detType==slsDetectorDefs::EIGER)) { + setFixedHeight(20+(50+(NUM_DAC_WIDGETS/2)*35)+(50+(NUM_ADC_WIDGETS/2)*35)); + boxAdcs = new QGroupBox("ADCs",this); + boxAdcs->setFixedHeight(25+(NUM_ADC_WIDGETS/2)*35); + layout->addWidget(boxAdcs,2,0); + CreateADCWidgets(); + //to make the adcs at the bottom most + if(detType!=slsDetectorDefs::EIGER) { + int diff = 340-height(); + setFixedHeight(340); + layout->setVerticalSpacing(diff/2); + } + //timer to check adcs + adcTimer = new QTimer(this); + } + + qDefs::checkErrorMessage(myDet,"qTabDeveloper::SetupWidgetWindow"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDeveloper::Initialization(){ + if(NUM_ADC_WIDGETS) connect(adcTimer, SIGNAL(timeout()), this, SLOT(RefreshAdcs())); + + for(int i=0;isetMinimum(-1); + spinDacs[i]->setMaximum(10000); + lblDacsmV[i]= new QLabel("",boxDacs); + + + dacLayout->addWidget(lblDacs[i],(int)(i/2),((i%2)==0)?1:5); + dacLayout->addWidget(spinDacs[i],(int)(i/2),((i%2)==0)?2:6); + dacLayout->addWidget(lblDacsmV[i],(int)(i/2),((i%2)==0)?3:7); + if(!(i%2)){ + dacLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),0); + dacLayout->addItem(new QSpacerItem(60,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),4); + dacLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),8); + } + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDeveloper::CreateADCWidgets(){ + QGridLayout *adcLayout = new QGridLayout(boxAdcs); + + for(int i=0;isetMaximum(10000); + spinAdcs[i]->setMinimum(-1); + if((detType==slsDetectorDefs::GOTTHARD) || + (detType==slsDetectorDefs::PROPIX) || + (detType==slsDetectorDefs::MOENCH)|| + (detType==slsDetectorDefs::EIGER)) + spinAdcs[i]->setSuffix(0x00b0+QString("C")); + + adcLayout->addWidget(lblAdcs[i],(int)(i/2),((i%2)==0)?1:4); + adcLayout->addWidget(spinAdcs[i],(int)(i/2),((i%2)==0)?2:5); + if(!(i%2)){ + adcLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),0); + adcLayout->addItem(new QSpacerItem(60,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),3); + adcLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),6); + } + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDeveloper::SetDacValues(int id){ +#ifdef VERBOSE + cout << "Setting dac:" << dacNames[id] << " : " << spinDacs[id]->value() << endl; +#endif + + int detid = comboDetector->currentIndex(); + if(detid) + det = myDet->getSlsDetector(detid-1); + + //all detectors + if(!detid){ + myDet->setDAC((dacs_t)spinDacs[id]->value(),getSLSIndex(id),0); + lblDacsmV[id]->setText(QString("%1mV").arg(myDet->setDAC(-1,getSLSIndex(id),1),-10)); + qDefs::checkErrorMessage(myDet,"qTabDeveloper::SetDacValues"); + } + //specific detector + else{ + det->setDAC((dacs_t)spinDacs[id]->value(),getSLSIndex(id),0); + lblDacsmV[id]->setText(QString("%1mV").arg(det->setDAC(-1,getSLSIndex(id),1),-10)); + qDefs::checkErrorMessage(det,"qTabDeveloper::SetDacValues"); + } + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDeveloper::SetHighVoltage(){ +#ifdef VERBOSE + cout << "Setting high voltage:" << comboHV->currentText().toAscii().constData() << endl; +#endif + + int detid = comboDetector->currentIndex(); + if(detid) + det = myDet->getSlsDetector(detid-1); + + int highvoltage = comboHV->currentText().toInt(); + int ret; + + //all detectors + if(!detid){ + ret = myDet->setDAC(highvoltage,slsDetectorDefs::HV_POT,0); + qDefs::checkErrorMessage(myDet,"qTabDeveloper::SetHighVoltage"); + } + //specific detector + else{ + ret = det->setDAC(highvoltage,slsDetectorDefs::HV_POT,0); + qDefs::checkErrorMessage(det,"qTabDeveloper::SetHighVoltage"); + } + + + //error + if(ret != highvoltage){ + qDefs::Message(qDefs::CRITICAL,"High Voltage could not be set to this value.","qTabDeveloper::SetHighVoltage"); + lblHV->setPalette(red); + lblHV->setText("High Voltage:*"); + QString errTip = tipHV+QString("

High Voltage could not be set. The return value is ")+ + QString::number(ret)+ QString(""); + lblHV->setToolTip(errTip); + comboHV->setToolTip(errTip); + }else{ + lblHV->setPalette(lblDacs[0]->palette()); + lblHV->setText("High Voltage:"); + lblHV->setToolTip(tipHV); + comboHV->setToolTip(tipHV); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +slsDetectorDefs::dacIndex qTabDeveloper::getSLSIndex(int index){ + switch(detType){ + case slsDetectorDefs::MYTHEN: + switch(index){ + case 0: return slsDetectorDefs::TRIMBIT_SIZE; + case 1: return slsDetectorDefs::THRESHOLD; + case 2: return slsDetectorDefs::SHAPER1; + case 3: return slsDetectorDefs::SHAPER2; + case 4: return slsDetectorDefs::CALIBRATION_PULSE; + case 5: return slsDetectorDefs::PREAMP; + default: + qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); + Refresh(); + break; + } + break; + case slsDetectorDefs::EIGER: + switch(index){ + case 0: return slsDetectorDefs::E_SvP; + case 1: return slsDetectorDefs::E_SvN; + case 2: return slsDetectorDefs::E_Vrf; + case 3: return slsDetectorDefs::E_Vrs; + case 4: return slsDetectorDefs::E_Vtr; + case 5: return slsDetectorDefs::E_Vtgstv; + case 6: return slsDetectorDefs::E_cal; + case 7: return slsDetectorDefs::E_Vcp; + case 8: return slsDetectorDefs::E_Vcn; + case 9: return slsDetectorDefs::E_Vis; + case 10:return slsDetectorDefs::E_rxb_lb; + case 11:return slsDetectorDefs::E_rxb_rb; + case 12:return slsDetectorDefs::E_Vcmp_ll; + case 13:return slsDetectorDefs::E_Vcmp_lr; + case 14:return slsDetectorDefs::E_Vcmp_rl; + case 15:return slsDetectorDefs::E_Vcmp_rr; + case 16:return slsDetectorDefs::THRESHOLD; + case 17:return slsDetectorDefs::TEMPERATURE_FPGAEXT; + case 18:return slsDetectorDefs::TEMPERATURE_10GE; + case 19:return slsDetectorDefs::TEMPERATURE_DCDC; + case 20:return slsDetectorDefs::TEMPERATURE_SODL; + case 21:return slsDetectorDefs::TEMPERATURE_SODR; + case 22:return slsDetectorDefs::TEMPERATURE_FPGA; + default: + qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); + Refresh(); + break; + } + break; + case slsDetectorDefs::MOENCH: + switch(index){ + case 0: return slsDetectorDefs::V_DAC0; + case 1: return slsDetectorDefs::V_DAC1; + case 2: return slsDetectorDefs::V_DAC2; + case 3: return slsDetectorDefs::V_DAC3; + case 4: return slsDetectorDefs::V_DAC4; + case 5: return slsDetectorDefs::V_DAC5; + case 6: return slsDetectorDefs::V_DAC6; + case 7: return slsDetectorDefs::V_DAC7; + case 8: return slsDetectorDefs::TEMPERATURE_ADC; + case 9:return slsDetectorDefs::TEMPERATURE_FPGA; + + default: + qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error. Index:"+ index,"qTabDeveloper::getSLSIndex"); + Refresh(); + break; + } + break; + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::GOTTHARD: + switch(index){ + case 0: return slsDetectorDefs::G_VREF_DS; + case 1: return slsDetectorDefs::G_VCASCN_PB; + case 2: return slsDetectorDefs::G_VCASCP_PB; + case 3: return slsDetectorDefs::G_VOUT_CM; + case 4: return slsDetectorDefs::G_VCASC_OUT; + case 5: return slsDetectorDefs::G_VIN_CM; + case 6: return slsDetectorDefs::G_VREF_COMP; + case 7: return slsDetectorDefs::G_IB_TESTC; + case 8: return slsDetectorDefs::TEMPERATURE_ADC; + case 9:return slsDetectorDefs::TEMPERATURE_FPGA; + default: + qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); + Refresh(); + break; + } + break; + case slsDetectorDefs::JUNGFRAU: + switch(index){ + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + return (slsDetectorDefs::dacIndex)index; + break; + default: + qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); + Refresh(); + break; + } + break; + default: + cout << "Unknown detector type:" + myDet->slsDetectorBase::getDetectorType(detType) << endl; + qDefs::Message(qDefs::CRITICAL,string("Unknown detector type:")+myDet->slsDetectorBase::getDetectorType(detType),"qTabDeveloper::getSLSIndex"); + qDefs::checkErrorMessage(myDet,"qTabDeveloper::getSLSIndex"); + exit(-1); + break; + } + return slsDetectorDefs::HUMIDITY; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDeveloper::RefreshAdcs(){ + if(!thisParent->isCurrentlyTabDeveloper()) + return; + +#ifdef VERYVERBOSE + cout << "Updating ADCs" <stop(); + + int detid = comboDetector->currentIndex(); + if(detid) + det = myDet->getSlsDetector(detid-1); + + for(int i=0;igetADC(getSLSIndex(i+NUM_DAC_WIDGETS)); + if(value == -1) + spinAdcs[i]->setValue(value); + else + spinAdcs[i]->setValue(value/1000.00); + + } + else + spinAdcs[i]->setValue((double)myDet->getADC(getSLSIndex(i+NUM_DAC_WIDGETS))); + } + //specific detector + else{ + if(detType == slsDetectorDefs::EIGER) + spinAdcs[i]->setValue((double)det->getADC(getSLSIndex(i+NUM_DAC_WIDGETS))/1000.00); + else + spinAdcs[i]->setValue((double)det->getADC(getSLSIndex(i+NUM_DAC_WIDGETS))); + } + } + + + adcTimer->start(ADC_TIMEOUT); + qDefs::checkErrorMessage(myDet,"qTabDeveloper::RefreshAdcs"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabDeveloper::Refresh(){ +#ifdef VERBOSE + cout << endl << "**Updating Developer Tab" << endl; +#endif + + + int detid = comboDetector->currentIndex(); + if(detid) + det = myDet->getSlsDetector(detid-1); + + + //dacs +#ifdef VERBOSE + cout << "Gettings DACs" << endl; +#endif + for(int i=0;isetValue((double)myDet->setDAC(-1,getSLSIndex(i),0)); + lblDacsmV[i]->setText(QString("%1mV").arg(myDet->setDAC(-1,getSLSIndex(i),1),-10)); + } + //specific detector + else{ + spinDacs[i]->setValue((double)det->setDAC(-1,getSLSIndex(i),0)); + lblDacsmV[i]->setText(QString("%1mV").arg(det->setDAC(-1,getSLSIndex(i),1),-10)); + } + } + + + //adcs + if(NUM_ADC_WIDGETS) RefreshAdcs(); + + //gotthard -high voltage + if((detType == slsDetectorDefs::GOTTHARD) || + (detType == slsDetectorDefs::PROPIX) || + (detType == slsDetectorDefs::MOENCH)){ + disconnect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + + //default should be correct + lblHV->setPalette(lblDacs[0]->palette()); + lblHV->setText("High Voltage:"); + lblHV->setToolTip(tipHV); + comboHV->setToolTip(tipHV); + //getting hv value + int ret; + if(!detid) ret = (int)myDet->setDAC(-1,slsDetectorDefs::HV_POT,0); + else ret = (int)det->setDAC(-1,slsDetectorDefs::HV_POT,0); + + switch(ret){ + case 0: comboHV->setCurrentIndex(0);break; + case 90: comboHV->setCurrentIndex(1);break; + case 110: comboHV->setCurrentIndex(2);break; + case 120: comboHV->setCurrentIndex(3);break; + case 150: comboHV->setCurrentIndex(4);break; + case 180: comboHV->setCurrentIndex(5);break; + case 200: comboHV->setCurrentIndex(6);break; + default: comboHV->setCurrentIndex(0);//error + lblHV->setPalette(red); + lblHV->setText("High Voltage:*"); + QString errTip = tipHV+QString("

High Voltage could not be set. The return value is ")+ + QString::number(ret)+ QString(""); + lblHV->setToolTip(errTip); + comboHV->setToolTip(errTip); + break; + } + + connect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + } + +#ifdef VERBOSE + cout << "**Updated Developer Tab" << endl << endl; +#endif + + qDefs::checkErrorMessage(myDet,"qTabDeveloper::Refresh"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + diff --git a/slsDetectorGui/src/qTabMeasurement.cpp b/slsDetectorGui/src/qTabMeasurement.cpp new file mode 100644 index 0000000000..579f38c76e --- /dev/null +++ b/slsDetectorGui/src/qTabMeasurement.cpp @@ -0,0 +1,916 @@ +/* + * qTabMeasurement.cpp + * + * Created on: May 2, 2012 + * Author: l_maliakal_d + */ + +//Qt Project Class Headers +#include "qTabMeasurement.h" +#include "qDetectorMain.h" +//Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +//C++ Include Headers +#include +using namespace std; + + + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabMeasurement::qTabMeasurement(qDetectorMain *parent,multiSlsDetector*& detector, qDrawPlot*& plot): + thisParent(parent),myDet(detector),myPlot(plot),expertMode(false){ + setupUi(this); + SetupWidgetWindow(); + Initialization(); + SetupTimingMode(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabMeasurement::~qTabMeasurement(){ + delete myDet; + delete myPlot; + delete thisParent; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::SetupWidgetWindow(){ + + detType = myDet->getDetectorsType(); + + //Number of measurements + spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,-1)); + //Number of frames + spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); + //Exp Time + qDefs::timeUnit unit; + double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-9)))); + spinExpTime->setValue(time); + comboExpUnit->setCurrentIndex((int)unit); + //period + time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1)*(1E-9)))); + spinPeriod->setValue(time); + comboPeriodUnit->setCurrentIndex((int)unit); + //Number of Triggers + spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); + //delay + time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,-1)*(1E-9)))); + spinDelay->setValue(time); + comboDelayUnit->setCurrentIndex((int)unit); + //gates + spinNumGates->setValue((int)myDet->setTimer(slsDetectorDefs::GATES_NUMBER,-1)); + //probes + if(detType == slsDetectorDefs::MYTHEN) + spinNumProbes->setValue((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1)); + //File Name + dispFileName->setText(QString(myDet->getFileName().c_str())); + //File Index + spinIndex->setValue(myDet->getFileIndex()); + //only initially + lblProgressIndex->setText(QString::number(0)); + //ly initially + progressBar->setValue(0); + //file write enabled/disabled + chkFile->setChecked(myDet->enableWriteToFile()); + dispFileName->setEnabled(myDet->enableWriteToFile()); + + + //creating the icons for the buttons + iconStart = new QIcon(":/icons/images/start.png"); + iconStop = new QIcon(":/icons/images/stop.png"); + + + //Timer to update the progress bar + progressTimer = new QTimer(this); + + //Hide the error message + red = QPalette(); + red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + acqPeriodTip = spinPeriod->toolTip(); + errPeriodTip = QString("Frame period between exposures.
" + " #period#

")+ + QString("Acquisition Period should be" + " greater than or equal to Exposure Time."); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetupWidgetWindow"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::SetExpertMode(bool enable){ + expertMode = enable; + qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetExpertMode"); + + EnableProbes(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::SetupTimingMode(){ + //To be able to index items on a combo box + model = qobject_cast(comboTimingMode->model()); + QModelIndex index[NumTimingModes]; + QStandardItem* item[NumTimingModes]; + if (model) { + for(int i=0;iindex(i, comboTimingMode->modelColumn(), comboTimingMode->rootModelIndex()); + item[i] = model->itemFromIndex(index[i]); + } + //Enabling/Disabling depending on the detector type + switch(detType){ + case slsDetectorDefs::MYTHEN: + item[(int)Trigger_Exp_Series]->setEnabled(true); + item[(int)Trigger_Readout]->setEnabled(true); + item[(int)Gated]->setEnabled(true); + item[(int)Gated_Start]->setEnabled(true); + item[(int)Burst_Trigger]->setEnabled(false); + break; + case slsDetectorDefs::EIGER: + item[(int)Trigger_Exp_Series]->setEnabled(true); + item[(int)Trigger_Readout]->setEnabled(false); + item[(int)Gated]->setEnabled(true); + item[(int)Gated_Start]->setEnabled(false); + item[(int)Burst_Trigger]->setEnabled(true); + break; + case slsDetectorDefs::MOENCH: + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::GOTTHARD: + case slsDetectorDefs::JUNGFRAU: + item[(int)Trigger_Exp_Series]->setEnabled(true); + item[(int)Trigger_Readout]->setEnabled(false); + item[(int)Gated]->setEnabled(false); + item[(int)Gated_Start]->setEnabled(false); + item[(int)Burst_Trigger]->setEnabled(false); + break; + default: + cout << "Unknown detector type." << endl; + qDefs::Message(qDefs::CRITICAL,"Unknown detector type.","qTabMeasurement::SetupTimingMode"); + exit(-1); + break; + } + } + + GetModeFromDetector(true); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::GetModeFromDetector(bool startup){ +#ifdef VERBOSE + cout << "Getting timing mode" << endl; +#endif + //Get timing mode from detector + slsDetectorDefs::externalCommunicationMode mode = myDet->setExternalCommunicationMode(); + + //Setting the timing mode in gui + if(model && model->itemFromIndex(model->index(mode+1,comboTimingMode->modelColumn(), comboTimingMode->rootModelIndex()))->isEnabled()){ + + //these are things checked in setuptimingmode + + // to let qdrawplot know that triggers or frames are used + myPlot->setFrameEnabled(lblNumFrames->isEnabled()); + myPlot->setTriggerEnabled(lblNumTriggers->isEnabled()); + if((!startup) && (comboTimingMode->currentIndex() == (mode+1))){ + if(lblPeriod->isEnabled()) + CheckAcqPeriodGreaterThanExp(); + else{ + spinPeriod->setToolTip(acqPeriodTip); + lblPeriod->setToolTip(acqPeriodTip); + lblPeriod->setPalette(lblTimingMode->palette()); + lblPeriod->setText("Acquisition Period:"); + } + EnableProbes(); + emit CheckPlotIntervalSignal(); + return; + } + + //if the timing mode is Auto and + // number of Frames and number of triggers is 1, + // then the timing mode is 'None'. + // This is for the inexperienced user + if(mode==slsDetectorDefs::AUTO_TIMING){ + int frames = spinNumFrames->value(); + int triggers = spinNumTriggers->value(); + if((frames==1)&&(triggers==1)){ + comboTimingMode->setCurrentIndex((int)None); + SetTimingMode((int)None); + }else{ + comboTimingMode->setCurrentIndex((int)Auto); + SetTimingMode((int)Auto); + } + }else{ + //mode +1 since the detector class has no timingmode as "None" + comboTimingMode->setCurrentIndex((int)mode+1); + SetTimingMode((int)mode+1); + } + } + // Mode NOT ENABLED. + // This should not happen -only if the server and gui has a mismatch + // on which all modes are allowed in detectors + else{ + //check if the detector is not even connected + string offline = myDet->checkOnline(); + qDefs::checkErrorMessage(myDet,"qTabMeasurement::GetModeFromDetector"); + + if(!offline.empty()){ + qDefs::Message(qDefs::CRITICAL,string("The detector(s) ")+offline+string(" is/are not connected. Exiting GUI."),"Main"); + cout << "The detector(s) " << offline << " is/are not connected. Exiting GUI." << endl; + exit(-1); + } + cout << "Unknown Timing Mode " << mode << " detected from detector" << endl; + qDefs::Message(qDefs::WARNING,"Unknown Timing Mode detected from detector." + "\n\nSetting the following defaults:\nTiming Mode \t: None\n" + "Number of Frames \t: 1\nNumber of Triggers \t: 1","qTabMeasurement::GetModeFromDetector"); + comboTimingMode->setCurrentIndex((int)None); + SetTimingMode((int)None); + } + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::GetModeFromDetector"); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + + +void qTabMeasurement::Initialization(){ + //Number of Measurements + connect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + //File Name + connect(dispFileName, SIGNAL(editingFinished()),this, SLOT(setFileName())); + //File Index + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + //Start/Stop Acquisition + connect(btnStartStop, SIGNAL(clicked()), this, SLOT(startStopAcquisition())); + //Timing Mode + connect(comboTimingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(SetTimingMode(int)));// + //progress bar + connect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); + //enable write to file + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + //Number of Frames + connect(spinNumFrames,SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + //Exposure Time + connect(spinExpTime,SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); + connect(comboExpUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); + //Frame Period between exposures + connect(spinPeriod,SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); + connect(comboPeriodUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); + //Number of Triggers + connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + //Delay After Trigger + connect(spinDelay,SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + connect(comboDelayUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); + //Number of Gates + connect(spinNumGates,SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); + //Number of Probes + connect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::Enable(bool enable){ + frameTimeResolved->setEnabled(enable); + frameNotTimeResolved->setEnabled(enable); + + //shortcut each time, else it doesnt work a second time + btnStartStop->setShortcut(QApplication::translate("TabMeasurementObject", "Shift+Space", 0, QApplication::UnicodeUTF8)); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::startStopAcquisition(){ + if(btnStartStop->isChecked()){ + + //if file write enabled and output dir doesnt exist + if((chkFile->isChecked())&&(thisParent->DoesOutputDirExist() == slsDetectorDefs::FAIL)){ + if(qDefs::Message(qDefs::QUESTION, + "Your data will not be saved.
Disable File write and Proceed with acquisition anyway?", + "qTabMeasurement::startStopAcquisition") == slsDetectorDefs::FAIL){ + disconnect(btnStartStop,SIGNAL(clicked()),this,SLOT(startStopAcquisition())); + btnStartStop->click(); + connect(btnStartStop,SIGNAL(clicked()),this,SLOT(startStopAcquisition())); + return; + }else{ + //done because for receiver it cant save a file with blank file path and returns without acquiring even to the gui + disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + chkFile->setChecked(false); + EnableFileWrite(false); + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + } + } + +#ifdef VERBOSE + cout << endl << endl << "Starting Acquisition" << endl; +#endif + //btnStartStop->setStyleSheet("color:red"); + btnStartStop->setText("Stop"); + btnStartStop->setIcon(*iconStop); + lblProgressIndex->setText(QString::number(0)); + Enable(0); + progressBar->setValue(0); + progressTimer->start(100); + + emit StartSignal(); + }else{ +#ifdef VERBOSE + cout << "Stopping Acquisition" << endl<< endl; +#endif + //emit StopSignal(); commented out to prevent undefined state + myDet->stopAcquisition(); + /* commented out to prevent undefined state + myDet->waitForReceiverReadToFinish(); + UpdateProgress(); + //spin index + disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + spinIndex->setValue(myDet->getFileIndex()); + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + progressTimer->stop(); + btnStartStop->setText("Start"); + btnStartStop->setIcon(*iconStart); + btnStartStop->setChecked(false); + Enable(1);*/ + } + qDefs::checkErrorMessage(myDet,"qTabMeasurement::startStopAcquisition"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::UpdateFinished(){ + UpdateProgress(); + disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + spinIndex->setValue(myDet->getFileIndex()); + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + progressTimer->stop(); + + disconnect(btnStartStop,SIGNAL(clicked()),this,SLOT(startStopAcquisition())); + btnStartStop->setText("Start"); + btnStartStop->setIcon(*iconStart); + btnStartStop->setChecked(false); + Enable(1); + connect(btnStartStop,SIGNAL(clicked()),this,SLOT(startStopAcquisition())); + qDefs::checkErrorMessage(myDet,"qTabMeasurement::UpdateFinished"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::SetCurrentMeasurement(int val){ + if((val)value()) + lblCurrentMeasurement->setText(QString::number(val)); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::UpdateProgress(){ + progressBar->setValue((int)myPlot->GetProgress()); + lblProgressIndex->setText(QString::number(myPlot->GetFrameIndex())); + qDefs::checkErrorMessage(myDet,"qTabMeasurement::UpdateProgress"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setFileName(){ + QString fName = dispFileName->text(); +#ifdef VERBOSE + cout << "Setting File name to " << fName.toAscii().constData() << endl; +#endif + myDet->setFileName(fName.toAscii().data()); + + disconnect(dispFileName, SIGNAL(editingFinished()),this, SLOT(setFileName())); + dispFileName->setText(QString(myDet->getFileName().c_str())); + connect(dispFileName, SIGNAL(editingFinished()),this, SLOT(setFileName())); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setFileName"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabMeasurement::setRunIndex(int index){ +#ifdef VERBOSE + cout << "Setting File Index to " << index << endl; +#endif + myDet->setFileIndex(index); + + disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + spinIndex->setValue(myDet->getFileIndex()); + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setRunIndex"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setNumMeasurements(int val){ +#ifdef VERBOSE + cout << "Setting Number of Measurements to " << val << endl; +#endif + myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,val); + + disconnect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,-1)); + connect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumMeasurements"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setNumFrames(int val){ +#ifdef VERBOSE + cout << "Setting number of frames to " << val << endl; +#endif + myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,val); + + disconnect(spinNumFrames,SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); + connect(spinNumFrames,SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumFrames"); + + EnableProbes(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::CheckAcqPeriodGreaterThanExp(){ + double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(),spinExpTime->value()); + double acqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(),spinPeriod->value()); + if(exptimeNS>acqtimeNS) { + spinPeriod->setToolTip(errPeriodTip); + lblPeriod->setToolTip(errPeriodTip); + lblPeriod->setPalette(red); + lblPeriod->setText("Acquisition Period:*"); + } + else { + spinPeriod->setToolTip(acqPeriodTip); + lblPeriod->setToolTip(acqPeriodTip); + lblPeriod->setPalette(lblTimingMode->palette()); + lblPeriod->setText("Acquisition Period:"); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setExposureTime(){ + //Get the value of timer in ns + double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(),spinExpTime->value()); +#ifdef VERBOSE + cout << "Setting acquisition time to " << exptimeNS << " clocks" << "/" << spinExpTime->value() << qDefs::getUnitString((qDefs::timeUnit)comboExpUnit->currentIndex()) << endl; +#endif + myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,(int64_t)exptimeNS); + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setExposureTime"); + + if(lblPeriod->isEnabled()) + CheckAcqPeriodGreaterThanExp(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setAcquisitionPeriod(){ + //Get the value of timer in ns + double acqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(),spinPeriod->value()); +#ifdef VERBOSE + cout << "Setting frame period between exposures to " << acqtimeNS << " clocks"<< "/" << spinPeriod->value() << qDefs::getUnitString((qDefs::timeUnit)comboPeriodUnit->currentIndex()) << endl; +#endif + myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,(int64_t)acqtimeNS); + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setAcquisitionPeriod"); + + CheckAcqPeriodGreaterThanExp(); + //Check if the interval between plots is ok + emit CheckPlotIntervalSignal(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setNumTriggers(int val){ +#ifdef VERBOSE + cout << "Setting number of triggers to " << val << endl; +#endif + myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,val); + + disconnect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); + connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumTriggers"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setDelay(){ + //Get the value of timer in ns + double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboDelayUnit->currentIndex(),spinDelay->value()); +#ifdef VERBOSE + cout << "Setting delay after trigger to " << exptimeNS << " clocks" << "/" << spinDelay->value() << qDefs::getUnitString((qDefs::timeUnit)comboDelayUnit->currentIndex()) << endl; +#endif + myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,(int64_t)exptimeNS); +/* + //updating value set + disconnect(spinDelay,SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + disconnect(comboDelayUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); + qDefs::timeUnit unit; + double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,-1)*(1E-9)))); + spinDelay->setValue(time); + comboDelayUnit->setCurrentIndex((int)unit); + connect(spinDelay,SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + connect(comboDelayUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); +*/ + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setDelay"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setNumGates(int val){ +#ifdef VERBOSE + cout << "Setting number of gates to " << val << endl; +#endif + myDet->setTimer(slsDetectorDefs::GATES_NUMBER,val); + + disconnect(spinNumGates,SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); + spinNumGates->setValue((int)myDet->setTimer(slsDetectorDefs::GATES_NUMBER,-1)); + connect(spinNumGates,SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumGates"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::setNumProbes(int val){ +#ifdef VERBOSE + cout << "Setting number of probes to " << val << endl; +#endif + disconnect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + disconnect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); + + //set probes + int ret = myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,val); + if(ret != val) + ret = myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1); + spinNumProbes->setValue(ret); + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumProbes"); + + + //Setting number of probes should reset number of triggers to 1, need to check if enabled, cuz its updated when refresh + if((spinNumProbes->isEnabled()) && (ret > 0) && (spinNumTriggers->value() != 1)){ + qDefs::Message(qDefs::INFORMATION,"Number of Triggers has been reset to 1.
" + "This is mandatory to use probes.","qTabMeasurement::setNumProbes"); + cout << "Resetting Number of triggers to 1" << endl; + spinNumTriggers->setValue(1); + } + qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumProbes"); + + connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + connect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::SetTimingMode(int mode){ +#ifdef VERBOSE + cout << "Setting Timing mode to " << comboTimingMode->currentText().toAscii().data() << endl; +#endif + //Default settings + lblNumFrames->setEnabled(false); spinNumFrames->setEnabled(false); + lblExpTime->setEnabled(false); spinExpTime->setEnabled(false); comboExpUnit->setEnabled(false); + lblPeriod->setEnabled(false); spinPeriod->setEnabled(false); comboPeriodUnit->setEnabled(false); + lblNumTriggers->setEnabled(false); spinNumTriggers->setEnabled(false); + lblDelay->setEnabled(false); spinDelay->setEnabled(false); comboDelayUnit->setEnabled(false); + lblNumGates->setEnabled(false); spinNumGates->setEnabled(false); + lblNumProbes->setEnabled(false); spinNumProbes->setEnabled(false); + + bool success = false; + switch(mode){ + case None://Exposure Time + lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); + spinNumTriggers->setValue(1); + spinNumFrames->setValue(1); + if(myDet->setExternalCommunicationMode(slsDetectorDefs::AUTO_TIMING)==slsDetectorDefs::AUTO_TIMING) + success = true; + break; + case Auto://#Frames, ExpTime, Period + spinNumTriggers->setValue(1); + lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); + lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); + lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); + if(myDet->setExternalCommunicationMode(slsDetectorDefs::AUTO_TIMING)==slsDetectorDefs::AUTO_TIMING) + success = true; + break; + case Trigger_Exp_Series://#(Frames), #Triggers, ExpTime, Period, (Delay) + if(detType == slsDetectorDefs::EIGER) //only 1 frame for each trigger for eiger + spinNumFrames->setValue(1); + else{ + lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); + lblDelay->setEnabled(true); spinDelay->setEnabled(true); comboDelayUnit->setEnabled(true); + lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); + } + lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); + lblNumTriggers->setEnabled(true); spinNumTriggers->setEnabled(true); + if(myDet->setExternalCommunicationMode(slsDetectorDefs::TRIGGER_EXPOSURE)==slsDetectorDefs::TRIGGER_EXPOSURE) + success = true; + break; + case Trigger_Readout://#Frames, ExpTime, Period, (Delay) + spinNumTriggers->setValue(1); + lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); + lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); + lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); + if(myDet->setExternalCommunicationMode(slsDetectorDefs::TRIGGER_READOUT)==slsDetectorDefs::TRIGGER_READOUT) + success = true; + break; + case Gated://#Frames, #(Gates) + if(detType != slsDetectorDefs::EIGER){ + lblNumGates->setEnabled(true); spinNumGates->setEnabled(true); + } + spinNumTriggers->setValue(1); + lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); + + + if(myDet->setExternalCommunicationMode(slsDetectorDefs::GATE_FIX_NUMBER)==slsDetectorDefs::GATE_FIX_NUMBER) + success = true; + break; + case Gated_Start://#Frames, #Triggers, #Gates, ExpTime, Period + lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); + lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); + lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); + lblNumTriggers->setEnabled(true); spinNumTriggers->setEnabled(true); + lblNumGates->setEnabled(true); spinNumGates->setEnabled(true); + if(myDet->setExternalCommunicationMode(slsDetectorDefs::GATE_WITH_START_TRIGGER)==slsDetectorDefs::GATE_WITH_START_TRIGGER) + success = true; + break; + case Burst_Trigger://#Frames, ExpTime, Period, (Delay) + spinNumTriggers->setValue(1); + if(detType != slsDetectorDefs::EIGER){ + lblDelay->setEnabled(true); spinDelay->setEnabled(true); comboDelayUnit->setEnabled(true); + } + lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); + lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); + lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); + if(myDet->setExternalCommunicationMode(slsDetectorDefs::BURST_TRIGGER)==slsDetectorDefs::BURST_TRIGGER) + success = true; + break; + default: + cout << "Timing mode unknown to GUI" << endl; + //This should never happen + qDefs::Message(qDefs::CRITICAL,"Timing mode unknown to GUI","qTabMeasurement::SetTimingMode"); + qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetTimingMode"); + exit(-1); + } + qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetTimingMode"); + if(!success){ + qDefs::Message(qDefs::WARNING,"The detector timing mode could not be set.\n" + "Please check the external flags." + "\n\nSetting the following defaults:\nTiming Mode \t: None\n" + "Number of Frames \t: 1\nNumber of Triggers \t: 1","qTabMeasurement::SetTimingMode"); + spinNumFrames->setValue(1); + spinNumTriggers->setValue(1); + comboTimingMode->setCurrentIndex((int)None); + return; + } + + + //Frame Period between exposures + qDefs::timeUnit unit; + if(lblPeriod->isEnabled()) + CheckAcqPeriodGreaterThanExp(); + else{ + spinPeriod->setToolTip(acqPeriodTip); + lblPeriod->setToolTip(acqPeriodTip); + lblPeriod->setPalette(lblTimingMode->palette()); + lblPeriod->setText("Acquisition Period:"); + } + + + //Check if Number of Probes should be enabled + EnableProbes(); + + // to let qdrawplot know that triggers or frames are used + myPlot->setFrameEnabled(lblNumFrames->isEnabled()); + myPlot->setTriggerEnabled(lblNumTriggers->isEnabled()); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetTimingMode"); + + emit CheckPlotIntervalSignal(); + + return; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::EnableFileWrite(bool enable){ +#ifdef VERBOSE + cout << "Enable File Write:" << enable << endl; +#endif + myDet->enableWriteToFile(enable); + dispFileName->setEnabled(enable); + if(enable) setFileName(); + myPlot->SetEnableFileWrite(enable); + + disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + chkFile->setChecked(myDet->enableWriteToFile()); + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::EnableFileWrite"); +}; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::Refresh(){ +#ifdef VERBOSE + cout << endl << "**Updating Measurement Tab" << endl; +#endif + + if(!myPlot->isRunning()){ + //to prevent it from recalculating forever + disconnect(spinNumMeasurements, SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + disconnect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); + disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + disconnect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); + disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + disconnect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + disconnect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); + disconnect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); + disconnect(spinPeriod, SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); + disconnect(comboPeriodUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); + disconnect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + disconnect(spinDelay, SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + disconnect(comboDelayUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); + disconnect(spinNumGates, SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); + +#ifdef VERBOSE + cout << "Getting number of measurements & frames" << endl; +#endif + //Number of measurements + spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,-1)); + //Number of frames + spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); + + +#ifdef VERBOSE + cout << "Getting Exposure time and Acquisition Period" << endl; +#endif + //Exp Time + qDefs::timeUnit unit; + double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-9)))); + spinExpTime->setValue(time); + comboExpUnit->setCurrentIndex((int)unit); + //period + time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1)*(1E-9)))); + spinPeriod->setValue(time); + comboPeriodUnit->setCurrentIndex((int)unit); + + +#ifdef VERBOSE + cout << "Getting delay after trigger, number of triggers and number of gates" << endl; +#endif + //delay + time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,-1)*(1E-9)))); + spinDelay->setValue(time); + comboDelayUnit->setCurrentIndex((int)unit); + //Number of Triggers + spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); + //gates + spinNumGates->setValue((int)myDet->setTimer(slsDetectorDefs::GATES_NUMBER,-1)); + + +#ifdef VERBOSE + cout << "Getting file name prefix, file index, file write enable and progress index" << endl; +#endif + //File Name + dispFileName->setText(QString(myDet->getFileName().c_str())); + //File Index + spinIndex->setValue(myDet->getFileIndex()); + //file write enabled/disabled + chkFile->setChecked(myDet->enableWriteToFile()); + + //progress label index + if(myDet->getFrameIndex()==-1) + lblProgressIndex->setText("0"); + else + lblProgressIndex->setText(QString::number(myDet->getFrameIndex())); + + connect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + connect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + connect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + connect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); + connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); + connect(spinPeriod, SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); + connect(comboPeriodUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); + connect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + connect(spinDelay, SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + connect(comboDelayUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); + connect(spinNumGates, SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); + + //timing mode - will also check if exptime>acq period and also enableprobes() + GetModeFromDetector(); + + // to let qdrawplot know that triggers or frames are used + myPlot->setFrameEnabled(lblNumFrames->isEnabled()); + myPlot->setTriggerEnabled(lblNumTriggers->isEnabled()); + + qDefs::checkErrorMessage(myDet,"qTabMeasurement::Refresh"); + } + +#ifdef VERBOSE + cout << "**Updated Measurement Tab" << endl << endl; +#endif +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabMeasurement::EnableProbes(){ + + //disconnect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); + disconnect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + + + //enabled only in expert mode and if #Frames > 1 + if((expertMode)&&(detType==slsDetectorDefs::MYTHEN)&&(spinNumFrames->value()>1)){ + lblNumProbes->setEnabled(true); + spinNumProbes->setEnabled(true); + spinNumProbes->setValue((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1)); +#ifdef VERBOSE + cout << "Getting number of probes : " << spinNumProbes->value() << endl; +#endif + + //Setting number of probes should reset number of triggers to 1, need to check if enabled, cuz its updated when refresh + if((spinNumProbes->isEnabled()) && (spinNumProbes->value() > 0) && (spinNumTriggers->value() != 1)){ + qDefs::Message(qDefs::INFORMATION,"Number of Triggers has been reset to 1.
" + "This is mandatory to use probes.","qTabMeasurement::EnableProbes"); + cout << "Resetting Number of triggers to 1" << endl; + spinNumTriggers->setValue(1); + } + qDefs::checkErrorMessage(myDet,"qTabMeasurement::EnableProbes"); + + connect(spinNumProbes, SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); + connect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + return; + } + cout << "Probes not enabled" << endl; + if(detType==slsDetectorDefs::MYTHEN) + spinNumProbes->setValue(0); + lblNumProbes->setEnabled(false); + spinNumProbes->setEnabled(false); + + //connect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); + connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qTabMessages.cpp b/slsDetectorGui/src/qTabMessages.cpp new file mode 100644 index 0000000000..4c9a65850d --- /dev/null +++ b/slsDetectorGui/src/qTabMessages.cpp @@ -0,0 +1,122 @@ +/* + * qTabMessages.cpp + * + * Created on: Jun 26, 2012 + * Author: l_maliakal_d + */ + +/** Qt Project Class Headers */ +#include "qTabMessages.h" +#include "qDetectorMain.h" +/** Project Class Headers */ +/** Qt Include Headers */ +#include +#include +#include +#include + + +/** C++ Include Headers */ +#include +#include +using namespace std; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +qTabMessages::qTabMessages(qDetectorMain* m):myMainTab(m),qout(0),qerr(0){ + SetupWidgetWindow(); + Initialization(); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +qTabMessages::~qTabMessages(){ + delete myMainTab; + delete dispLog; + delete qout; + delete qerr; +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabMessages::SetupWidgetWindow(){ + /** Layout */ + QGridLayout *gridLayout = new QGridLayout(this); + + dispLog = new QTextEdit(this); + dispLog->setReadOnly(true); + dispLog->setFocusPolicy(Qt::NoFocus); + dispLog->setTextColor(Qt::darkBlue); + + + btnSave = new QPushButton("Save Log ",this); + btnSave->setFocusPolicy(Qt::NoFocus); + btnSave->setFixedWidth(100); + btnSave->setIcon(QIcon( ":/icons/images/save.png" )); + + btnClear = new QPushButton("Clear ",this); + btnClear->setFocusPolicy(Qt::NoFocus); + btnClear->setFixedWidth(100); + btnClear->setIcon(QIcon( ":/icons/images/erase.png" )); + + gridLayout->addItem(new QSpacerItem(15,10,QSizePolicy::Fixed,QSizePolicy::Fixed),0,0); + gridLayout->addWidget(btnSave,1,0,1,1); + gridLayout->addWidget(btnClear,1,4,1,1); + gridLayout->addItem(new QSpacerItem(15,10,QSizePolicy::Fixed,QSizePolicy::Fixed),2,0); + gridLayout->addWidget(dispLog,3,0,1,5); + + errMsg = " Please check Messages Tab. Following message was caught:

"; + qout=new qDebugStream(std::cout,this); + qerr=new qDebugStream(std::cerr,this); + +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabMessages::Initialization(){ + connect(btnSave,SIGNAL(clicked()),this,SLOT(SaveLog())); + connect(btnClear,SIGNAL(clicked()),this,SLOT(ClearLog())); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabMessages::customEvent(QEvent *e) { + if (e->type() == (STREAMEVENT)){ + QString temp = ((qStreamEvent*)e)->getString(); + dispLog->append(temp); + } + +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabMessages::SaveLog() { + QString fName = QString(myMainTab->GetFilePath()); + fName = fName+"/LogFile.txt"; + fName = QFileDialog::getSaveFileName(this,tr("Save Snapshot "), + fName,tr("Text files (*.txt);;All Files(*)")); + if (!fName.isEmpty()){ + QFile outfile; + outfile.setFileName(fName); + if(outfile.open(QIODevice::WriteOnly | QIODevice::Text)){//Append + QTextStream out(&outfile); + out<toPlainText() << endl; + qDefs::Message(qDefs::INFORMATION,string("The Log has been successfully saved to " + "")+fName.toAscii().constData(),"qTabMessages::SaveLog"); + } + else qDefs::Message(qDefs::WARNING,"Attempt to save log file failed.","qTabMessages::SaveLog"); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabMessages::ClearLog() { + dispLog->clear(); +#ifdef VERBOSE + cout<<"Log Cleared"< +// C++ Include Headers +#include +#include +#include +using namespace std; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +const QString qTabPlot::modeNames[5]={"None","Energy Scan","Threshold Scan","Trimbits Scan","Custom Script Scan"}; + +QString qTabPlot::defaultPlotTitle(""); +QString qTabPlot::defaultHistXAxisTitle("Channel Number"); +QString qTabPlot::defaultHistYAxisTitle("Counts"); +QString qTabPlot::defaultImageXAxisTitle("Pixel"); +QString qTabPlot::defaultImageYAxisTitle("Pixel"); +QString qTabPlot::defaultImageZAxisTitle("Intensity"); + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabPlot::qTabPlot(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot): + QWidget(parent), + myDet(detector), + myPlot(plot), + isOneD(false), + isOriginallyOneD(false), + wrongInterval(0), + stackedLayout(0), + spinNthFrame(0), + spinTimeGap(0), + comboTimeGapUnit(0), + btnGroupScan(0), + btnGroupPlotType(0), + btnGroupHistogram(0){ + setupUi(this); + SetupWidgetWindow(); + Initialization(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +qTabPlot::~qTabPlot(){ + delete myDet; + delete myPlot; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetupWidgetWindow(){ + //error for interval between plots + red = new QPalette();; + red->setColor(QPalette::Active,QPalette::WindowText,Qt::red); + intervalTip = boxFrequency->toolTip(); + + +//scan arguments + btnGroupScan = new QButtonGroup(this); + btnGroupScan->addButton(radioLevel0,0); + btnGroupScan->addButton(radioLevel1,1); + btnGroupScan->addButton(radioFileIndex,2); + btnGroupScan->addButton(radioAllFrames,3); + +//plot type + btnGroupPlotType = new QButtonGroup(this); + btnGroupPlotType->addButton(radioNoPlot,0); + btnGroupPlotType->addButton(radioDataGraph,1); + btnGroupPlotType->addButton(radioHistogram,2); + +//histogram arguments + btnGroupHistogram = new QButtonGroup(this); + btnGroupHistogram->addButton(radioHistIntensity,0); + btnGroupHistogram->addButton(radioHistLevel0,1); + btnGroupHistogram->addButton(radioHistLevel1,2); + +// Plot Axis + dispTitle->setEnabled(false); + dispXAxis->setEnabled(false); + dispYAxis->setEnabled(false); + dispZAxis->setEnabled(false); + dispXMin->setEnabled(false); + dispYMin->setEnabled(false); + dispZMin->setEnabled(false); + dispXMax->setEnabled(false); + dispYMax->setEnabled(false); + dispZMax->setEnabled(false); + dispXMin->setValidator(new QDoubleValidator(dispXMin)); + dispYMin->setValidator(new QDoubleValidator(dispYMin)); + dispZMin->setValidator(new QDoubleValidator(dispZMin)); + dispXMax->setValidator(new QDoubleValidator(dispXMax)); + dispYMax->setValidator(new QDoubleValidator(dispYMax)); + dispZMax->setValidator(new QDoubleValidator(dispZMax)); + + //default titles + dispTitle->setText(""); + myPlot->SetPlotTitlePrefix(""); + dispXAxis->setText(defaultHistXAxisTitle); + dispYAxis->setText(defaultHistYAxisTitle); + myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); + myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); + dispXAxis->setText(defaultImageXAxisTitle); + dispYAxis->setText(defaultImageYAxisTitle); + dispZAxis->setText(defaultImageZAxisTitle); + myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); + myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); + myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); + + // Plotting Frequency + + stackedLayout = new QStackedLayout; + stackedLayout->setSpacing(0); + spinNthFrame = new QSpinBox; + spinNthFrame->setMinimum(1); + spinNthFrame->setMaximum(2000000000); + spinTimeGap = new QDoubleSpinBox; + spinTimeGap->setMinimum(0); + spinTimeGap->setDecimals(3); + spinTimeGap->setMaximum(999999); + spinTimeGap->setValue(myPlot->GetMinimumPlotTimer()); + comboTimeGapUnit = new QComboBox; + comboTimeGapUnit->addItem("hr"); + comboTimeGapUnit->addItem("min"); + comboTimeGapUnit->addItem("s"); + comboTimeGapUnit->addItem("ms"); + comboTimeGapUnit->setCurrentIndex(3); + QWidget *w = new QWidget; + QHBoxLayout *h1 = new QHBoxLayout; + w->setLayout(h1); + h1->setContentsMargins(0,0,0,0); + h1->setSpacing(3); + h1->addWidget(spinTimeGap); + h1->addWidget(comboTimeGapUnit); + + stackedLayout->addWidget(w); + stackedLayout->addWidget(spinNthFrame); + stackWidget->setLayout(stackedLayout); + + stackedWidget->setCurrentIndex(0); + stackedWidget_2->setCurrentIndex(0); + + // Depending on whether the detector is 1d or 2d + switch(myDet->getDetectorsType()){ + case slsDetectorDefs::MYTHEN: + isOriginallyOneD = true; + pagePedestal->setEnabled(false); + pagePedestal_2->setEnabled(false); + chkBinary->setEnabled(false); + chkBinary_2->setEnabled(false); + break; + case slsDetectorDefs::EIGER: + isOriginallyOneD = false; + pagePedestal->setEnabled(false); + pagePedestal_2->setEnabled(false); + chkBinary->setEnabled(false); + chkBinary_2->setEnabled(false); + break; + case slsDetectorDefs::GOTTHARD: + isOriginallyOneD = true; + break; + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::MOENCH: + case slsDetectorDefs::JUNGFRAU: + isOriginallyOneD = false; + break; + default: + cout << "ERROR: Detector Type is Generic" << endl; + exit(-1); + } + + Select1DPlot(isOriginallyOneD); + + //to check if this should be enabled + EnableScanBox(); + + //disable histogram initially + boxHistogram->hide(); + + qDefs::checkErrorMessage(myDet,"qTabPlot::SetupWidgetWindow"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetPlotOptionsRightPage(){ + if(isOneD){ + int i = stackedWidget->currentIndex(); + if(i == (stackedWidget->count()-1)) + stackedWidget->setCurrentIndex(0); + else + stackedWidget->setCurrentIndex(i+1); + box1D->setTitle(QString("1D Plot Options %1").arg(stackedWidget->currentIndex()+1)); + } + else{ + int i = stackedWidget_2->currentIndex(); + if(i == (stackedWidget_2->count()-1)) + stackedWidget_2->setCurrentIndex(0); + else + stackedWidget_2->setCurrentIndex(i+1); + box2D->setTitle(QString("2D Plot Options %1").arg(stackedWidget_2->currentIndex()+1)); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetPlotOptionsLeftPage(){ + if(isOneD){ + int i = stackedWidget->currentIndex(); + if(i == 0) + stackedWidget->setCurrentIndex(stackedWidget->count()-1); + else + stackedWidget->setCurrentIndex(i-1); + box1D->setTitle(QString("1D Plot Options %1").arg(stackedWidget->currentIndex()+1)); + } + else{ + int i = stackedWidget_2->currentIndex(); + if(i == 0) + stackedWidget_2->setCurrentIndex(stackedWidget_2->count()-1); + else + stackedWidget_2->setCurrentIndex(i-1); + box2D->setTitle(QString("2D Plot Options %1").arg(stackedWidget_2->currentIndex()+1)); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::Select1DPlot(bool b){ +#ifdef VERBOSE + if(b) + cout << "Selecting 1D Plot" << endl; + else + cout << "Selecting 2D Plot" << endl; +#endif + isOneD = b; + lblFrom->setEnabled(false); + lblTo->setEnabled(false); + lblFrom_2->setEnabled(false); + lblTo_2->setEnabled(false); + spinFrom->setEnabled(false); + spinFrom_2->setEnabled(false); + spinTo->setEnabled(false); + spinTo_2->setEnabled(false); + if(b){ + box1D->show(); + box2D->hide(); + chkZAxis->setEnabled(false); + chkZMin->setEnabled(false); + chkZMax->setEnabled(false); + myPlot->Select1DPlot(); + }else{ + box1D->hide(); + box2D->show(); + chkZAxis->setEnabled(true); + chkZMin->setEnabled(true); + chkZMax->setEnabled(true); + myPlot->Select2DPlot(); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::Initialization(){ +// Plot arguments box + connect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); +// Histogram arguments box + connect(btnGroupHistogram,SIGNAL(buttonClicked(int)),this, SLOT(SetHistogramOptions())); +// Scan box + connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); +// Snapshot box + connect(btnClone, SIGNAL(clicked()),myPlot, SLOT(ClonePlot())); + connect(btnCloseClones, SIGNAL(clicked()),myPlot, SLOT(CloseClones())); + connect(btnSaveClones, SIGNAL(clicked()),myPlot, SLOT(SaveClones())); +// 1D Plot box + //to change pages + connect(btnRight, SIGNAL(clicked()), this, SLOT(SetPlotOptionsRightPage())); + connect(btnLeft, SIGNAL(clicked()), this, SLOT(SetPlotOptionsLeftPage())); + + connect(chkSuperimpose, SIGNAL(toggled(bool)), this, SLOT(EnablePersistency(bool))); + connect(spinPersistency,SIGNAL(valueChanged(int)), myPlot,SLOT(SetPersistency(int))); + connect(chkPoints, SIGNAL(toggled(bool)), myPlot, SLOT(SetMarkers(bool))); + connect(chkLines, SIGNAL(toggled(bool)), myPlot, SLOT(SetLines(bool))); + connect(chk1DLog, SIGNAL(toggled(bool)), myPlot, SIGNAL(LogySignal(bool))); + connect(chkStatistics, SIGNAL(toggled(bool)), myPlot, SLOT(DisplayStatistics(bool))); + +// 2D Plot box + connect(chkInterpolate, SIGNAL(toggled(bool)),myPlot, SIGNAL(InterpolateSignal(bool))); + connect(chkContour, SIGNAL(toggled(bool)),myPlot, SIGNAL(ContourSignal(bool))); + connect(chkLogz, SIGNAL(toggled(bool)),myPlot, SIGNAL(LogzSignal(bool))); + connect(chkStatistics_2,SIGNAL(toggled(bool)),myPlot, SLOT(DisplayStatistics(bool))); +// Plotting frequency box + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); +// Plot Axis * + connect(chkTitle, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(chkXAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(chkYAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(chkZAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(dispTitle, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); + connect(dispXAxis, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); + connect(dispYAxis, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); + connect(dispZAxis, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); + + connect(chkXMin, SIGNAL(toggled(bool)), this, SLOT(EnableRange())); + connect(chkXMax, SIGNAL(toggled(bool)), this, SLOT(EnableRange())); + connect(chkYMin, SIGNAL(toggled(bool)), this, SLOT(EnableRange())); + connect(chkYMax, SIGNAL(toggled(bool)), this, SLOT(EnableRange())); + connect(chkZMin, SIGNAL(toggled(bool)), this, SLOT(EnableZRange())); + connect(chkZMax, SIGNAL(toggled(bool)), this, SLOT(EnableZRange())); + connect(this, SIGNAL(ResetZMinZMaxSignal(bool,bool,double,double)), myPlot, SIGNAL(ResetZMinZMaxSignal(bool,bool,double,double))); + + connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetAxesRange())); + connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetAxesRange())); + connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetAxesRange())); + connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetAxesRange())); + connect(dispZMin, SIGNAL(editingFinished()), this, SLOT(SetZRange())); + connect(dispZMax, SIGNAL(editingFinished()), this, SLOT(SetZRange())); +// Save + connect(btnSave, SIGNAL(clicked()), myPlot, SLOT(SavePlot())); + connect(chkSaveAll, SIGNAL(toggled(bool)), myPlot, SLOT(SaveAll(bool))); + + connect(this,SIGNAL(SetZRangeSignal(double,double)),myPlot, SIGNAL(SetZRangeSignal(double,double))); + +//pedstal + connect(chkPedestal, SIGNAL(toggled(bool)), myPlot, SLOT(SetPedestal(bool))); + connect(btnRecalPedestal, SIGNAL(clicked()), myPlot, SLOT(RecalculatePedestal())); + connect(chkPedestal_2, SIGNAL(toggled(bool)), myPlot, SLOT(SetPedestal(bool))); + connect(btnRecalPedestal_2, SIGNAL(clicked()), myPlot, SLOT(RecalculatePedestal())); + +//accumulate + connect(chkAccumulate, SIGNAL(toggled(bool)), myPlot, SLOT(SetAccumulate(bool))); + connect(btnResetAccumulate, SIGNAL(clicked()), myPlot, SLOT(ResetAccumulate())); + connect(chkAccumulate_2, SIGNAL(toggled(bool)), myPlot, SLOT(SetAccumulate(bool))); + connect(btnResetAccumulate_2, SIGNAL(clicked()), myPlot, SLOT(ResetAccumulate())); + + //binary + connect(chkBinary, SIGNAL(toggled(bool)), this, SLOT(SetBinary())); + connect(chkBinary_2, SIGNAL(toggled(bool)), this, SLOT(SetBinary())); + connect(spinFrom, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); + connect(spinFrom_2, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); + connect(spinTo, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); + connect(spinTo_2, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::EnablePersistency(bool enable){ +#ifdef VERBOSE + if(enable) + cout << "Enabling Persistency" << endl; + else + cout << "Disabling Persistency" << endl; +#endif + lblPersistency->setEnabled(enable); + spinPersistency->setEnabled(enable); + if(enable) myPlot->SetPersistency(spinPersistency->value()); + else myPlot->SetPersistency(0); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetTitles(){ +#ifdef VERBOSE + cout << "Setting Plot Titles" << endl; +#endif + // Plot Title + if(dispTitle->isEnabled()) + myPlot->SetPlotTitlePrefix(dispTitle->text()); + // X Axis + if(dispXAxis->isEnabled()){ + if(isOneD) myPlot->SetHistXAxisTitle(dispXAxis->text()); + else myPlot->SetImageXAxisTitle(dispXAxis->text()); + } + // Y Axis + if(dispYAxis->isEnabled()){ + if(isOneD) myPlot->SetHistYAxisTitle(dispYAxis->text()); + else myPlot->SetImageYAxisTitle(dispYAxis->text()); + } + // Z Axis + if(dispZAxis->isEnabled()) + myPlot->SetImageZAxisTitle(dispZAxis->text()); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::EnableTitles(){ + // Plot Title + dispTitle->setEnabled(chkTitle->isChecked()); + if(!chkTitle->isChecked()){ + myPlot->SetPlotTitlePrefix(""); + dispTitle->setText(""); + } + // X Axis + dispXAxis->setEnabled(chkXAxis->isChecked()); + if(!chkXAxis->isChecked()){ + if(isOneD){ + myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); + dispXAxis->setText(defaultHistXAxisTitle); + } + else{ + myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); + dispXAxis->setText(defaultImageXAxisTitle); + } + } + // Y Axis + dispYAxis->setEnabled(chkYAxis->isChecked()); + if(!chkYAxis->isChecked()){ + if(isOneD){ + myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); + dispYAxis->setText(defaultHistYAxisTitle); + }else{ + myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); + dispYAxis->setText(defaultImageYAxisTitle); + } + } + // Z Axis + dispZAxis->setEnabled(chkZAxis->isChecked()); + if(!chkZAxis->isChecked()){ + myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); + dispZAxis->setText(defaultImageZAxisTitle); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::EnableRange(){ + bool disableZoom = false; + if(!chkXMin->isChecked()) dispXMin->setEnabled(false); + else{disableZoom = true; dispXMin->setEnabled(true); } + if(!chkXMax->isChecked()) dispXMax->setEnabled(false); + else{disableZoom = true; dispXMax->setEnabled(true); } + if(!chkYMin->isChecked()) dispYMin->setEnabled(false); + else{disableZoom = true; dispYMin->setEnabled(true); } + if(!chkYMax->isChecked()) dispYMax->setEnabled(false); + else{disableZoom = true; dispYMax->setEnabled(true); } + + myPlot->DisableZoom(disableZoom); + emit DisableZoomSignal(disableZoom); + SetAxesRange(); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetAxesRange(){ +#ifdef VERBOSE + cout << "Setting Range" << endl; +#endif + + bool changed = false; + // x min + changed = (dispXMin->isEnabled())&&(!dispXMin->text().isEmpty()); + if(changed) myPlot->SetXYRangeValues(dispXMin->text().toDouble(),qDefs::XMINIMUM); + myPlot->IsXYRangeValues(changed,qDefs::XMINIMUM); + + // x max + changed = (dispXMax->isEnabled())&&(!dispXMax->text().isEmpty()); + if(changed) myPlot->SetXYRangeValues(dispXMax->text().toDouble(),qDefs::XMAXIMUM); + myPlot->IsXYRangeValues(changed,qDefs::XMAXIMUM); + + // y min + changed = (dispYMin->isEnabled())&&(!dispYMin->text().isEmpty()); + if(changed) myPlot->SetXYRangeValues(dispYMin->text().toDouble(),qDefs::YMINIMUM); + myPlot->IsXYRangeValues(changed,qDefs::YMINIMUM); + + // y max + changed = (dispYMax->isEnabled())&&(!dispYMax->text().isEmpty()); + if(changed) myPlot->SetXYRangeValues(dispYMax->text().toDouble(),qDefs::YMAXIMUM); + myPlot->IsXYRangeValues(changed,qDefs::YMAXIMUM); + + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetZRange(){ + emit ResetZMinZMaxSignal( + (chkZMin->isChecked() && CheckZRange(dispZMin->text())), + (chkZMax->isChecked() && CheckZRange(dispZMax->text())), + dispZMin->text().toDouble(), + dispZMax->text().toDouble()); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::EnableZRange(){ + + dispZMin->setEnabled(chkZMin->isChecked()); + dispZMax->setEnabled(chkZMax->isChecked()); + emit ResetZMinZMaxSignal( + (chkZMin->isChecked() && CheckZRange(dispZMin->text())), + (chkZMax->isChecked() && CheckZRange(dispZMax->text())), + dispZMin->text().toDouble(), + dispZMax->text().toDouble()); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +bool qTabPlot::CheckZRange(QString value){ + if(value.isEmpty()) + return false; + + bool ok; + value.toDouble(&ok); + if(!ok) + return false; + + return true; +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetPlot(){ +#ifdef VERBOSE + cout << "Entering Set Plot()" ; +#endif + if(radioNoPlot->isChecked()){ + cout << " - No Plot" << endl; + + boxScan->show(); + boxHistogram->hide(); + myPlot->EnablePlot(false); + boxSnapshot->setEnabled(false); + boxSave->setEnabled(false); + boxFrequency->setEnabled(false); + boxPlotAxis->setEnabled(false); + boxScan->setEnabled(false); + + }else if(radioDataGraph->isChecked()){ + cout << " - DataGraph" << endl; + + boxScan->show(); + boxHistogram->hide(); + myPlot->EnablePlot(true); + Select1DPlot(isOriginallyOneD); + boxSnapshot->setEnabled(true); + boxSave->setEnabled(true); + boxFrequency->setEnabled(true); + boxPlotAxis->setEnabled(true); + if(!myPlot->isRunning()) + EnableScanBox(); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); + } + else{ + //histogram and 2d scans dont work + if(boxScan->isChecked()){ + qDefs::Message(qDefs::WARNING,"Histogram cannot be used together with 2D Scan Plots.
" + "Uncheck 2D Scan plots to plot Histograms", "qTabPlot::SetPlot"); + radioDataGraph->setChecked(true); + boxScan->show(); + boxHistogram->hide(); + return; + } + + cout << " - Histogram" << endl; + + if(radioHistIntensity->isChecked()){ + pageHistogram->setEnabled(true); + pageHistogram_2->setEnabled(true); + }else{ + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } + boxScan->hide(); + boxHistogram->show(); + myPlot->EnablePlot(true); + Select1DPlot(isOriginallyOneD); + boxSnapshot->setEnabled(true); + boxSave->setEnabled(true); + boxFrequency->setEnabled(true); + boxPlotAxis->setEnabled(true); + if(!myPlot->isRunning()) + EnableScanBox(); + + //qDefs::Message(qDefs::INFORMATION,"Please check the Plot Histogram Options below " + // "before Starting Acquitision","qTabPlot::SetPlot"); + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabPlot::SetFrequency(){ +#ifdef VERBOSE + cout << "Setting Plot Interval Frequency" << endl; +#endif + disconnect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + disconnect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + double timeMS,acqPeriodMS; + double minPlotTimer = myPlot->GetMinimumPlotTimer(); + char cMin[200]; + sprintf(cMin,"%f ms",minPlotTimer); + + + acqPeriodMS = (myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1)*(1E-6)); + //if period is 0, check exptime, if that is also 0, give warning and set to min timer + if(acqPeriodMS==0){ + acqPeriodMS = (myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-6)); + + if(acqPeriodMS==0){ + //to reduce the warnings displayed + if((comboFrequency->currentIndex() == 0) && (spinTimeGap->value() == minPlotTimer)); + else + qDefs::Message(qDefs::WARNING,"Interval between Plots:
" + "Every Nth Image: Period betwen Frames and Exposure Time cannot both be 0 ms.
" + "Resetting to minimum plotting time interval","qTabPlot::SetFrequency"); + comboFrequency->setCurrentIndex(0); + stackedLayout->setCurrentIndex(comboFrequency->currentIndex()); + spinTimeGap->setValue(minPlotTimer); + comboTimeGapUnit->setCurrentIndex(qDefs::MILLISECONDS); + timeMS=minPlotTimer; + //This is done so that its known which one was selected + myPlot->SetFrameFactor(0); + // Setting the timer value(ms) between plots + myPlot->SetPlotTimer(timeMS); + + connect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + qDefs::checkErrorMessage(myDet,"qTabPlot::SetFrequency"); + return; + } + } + + + stackedLayout->setCurrentIndex(comboFrequency->currentIndex()); + switch(comboFrequency->currentIndex()){ + case 0: + // Get the time interval from gui in ms + timeMS = (qDefs::getNSTime((qDefs::timeUnit)comboTimeGapUnit->currentIndex(),spinTimeGap->value()))/(1e6); + + if((int)timeMS==0){ + qDefs::Message(qDefs::WARNING,"Interval between Plots:
" + "Time Interval must be atleast >= 1 ms. Resetting to minimum plotting time interval.","qTabPlot::SetFrequency"); + spinTimeGap->setValue(minPlotTimer); + comboTimeGapUnit->setCurrentIndex(qDefs::MILLISECONDS); + timeMS=minPlotTimer; + } + + + //show red if min intervalInterval between Plots: You might be losing Images!","Plot"); + boxFrequency->setPalette(*red); + boxFrequency->setTitle("Interval between Plots*"); + QString errTip = intervalTip + QString("

" + "Time Interval Condition: min of ")+QString("%1").arg(minPlotTimer)+ + QString("ms.
You might be losing images!
"); + boxFrequency->setToolTip(errTip); + } + //show red if acqPeriodInterval between Plots: You might be losing Images!","Plot"); + boxFrequency->setPalette(*red); + boxFrequency->setTitle("Interval between Plots*"); + QString errTip = intervalTip + QString("

" + "Time Interval Acquisition Period should be >= Time Interval between plots.
" + "You might be losing images!
"); + boxFrequency->setToolTip(errTip); + } + //correct + else{ + boxFrequency->setPalette(boxSnapshot->palette()); + boxFrequency->setTitle("Interval between Plots"); + boxFrequency->setToolTip(intervalTip); + } + + //This is done so that its known which one was selected + myPlot->SetFrameFactor(0); + // Setting the timer value(ms) between plots + myPlot->SetPlotTimer(timeMS); +#ifdef VERBOSE + cout << "Plotting Frequency: Time Gap - " << spinTimeGap->value() << qDefs::getUnitString((qDefs::timeUnit)comboTimeGapUnit->currentIndex()) << endl; +#endif + break; + + + + + case 1: + + // gets the acq period * number of nth frames + timeMS = (spinNthFrame->value())*acqPeriodMS; + + //Show red to make sure the period between plotting is not less than minimum plot timer in ms + if(timeMSInterval between Plots: You might be losing Images!","Plot"); + boxFrequency->setPalette(*red); + boxFrequency->setTitle("Interval between Plots*"); + QString errTip = intervalTip + QString("

" + "Every nth Image Condition: min nth Image for this time period: ")+QString("%1").arg(minFrame)+ + QString(".
You might be losing images!
"); + boxFrequency->setToolTip(errTip); + }else{ + boxFrequency->setPalette(boxSnapshot->palette()); + boxFrequency->setTitle("Interval between Plots"); + boxFrequency->setToolTip(intervalTip); + } + + // Setting the timer value (nth frames) between plots + myPlot->SetFrameFactor(spinNthFrame->value()); + + +#ifdef VERBOSE + cout << "Plotting Frequency: Nth Frame - " << spinNthFrame->value() << endl; +#endif + break; + } + + connect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + qDefs::checkErrorMessage(myDet,"qTabPlot::SetFrequency"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabPlot::EnableScanBox(){ +#ifdef VERBOSE + cout << "Entering Enable Scan Box"<< endl; +#endif + disconnect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); + disconnect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + + int mode0 = myDet->getScanMode(0); + int mode1 = myDet->getScanMode(1); + + radioHistLevel0->setEnabled(mode0); + radioHistLevel1->setEnabled(mode1); + int ang; + bool angConvert = myDet->getAngularConversion(ang); + myPlot->EnableAnglePlot(angConvert); + + radioDataGraph->setEnabled(true); + radioHistogram->setEnabled(true); + chkSuperimpose->setEnabled(true); + pageAccumulate->setEnabled(true); + pageAccumulate_2->setEnabled(true); + if((myDet->getDetectorsType() == slsDetectorDefs::GOTTHARD) || + (myDet->getDetectorsType() == slsDetectorDefs::PROPIX) || + (myDet->getDetectorsType() == slsDetectorDefs::JUNGFRAU) || + (myDet->getDetectorsType() == slsDetectorDefs::MOENCH)){ + pagePedestal->setEnabled(true); + pagePedestal_2->setEnabled(true); + chkBinary->setEnabled(true); + chkBinary_2->setEnabled(true); + } + + + + + //if angle plot or originally 2d, uncheck and disable scanbox + if ((angConvert) || (!isOriginallyOneD)){ + boxScan->setChecked(false); + boxScan->setEnabled(false); + + /**Newly added*/ + // To remind the updateplot in qdrawplot to set range after updating plot + if(!isOriginallyOneD) + myPlot->SetXYRange(true); + + //2d scans read every frame, not compulsory, but for historgrams + if((!isOriginallyOneD) && (mode0 || mode1)){ + //read every frame + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + comboFrequency->setCurrentIndex(1); + spinNthFrame->setValue(1); + SetFrequency(); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + } + + //persistency, accumulate, pedestal, binary + if(angConvert){ + if(chkSuperimpose->isChecked()) chkSuperimpose->setChecked(false); + if(chkPedestal->isChecked()) chkPedestal->setChecked(false); + if(chkPedestal_2->isChecked()) chkPedestal_2->setChecked(false); + if(chkAccumulate->isChecked()) chkAccumulate->setChecked(false); + if(chkAccumulate_2->isChecked())chkAccumulate_2->setChecked(false); + if(chkBinary->isChecked()) chkBinary->setChecked(false); + if(chkBinary_2->isChecked()) chkBinary_2->setChecked(false); + pagePedestal->setEnabled(false); + pagePedestal_2->setEnabled(false); + chkBinary->setEnabled(false); + chkBinary_2->setEnabled(false); + pageAccumulate->setEnabled(false); + pageAccumulate_2->setEnabled(false); + } + + if(angConvert){ + boxScan->setToolTip("Only 1D Plots enabled for Angle Plots"); + //disable histogram + if(radioHistogram->isChecked()){ + radioDataGraph->setChecked(true); + radioHistogram->setEnabled(false); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); + boxScan->show(); + boxHistogram->hide(); + } + } + } + + + + + //originally1d && not angle plot + else{ + boxScan->setToolTip(""); + boxScan->setEnabled(true); + /*if(mode0 || mode1) + boxScan->setChecked(true);*/ + + //2d enabled with boxscan + if(boxScan->isChecked()){ + + //2d for 1d detctors and histogram dont go + if(radioHistogram->isChecked()){ + radioDataGraph->setChecked(true); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); + boxScan->show(); + boxHistogram->hide(); + } + + //read every frame + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + comboFrequency->setCurrentIndex(1); + spinNthFrame->setValue(1); + SetFrequency(); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + + //enabling options + radioFileIndex->setEnabled(mode0||mode1); + if(mode0 && mode1){ + radioLevel0->setEnabled(false); + radioLevel1->setEnabled(false); + }else{ + radioLevel0->setEnabled(mode0); + radioLevel1->setEnabled(mode1); + } + //default is allframes if checked button is disabled + if(!btnGroupScan->checkedButton()->isEnabled()) + radioAllFrames->setChecked(true); + } + } + + + //histogram + if(radioHistogram->isChecked()){ + if(radioHistIntensity->isChecked()){ + pageHistogram->setEnabled(true); + pageHistogram_2->setEnabled(true); + }else{ + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } + stackedWidget->setCurrentIndex(stackedWidget->count()-1); + stackedWidget_2->setCurrentIndex(stackedWidget_2->count()-1); + box1D->setTitle(QString("1D Plot Options %1 - Histogram").arg(stackedWidget->currentIndex()+1)); + box2D->setTitle(QString("2D Plot Options %1 - Histogram").arg(stackedWidget_2->currentIndex()+1)); + + if(chkSuperimpose->isChecked()) chkSuperimpose->setChecked(false); + if(chkPedestal->isChecked()) chkPedestal->setChecked(false); + if(chkPedestal_2->isChecked()) chkPedestal_2->setChecked(false); + if(chkAccumulate->isChecked()) chkAccumulate->setChecked(false); + if(chkAccumulate_2->isChecked())chkAccumulate_2->setChecked(false); + if(chkBinary->isChecked()) chkBinary->setChecked(false); + if(chkBinary_2->isChecked()) chkBinary_2->setChecked(false); + pagePedestal->setEnabled(false); + pagePedestal_2->setEnabled(false); + chkBinary->setEnabled(false); + chkBinary_2->setEnabled(false); + pageAccumulate->setEnabled(false); + pageAccumulate_2->setEnabled(false); + + //read every frame + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + comboFrequency->setCurrentIndex(1); + spinNthFrame->setValue(1); + SetFrequency(); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + + + }else{ + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } + + connect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); + connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabPlot::SetScanArgument(){ +#ifdef VERYVERBOSE + cout << "Entering qTabPlot::SetScanArgument()" << endl; +#endif + + //1d + if(isOriginallyOneD){ + dispXAxis->setText(defaultHistXAxisTitle); + dispYAxis->setText(defaultHistYAxisTitle); + myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); + myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); + Select1DPlot(true); + } + //2d + else{ + dispXAxis->setText(defaultImageXAxisTitle); + dispYAxis->setText(defaultImageYAxisTitle); + dispZAxis->setText(defaultImageZAxisTitle); + myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); + myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); + myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); + Select1DPlot(false); + } + + + //histogram default - set before setscanargument + int min = spinHistFrom->value(); + int max = spinHistTo->value(); + double size = spinHistSize->value(); + int histArg = qDefs::Intensity; + if(radioHistogram->isChecked()){ + if(!radioHistIntensity->isChecked()){ + + int mode = 0; + histArg = qDefs::histLevel0; + if(radioHistLevel1->isChecked()){ + mode = 1; + histArg = qDefs::histLevel1; + } + + + int numSteps = myDet->getScanSteps(mode); + double *values = NULL; + min = 0;max = 1;size = 1; + + if(numSteps > 0){ + values = new double[numSteps]; + myDet->getScanSteps(mode,values); + min = values[0]; + max = values[numSteps - 1]; + size = (max - min)/(numSteps - 1); + } + } + + } + + //cout <<"min:"<SetHistogram(radioHistogram->isChecked(),histArg,min,max,size); + + + if(radioHistogram->isChecked()){ + if(radioHistIntensity->isChecked()) + dispXAxis->setText("Intensity"); + else if (radioHistLevel0->isChecked()) + dispXAxis->setText("Level 0"); + else + dispXAxis->setText("Level 1"); + dispYAxis->setText("Frequency"); + myPlot->SetHistXAxisTitle("Intensity"); + myPlot->SetHistYAxisTitle("Frequency"); + Select1DPlot(true); + } + + //angles (1D) + int ang; + if(myDet->getAngularConversion(ang)){ + dispXAxis->setText("Angles"); + myPlot->SetHistXAxisTitle("Angles"); + Select1DPlot(true); + } + + + //1d with scan + if(boxScan->isChecked()){ + myPlot->SetScanArgument(btnGroupScan->checkedId()+1); + + switch(btnGroupScan->checkedId()){ + case 0://level0 + dispYAxis->setText("Scan Level 0"); + myPlot->SetImageYAxisTitle("Scan Level 0"); + break; + case 1://level1 + dispYAxis->setText("Scan Level 1"); + myPlot->SetImageYAxisTitle("Scan Level 1"); + break; + break; + case 2://file index + dispYAxis->setText("Frame Index"); + myPlot->SetImageYAxisTitle("Frame Index"); + break; + case 3://all frames + dispYAxis->setText("All Frames"); + myPlot->SetImageYAxisTitle("All Frames"); + break; + } + Select1DPlot(false); + }else + myPlot->SetScanArgument(qDefs::None); + + //update the from and to labels to be enabled + SetBinary(); + + qDefs::checkErrorMessage(myDet,"qTabPlot::SetScanArgument"); + +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetBinary(){ + //1d + if(isOneD){ + if(chkBinary->isChecked()){ +#ifdef VERBOSE + cout << endl << "Enabling Binary" << endl; +#endif + lblFrom->setEnabled(true); + lblTo->setEnabled(true); + spinFrom->setEnabled(true); + spinTo->setEnabled(true); + myPlot->SetBinary(true,spinFrom->value(),spinTo->value()); + }else{ +#ifdef VERBOSE + cout << endl << "Disabling Binary" << endl; +#endif + lblFrom->setEnabled(false); + lblTo->setEnabled(false); + spinFrom->setEnabled(false); + spinTo->setEnabled(false); + myPlot->SetBinary(false); + } + } + //2d + else{ + if(chkBinary_2->isChecked()){ +#ifdef VERBOSE + cout << endl << "Enabling Binary" << endl; +#endif + lblFrom_2->setEnabled(true); + lblTo_2->setEnabled(true); + spinFrom_2->setEnabled(true); + spinTo_2->setEnabled(true); + myPlot->SetBinary(true,spinFrom_2->value(),spinTo_2->value()); + + }else{ +#ifdef VERBOSE + cout << endl << "Disabling Binary" << endl; +#endif + + lblFrom_2->setEnabled(false); + lblTo_2->setEnabled(false); + spinFrom_2->setEnabled(false); + spinTo_2->setEnabled(false); + myPlot->SetBinary(false); + } + } +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::SetHistogramOptions(){ + if(radioHistIntensity->isChecked()){ + pageHistogram->setEnabled(true); + pageHistogram_2->setEnabled(true); + }else { + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } +} + + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabPlot::Refresh(){ +#ifdef VERBOSE + cout << endl << "**Updating Plot Tab" << endl; +#endif + if(!myPlot->isRunning()){ + if (!radioNoPlot->isChecked()) + boxFrequency->setEnabled(true); + connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + EnableScanBox(); + /*if(myDet->getDetectorsType() == slsDetectorDefs::EIGER) + comboFrequency->setCurrentIndex(1);*/ + SetFrequency(); + + }else{ + boxFrequency->setEnabled(false); + disconnect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + boxScan->setEnabled(false); + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + if(radioHistogram->isChecked()) + radioDataGraph->setEnabled(false); + else + radioHistogram->setEnabled(false); + } +#ifdef VERBOSE + cout << "**Updated Plot Tab" << endl << endl; +#endif +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + diff --git a/slsDetectorGui/src/qTabSettings.cpp b/slsDetectorGui/src/qTabSettings.cpp new file mode 100644 index 0000000000..bd943e1626 --- /dev/null +++ b/slsDetectorGui/src/qTabSettings.cpp @@ -0,0 +1,377 @@ +/* + * qTabSettings.cpp + * + * Created on: May 10, 2012 + * Author: l_maliakal_d + */ + +#include "qTabSettings.h" +// Project Class Headers +#include "slsDetector.h" +#include "multiSlsDetector.h" +// C++ Include Headers +#include +#include +using namespace std; + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +qTabSettings::qTabSettings(QWidget *parent,multiSlsDetector*& detector): + QWidget(parent),myDet(detector),expertMode(false){ + + for(int i=0;igetDetectorsType(); + + // Settings + SetupDetectorSettings(); + + //threshold + if((detType == slsDetectorDefs::MYTHEN) || (detType == slsDetectorDefs::EIGER)) + spinThreshold->setValue(myDet->getThresholdEnergy()); + + //expert mode is not enabled initially + lblThreshold->setEnabled(false); + spinThreshold->setEnabled(false); + + // Number of Modules + spinNumModules->setMaximum(myDet->getMaxNumberOfModules()); + spinNumModules->setValue(myDet->setNumberOfModules()); + + Initialization(); + + // Dynamic Range + GetDynamicRange(); + + qDefs::checkErrorMessage(myDet,"qTabSettings::SetupWidgetWindow"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabSettings::GetDynamicRange(int setvalue){ +#ifdef VERBOSE + cout << "Getting dynamic range" << endl; +#endif + int ret = myDet->setDynamicRange(-1); + if(detType == slsDetectorDefs::MYTHEN) + if(ret==24) + ret=32; + else if(ret==24) + cout<<"ret:"<setCurrentIndex(0); break; + case 16: comboDynamicRange->setCurrentIndex(1); break; + case 8: comboDynamicRange->setCurrentIndex(2); break; + case 4: comboDynamicRange->setCurrentIndex(3); break; + default: comboDynamicRange->setCurrentIndex(0); break; + } + connect(comboDynamicRange, SIGNAL(activated(int)), this, SLOT(SetDynamicRange(int))); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabSettings::SetupDetectorSettings(){ + // Get detector settings from detector + int sett = (int)myDet->getSettings();cout<<"sett:"<(comboSettings->model()); + if (model) { + for(int i=0;iindex(i, comboSettings->modelColumn(), comboSettings->rootModelIndex()); + item[i] = model->itemFromIndex(index[i]); + } + + switch(detType){ + case slsDetectorDefs::MYTHEN: + item[(int)Standard]->setEnabled(true); + item[(int)Fast]->setEnabled(true); + item[(int)HighGain]->setEnabled(true); + item[(int)DynamicGain]->setEnabled(false); + item[(int)LowGain]->setEnabled(false); + item[(int)MediumGain]->setEnabled(false); + item[(int)VeryHighGain]->setEnabled(false); + item[(int)LowNoise]->setEnabled(false); + item[(int)DynamicHG0]->setEnabled(false); + item[(int)FixGain1]->setEnabled(false); + item[(int)FixGain2]->setEnabled(false); + item[(int)ForceSwitchG1]->setEnabled(false); + item[(int)ForceSwitchG2]->setEnabled(false); + item[(int)VeryLowGain]->setEnabled(false); + break; + case slsDetectorDefs::EIGER: + item[(int)Standard]->setEnabled(true); + item[(int)Fast]->setEnabled(false); + item[(int)HighGain]->setEnabled(true); + item[(int)DynamicGain]->setEnabled(false); + item[(int)LowGain]->setEnabled(true); + item[(int)MediumGain]->setEnabled(false); + item[(int)VeryHighGain]->setEnabled(true); + item[(int)LowNoise]->setEnabled(false); + item[(int)DynamicHG0]->setEnabled(false); + item[(int)FixGain1]->setEnabled(false); + item[(int)FixGain2]->setEnabled(false); + item[(int)ForceSwitchG1]->setEnabled(false); + item[(int)ForceSwitchG2]->setEnabled(false); + item[(int)VeryLowGain]->setEnabled(true); + break; + case slsDetectorDefs::MOENCH: + case slsDetectorDefs::PROPIX: + case slsDetectorDefs::GOTTHARD: + item[(int)Standard]->setEnabled(false); + item[(int)Fast]->setEnabled(false); + item[(int)HighGain]->setEnabled(true); + item[(int)DynamicGain]->setEnabled(true); + item[(int)LowGain]->setEnabled(true); + item[(int)MediumGain]->setEnabled(true); + item[(int)VeryHighGain]->setEnabled(true); + item[(int)LowNoise]->setEnabled(false); + item[(int)DynamicHG0]->setEnabled(false); + item[(int)FixGain1]->setEnabled(false); + item[(int)FixGain2]->setEnabled(false); + item[(int)ForceSwitchG1]->setEnabled(false); + item[(int)ForceSwitchG2]->setEnabled(false); + item[(int)VeryLowGain]->setEnabled(false); + break; + case slsDetectorDefs::JUNGFRAU: + item[(int)Standard]->setEnabled(false); + item[(int)Fast]->setEnabled(false); + item[(int)HighGain]->setEnabled(false); + item[(int)DynamicGain]->setEnabled(true); + item[(int)LowGain]->setEnabled(false); + item[(int)MediumGain]->setEnabled(false); + item[(int)VeryHighGain]->setEnabled(false); + item[(int)LowNoise]->setEnabled(false); + item[(int)DynamicHG0]->setEnabled(true); + item[(int)FixGain1]->setEnabled(true); + item[(int)FixGain2]->setEnabled(true); + item[(int)ForceSwitchG1]->setEnabled(true); + item[(int)ForceSwitchG2]->setEnabled(true); + item[(int)VeryLowGain]->setEnabled(false); + break; + default: + cout << "Unknown detector type. Exiting GUI." << endl; + qDefs::Message(qDefs::CRITICAL,"Unknown detector type. Exiting GUI.","qTabSettings::SetupDetectorSettings"); + exit(-1); + break; + } + // detector settings selected NOT ENABLED. + // This should not happen -only if the server and gui has a mismatch + // on which all modes are allowed in detectors + if(!(item[sett]->isEnabled())){ + qDefs::Message(qDefs::CRITICAL,"Unknown Detector Settings retrieved from detector. Exiting GUI.","qTabSettings::SetupDetectorSettings"); +#ifdef VERBOSE + cout << "ERROR: Unknown Detector Settings retrieved from detector." << endl; +#endif + exit(-1); + } + // Setting the detector settings + else comboSettings->setCurrentIndex(sett); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabSettings::Initialization(){ + // Settings + connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); + // Number of Modules + connect(spinNumModules, SIGNAL(valueChanged(int)), this, SLOT(SetNumberOfModules(int))); + // Dynamic Range + connect(comboDynamicRange, SIGNAL(activated(int)), this, SLOT(SetDynamicRange(int))); + // Threshold + connect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabSettings::setSettings(int index){ + //dont set it if settings is set to undefined or uninitialized + if((index==Undefined)||(index==Uninitialized)){ + qDefs::Message(qDefs::WARNING,"Cannot change settings to Undefined or Uninitialized.","qTabSettings::setSettings"); + disconnect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); + int sett = (int)myDet->getSettings(); + if(sett==-1) sett = Undefined; + else if(sett == slsDetectorDefs::UNDEFINED) sett = Undefined; + else if(sett == slsDetectorDefs::UNINITIALIZED) sett = Uninitialized; + comboSettings->setCurrentIndex(sett); + connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); + } + + else{ + slsDetectorDefs::detectorSettings sett = myDet->setSettings((slsDetectorDefs::detectorSettings)index); + #ifdef VERBOSE + cout << endl << "Settings have been set to " << myDet->slsDetectorBase::getDetectorSettings(sett) << endl; + #endif + + //threshold + if((detType==slsDetectorDefs::MYTHEN)||(detType==slsDetectorDefs::EIGER)){ + lblThreshold->setEnabled(true); + spinThreshold->setEnabled(true); + SetEnergy(); + //also update trimbits plot + if(expertMode) emit UpdateTrimbitSignal(0); + } + } + + qDefs::checkErrorMessage(myDet,"qTabSettings::setSettings"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabSettings::SetNumberOfModules(int index){ +#ifdef VERBOSE + cout << "Setting number of modules to "<< index << endl; +#endif + int i = myDet->setNumberOfModules(index); + if(index!=i) + qDefs::Message(qDefs::WARNING,"Number of modules cannot be set for this value.","qTabSettings::SetNumberOfModules"); +#ifdef VERBOSE + cout << "ERROR: Setting number of modules to "<< i << endl; +#endif + spinNumModules->setValue(i); + + qDefs::checkErrorMessage(myDet,"qTabSettings::SetNumberOfModules"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabSettings::SetDynamicRange(int index){ + int dr; + switch (index) { + case 0: dr=32; break; + case 1: dr=16; break; + case 2: dr=8; break; + case 3: dr=4; break; + default: dr=32; break; + } + myDet->setDynamicRange(dr); +#ifdef VERBOSE + cout << "Setting dynamic range to "<< dr << endl; +#endif + //check + GetDynamicRange(dr); + qDefs::checkErrorMessage(myDet,"qTabSettings::SetDynamicRange"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabSettings::SetEnergy(){ + int index = spinThreshold->value(); +#ifdef VERBOSE + cout << "Settings threshold energy to "<< index << endl; +#endif + myDet->setThresholdEnergy(index); + int ret = (int)myDet->getThresholdEnergy(); + if((ret-index)>200){ + qDefs::Message(qDefs::WARNING,"Threshold energy could not be set. The difference is greater than 200.","qTabSettings::SetEnergy"); + } + disconnect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); + spinThreshold->setValue(ret); + connect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); + + qDefs::checkErrorMessage(myDet,"qTabSettings::SetEnergy"); +} + + +//------------------------------------------------------------------------------------------------------------------------------------------------- + + +void qTabSettings::Refresh(){ +#ifdef VERBOSE + cout << endl << "**Updating Settings Tab" << endl; +#endif + + disconnect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); + disconnect(spinNumModules, SIGNAL(valueChanged(int)), this, SLOT(SetNumberOfModules(int))); + disconnect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); + + + // Number of Modules +#ifdef VERBOSE + cout << "Getting number of modules:" ; +#endif + int numMod = myDet->setNumberOfModules(); +#ifdef VERBOSE + cout << numMod << endl; +#endif + spinNumModules->setValue(numMod); + + // Dynamic Range + GetDynamicRange(); + + // Settings +#ifdef VERBOSE + cout << "Getting settings" << endl; +#endif + int sett = (int)myDet->getSettings(); + if(sett==-1) sett = Undefined;//slsDetectorDefs::UNDEFINED; + else if(sett == slsDetectorDefs::UNDEFINED) sett = Undefined; + else if(sett == slsDetectorDefs::UNINITIALIZED) sett = Uninitialized; + comboSettings->setCurrentIndex(sett); + + + //threshold + sett = comboSettings->currentIndex(); + if((detType==slsDetectorDefs::MYTHEN)||(detType==slsDetectorDefs::EIGER)){ + if((sett==Undefined)||(sett==Uninitialized)){ + lblThreshold->setEnabled(false); + spinThreshold->setEnabled(false); + }else{ + lblThreshold->setEnabled(true); + spinThreshold->setEnabled(true); +#ifdef VERBOSE + cout << "Getting threshold energy" << endl; +#endif + spinThreshold->setValue(myDet->getThresholdEnergy()); + } + } + + + connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); + connect(spinNumModules, SIGNAL(valueChanged(int)), this, SLOT(SetNumberOfModules(int))); + connect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); + +#ifdef VERBOSE + cout << "**Updated Settings Tab" << endl << endl; +#endif + + qDefs::checkErrorMessage(myDet,"qTabSettings::Refresh"); +} + + +//-------------------------------------------------------------------------------------------------------------------------------------------------