def __init__(self, camera=None, log=None, fps=10.):
     super().__init__()
     # ---  --- #
     if log != None:
         self.log = log
     else:
         self.log = LogDisplay()
     #self.log.show()
     # --- default --- #
     self.fps = fps
     self.normalise_hist = True
     self.cmap = 'jet'
     # --- main attriute --- #
     self.camera = camera
     if self.camera == None:
         dir_path = '/home/cgou/ENS/STAGE/M2--stage/Camera_acquisition/Miscellaneous/Camera_views/'
         self.camera = Camera(cam_id=0, log=self.log)
         if not self.camera.isCameraInit:
             self.camera = SimuCamera(0,
                                      directory_path=dir_path,
                                      log=self.log)
             self.camera.__info__()
     elif not self.camera.isCameraInit:
         self.camera.__init__(cam_id=0, log=self.log)
     # ---  --- #
     self.contview = ContinuousView(fps=self.fps)
     self.timer = pg.QtCore.QTimer()  #QTimer()# pg.QtCore.QTimer()
     self.qlabl_max = QLabel()
     self.isOn = False
     # ---  --- #
     self.initUI()
     # ---  --- #
     self.camera.setExposure(self.image_widget.exposure.value())
 def initCamera(self, camera):
     self.default_camera = camera
     self.simu_camera    = SimuCamera(directory_path=os.getcwd(), log=self.log)
     # ---  --- #
     self.camera = self.default_camera
     if not self.camera.isCameraInit:
         self.camera.__init__()
 def initCamera(self):
     dir_path = '/home/cgou/ENS/STAGE/M2--stage/Camera_acquisition/Miscellaneous/Camera_views/'
     self.camera   = Camera(cam_id=0, log=self.log)
     if not self.camera.isCameraInit:
         self.camera = SimuCamera(0, directory_path=dir_path, log=self.log)
         self.log.addText( self.camera.__str__() )
     else:
         self.log.addText('Camera in use is: USB camera')
        if type(xdata) != type(None) and type(ydata) != type(None):
            n = np.min( [len(xdata), len(ydata), len(max_data)] )
            xdata = xdata[-n:]/max_data[-n:]
            ydata = ydata[-n:]/max_data[-n:]
            xdata = self.postProcessLissajous(xdata)
            ydata = self.postProcessLissajous(ydata)
            self.data_lissjs.setData( xdata, ydata )

    def updatePtNbrLabel(self):
        self.samplingPtNbr.setText( str(self.samplingtime.value()*self.camera_view.fps) )

#########################################################################################################################
# CODE
#########################################################################################################################
if __name__ == '__main__':
    print('STARTING')
    dir_path = '/home/cgou/ENS/STAGE/M2--stage/Camera_acquisition/Miscellaneous/Camera_views/'
    camera   = Camera(cam_id=0)
    if not camera.isCameraInit:
        camera = SimuCamera(0, directory_path=dir_path)
        camera.__info__()

    app = QApplication([])
    start_window = PhaseNetworkElements(camera)
    start_window.show()
    app.exit(app.exec_())
    print('Close camera')
    camera.close_camera()

    print('FINISHED')
class Preview(QWidget):
    def __init__(self, camera=None, log=None, fps=10.):
        super().__init__()
        # ---  --- #
        if log != None:
            self.log = log
        else:
            self.log = LogDisplay()
        #self.log.show()
        # --- default --- #
        self.fps = fps
        self.normalise_hist = True
        self.cmap = 'jet'
        # --- main attriute --- #
        self.camera = camera
        if self.camera == None:
            dir_path = '/home/cgou/ENS/STAGE/M2--stage/Camera_acquisition/Miscellaneous/Camera_views/'
            self.camera = Camera(cam_id=0, log=self.log)
            if not self.camera.isCameraInit:
                self.camera = SimuCamera(0,
                                         directory_path=dir_path,
                                         log=self.log)
                self.camera.__info__()
        elif not self.camera.isCameraInit:
            self.camera.__init__(cam_id=0, log=self.log)
        # ---  --- #
        self.contview = ContinuousView(fps=self.fps)
        self.timer = pg.QtCore.QTimer()  #QTimer()# pg.QtCore.QTimer()
        self.qlabl_max = QLabel()
        self.isOn = False
        # ---  --- #
        self.initUI()
        # ---  --- #
        self.camera.setExposure(self.image_widget.exposure.value())

    def initUI(self):
        # ---  --- #
        self.layout = QVBoxLayout(self)
        self.initView()
        # --- button widget --- #
        self.button_acquire = QPushButton('Acquire frame')
        self.button_acquire.setStyleSheet("background-color: orange")
        self.button_acq_movie = QPushButton('Acquire movie')
        self.button_acq_movie.setStyleSheet("background-color: orange")
        # ---  --- #
        self.movie_frameNbre = QSpinBox()
        self.movie_frameNbre.setMinimum(0)
        self.movie_frameNbre.setMaximum(1000)
        self.movie_frameNbre.setValue(200)
        self.dir_save = QFileDialog()
        self.dir_save_label = QLabel('No file selected')
        self.dir_save_label.setWordWrap(True)
        self.name_save = QLineEdit()
        self.name_save.setText('img_data')
        self.progressbar = QProgressBar()
        self.progressbar.setValue(0)
        self.format_save = QComboBox()
        self.format_save.addItem('tif')
        self.format_save.addItem('tiff')
        self.format_save.addItem('png')
        self.format_save.addItem('jpg')
        self.histogram_mode = QComboBox()
        self.histogram_mode.addItem('Normalise')
        self.histogram_mode.addItem('Raw')
        # --- connections --- #
        self.button_acquire.clicked.connect(self.acquireFrame)
        self.button_acq_movie.clicked.connect(self.acquireMovie)
        self.histogram_mode.currentIndexChanged.connect(self.setHistogramMode)
        # --- layout --- #
        self.layout.addWidget(self.view_layout)
        grid = QGridLayout()
        grid.addWidget(self.histogram_mode, 0, 0)
        grid.addWidget(self.button_acquire, 0, 1, 1, 2)
        grid.addWidget(QLabel('Number of frame'), 1, 0)
        grid.addWidget(self.movie_frameNbre, 1, 1)
        grid.addWidget(self.button_acq_movie, 1, 2)
        grid.addWidget(QLabel('Filemane prefix:'), 2, 0)
        grid.addWidget(self.name_save, 2, 1)
        grid.addWidget(self.format_save, 2, 2)
        grid.addWidget(QLabel('Directory:'), 3, 0)
        grid.addWidget(self.dir_save_label, 3, 1, 1, 2)
        grid.addWidget(self.progressbar, 4, 0, 1, 3)
        self.layout.addLayout(grid)
        self.setLayout(self.layout)
        # ---  --- #
        self.update_timer = QTimer()

    def initView(self):
        self.image_widget = CameraDisplay(camera=self.camera, log=self.log)
        self.image_view = self.image_widget.image_view
        # --- histogram --- #
        self.hist_layWidget = pg.GraphicsLayoutWidget()
        self.plot_hist = self.hist_layWidget.addPlot()
        self.plot_hist.setXLink(self.image_view.getView())
        if self.normalise_hist:
            self.plot_hist.setYRange(0, 1)
        else:
            self.plot_hist.enableAutoRange(y=True)
        # ---  --- #
        self.data_hist = pg.PlotDataItem()
        self.plot_hist.addItem(self.data_hist)
        # --- link histogram to image view --- #
        self.image_widget.frame_updated.connect(self.updatePlotHistogram)
        # ---  --- #
        self.image_view.setLevels(0, 255)
        self.image_view.getHistogramWidget().item.setHistogramRange(
            0, 255)  #not working when update
        self.image_view.ui.roiBtn.hide()
        self.image_view.ui.menuBtn.hide()
        # ---  --- #
        self.image_view.setMinimumWidth(400)
        self.image_view.setMinimumHeight(200)
        self.hist_layWidget.setMinimumWidth(400)
        self.hist_layWidget.setMinimumHeight(100)
        # ---  --- #
        self.view_layout = QSplitter(PyQt5.QtCore.Qt.Vertical)
        self.view_layout.addWidget(self.image_widget)
        self.view_layout.addWidget(self.hist_layWidget)

    def setFPS(self):
        self.fps = self.fps_input.value()
        self.contview.setFPS(self.fps)
        self.timer.setInterval(1e3 / self.fps)

    def setHistogramMode(self, indx):
        val = self.histogram_mode.currentText()
        if val == 'Normalise':
            self.normalise_hist = True
            self.plot_hist.setYRange(0, 1)
        elif val == 'Raw':
            self.normalise_hist = False
            self.plot_hist.enableAutoRange(y=True)

    def nextFrame(self):
        wasOn = self.isOn
        if not self.isOn:
            self.camera.capture_video()
        # ---  --- #
        self.update_image()
        # ---  --- #
        if not wasOn:
            self.camera.capture_video()

    def updatePlotHistogram(self):
        frame = self.image_widget.frame
        if self.normalise_hist:
            bckgrnd = np.mean(frame)
            frame = frame - bckgrnd
        ydata = np.sum(frame, axis=0) / frame.shape[0]
        if self.normalise_hist:
            ydata -= np.min([0, np.min(ydata)])
            ydata = ydata / np.max(ydata)
        self.data_hist.setData(ydata)

    def update_slider(self):
        self.exposure_slider.setValue(self.exposure_spinb.value() * 100)
        self.update_exposure()

    def update_spinbox(self):
        self.exposure_spinb.setValue(float(self.exposure_slider.value()) / 100)
        self.update_exposure()

    def update_exposure(self):
        exp_val = self.exposure_spinb.value()
        self.camera.setExposure(exp_val)

    def acquireFrame(self):
        wasOn = self.isOn
        if self.isOn:
            self.startStop_continuous_view()
        # ---  --- #
        try:
            frame = self.camera.frame
            plt.imshow(frame, cmap=self.cmap)
            plt.show()
        except:
            pass
        # ---  --- #
        if wasOn:
            self.startStop_continuous_view()

    def acquireMovie(self):
        wasOn = self.isOn
        if self.isOn:
            self.startStop_continuous_view()
        # ---  --- #
        dir_save_path = self.dir_save.getExistingDirectory() + '/'
        self.dir_save_label.setText(dir_save_path)
        filename = self.name_save.text()
        format_ = self.format_save.currentText()
        # ---  --- #
        self.progressbar.setValue(0)
        self.progressbar.setMaximum(self.movie_frameNbre.value())
        # ---  --- #
        movie = self.camera.acquire_movie(self.movie_frameNbre.value())
        try:
            img_to_save = Image.fromarray(movie[0])
            img_to_save.save(dir_save_path + filename +
                             '_{0:03d}.{1}'.format(0, format_))
            self.progressbar.setValue(1)
        except:
            err_msg = 'Error: in acquireMovie. The filename is not accepted\nFilename: {0}\nDirectory path: {1}'.format(
                filename, dir_save_path)
            self.log.addText(err_msg)
            return None
        for i in range(1, len(movie)):
            img_to_save = Image.fromarray(movie[i])
            img_to_save.save(dir_save_path + filename +
                             '_{0:03d}.{1}'.format(i, format_))
            self.progressbar.setValue(i + 1)
        # ---  --- #
        if wasOn:
            self.startStop_continuous_view()
class CameraDisplay(QWidget):
    frame_updated = pyqtSignal()
    # ~~~~~~~~~~~~~~~~~~~~~~~~ #
    def __init__(self, camera=None, log=None, fps=10.):
        super().__init__()
        # ---  --- #
        if log != None:
            self.log = log
        else:
            self.log = LogDisplay()
        #self.log.show()
        # --- default --- #
        self.fps       = fps
        self.normalise_hist = True
        self.cmap      = 'jet'
        # --- main attriute --- #
        self.camera    = camera
        self.contview  = ContinuousView(fps=self.fps)
        self.timer     = pg.QtCore.QTimer() #QTimer()# pg.QtCore.QTimer()
        self.qlabl_max = QLabel()
        self.isOn      = False
        self.frame     = None
        # --- color acuisition --- #
        self.initColorDic()
        # ---  --- #
        self.initUI()
        self.initCamera(camera)
        # ---  --- #
        self.camera.setExposure( self.exposure.value() )

    def initUI(self):
        # ---  --- #
        self.layout      = QVBoxLayout(self)
        self.initView()
        # --- button widget --- #
        self.button_startstop = QPushButton('Start/Stop')
        self.button_startstop.setStyleSheet("background-color: red")
        self.button_nextFrame = QPushButton('Next frame')
        # ---  --- #
        self.fps_input     = QSpinBox()
        self.fps_input.setRange(1, 48)
        self.fps_input.setValue(self.fps)
        self.exposure      = QDoubleSpinBox()
        self.exposure.setSingleStep(0.01)
        self.cam_framerate = QDoubleSpinBox()
        self.exposure.setSingleStep(0.01)
        self.pixelclock    = QDoubleSpinBox()
        self.which_camera  = QComboBox()
        self.which_camera.addItem('USB camera')
        self.which_camera.addItem('From Image Dir.')
        # --- set default --- #
        self.exposure.setRange(0.10, 99.0)
        self.exposure.setValue(12.5)
        self.cam_framerate.setRange(1.00, 15.0)
        self.cam_framerate.setValue( 10.0 )
        self.pixelclock.setRange(5, 30)
        self.pixelclock.setValue(20)
        # --- connections --- #
        self.button_startstop.clicked.connect(self.startStop_continuous_view)
        self.fps_input.valueChanged.connect(self.setFPS)
        self.button_nextFrame.clicked.connect( self.nextFrame )
        self.exposure.valueChanged.connect( self.update_exposure )
        self.cam_framerate.valueChanged.connect( self.update_camFPS )
        self.pixelclock.valueChanged.connect( self.update_pixelClock )
        self.which_camera.currentIndexChanged.connect( self.changeCameraStyle )
        # --- layout --- #
        label_1 = QLabel('fps :')
        label_1.setWordWrap(True)
        label_2 = QLabel('value max:') 
        label_2.setWordWrap(True)
        label_3 = QLabel('Which camera')
        label_3.setWordWrap(True)
        label_4 = QLabel('Exposure (ms):')
        label_4.setWordWrap(True)
        label_5 = QLabel('Camera fps:')
        label_5.setWordWrap(True)
        label_6 = QLabel('Pixel clock (MHz):')
        label_6.setWordWrap(True)
        grid = QGridLayout()
        grid.addWidget( self.button_startstop, 0,0)
        grid.addWidget( self.button_nextFrame, 0,1)
        grid.addWidget( label_1              , 0,2)
        grid.addWidget( self.fps_input       , 0,3)
        grid.addWidget( label_2              , 0,4)
        grid.addWidget( self.qlabl_max       , 0,5)
        grid.addWidget(QVLine()              , 0,6 , 2,1)
        grid.addWidget(label_3               , 0,7)
        grid.addWidget( self.which_camera    , 1,7 , 2,1)
        grid.addWidget(label_4               , 1,0)
        grid.addWidget( self.exposure        , 1,1)
        grid.addWidget(label_5               , 1,2)
        grid.addWidget( self.cam_framerate   , 1,3)
        grid.addWidget(label_6               , 1,4)
        grid.addWidget( self.pixelclock      , 1,5)
        self.layout.addLayout(grid)
        self.layout.addWidget(self.image_view)
        self.setLayout(self.layout)

    def initColorDic(self):
        self.colordic = {}
        # --- jet-like cmap --- #
        alpha     = 1.0
        positions = [0.2, 0.5, 0.75, 1.0]
        colors    = [[0,0,1.,alpha],[0,1.,1.,alpha],[1.,1.,0,alpha],[170/255,0,0,alpha]] #colors    = ['#0000ff', '#00ffff', '#ffff00', '#aa0000']
        self.colordic['jet'] = pg.ColorMap(positions, colors)
        # --- jet reversed cmap --- #
        positions_r = [1-p_ for p_ in positions]
        self.colordic['jet_r'] = pg.ColorMap(positions_r, colors)
        # --- plasma cmap --- #
        self.colordic['plasma'] = generatePgColormap('plasma')

    def initView(self):
        self.image_view     = pg.ImageView()
        # ---  --- #
        self.image_view.setColorMap(self.colordic[self.cmap])
        self.image_view.setLevels(0,255)
        self.image_view.getHistogramWidget().item.setHistogramRange(0,255)
        # ---  --- #
        self.image_view.setMinimumWidth(800)
        self.image_view.setMinimumHeight(600)

    def initCamera(self, camera):
        self.default_camera = camera
        self.simu_camera    = SimuCamera(directory_path=os.getcwd(), log=self.log)
        # ---  --- #
        self.camera = self.default_camera
        if not self.camera.isCameraInit:
            self.camera.__init__()

    def hideHistogram(self):
        self.image_view.ui.histogram.hide()

    def hidePlotButtons(self):
        self.image_view.ui.roiBtn.hide()
        self.image_view.ui.menuBtn.hide()

    def setFPS(self):
        self.fps = self.fps_input.value()
        self.contview.setFPS( self.fps )
        self.timer.setInterval(1e3/self.fps)

    def update_frame(self):
        self.frame = self.camera.get_frame()
        self.qlabl_max.setText( str(np.max(self.frame)) )
        self.image_view.setImage(self.frame.T, autoHistogramRange=False, autoLevels=False)
        self.frame_updated.emit()

    def update_exposure(self):
        self.camera.setExposure( self.exposure.value() )
        self.log.addText( 'New exposure: {}ms'.format( self.camera.getExposure() ) )
        # ---  --- #
        new_pixelclock = self.camera.getPixelClock()
        self.pixelclock.setValue( new_pixelclock )
        new_camFPS     = self.camera.getFrameRate()
        self.cam_framerate.setValue( new_camFPS )

    def update_camFPS(self):
        newfps = self.camera.setFrameRate( self.cam_framerate.value() )
        self.log.addText('New camera fps: {:.3f}'.format( self.camera.getFrameRate() ) )
        self.cam_framerate.setValue(newfps)
        # ---  --- #
        new_pixelclock = self.camera.getPixelClock()
        self.pixelclock.setValue( new_pixelclock )
        new_exposure   = self.camera.getExposure()
        self.exposure.setValue( new_exposure )

    def update_pixelClock(self):
        self.camera.setPixelClock( int(self.pixelclock.value()) )
        self.log.addText( 'New pixel clock: {}Mhz'.format( self.camera.getPixelClock() ))
        # ---  --- #
        new_camFPS     = self.camera.getFrameRate()
        self.cam_framerate.setValue( new_camFPS )
        new_exposure   = self.camera.getExposure()
        self.exposure.setValue( new_exposure )

    def nextFrame(self):
        wasOn = self.isOn
        if not self.isOn:
            self.camera.capture_video()
        # ---  --- #
        self.update_frame()
        # ---  --- #
        if not wasOn:
            self.camera.capture_video()

    def startStop_continuous_view(self):
        if  self.isOn:
            self.stop_continuous_view()
            self.button_startstop.setStyleSheet("background-color: red")
            self.button_nextFrame.setFlat(False)
            self.button_nextFrame.setEnabled(True)
        else:
            self.start_continuous_view()
            self.button_startstop.setStyleSheet("background-color: green")
            self.button_nextFrame.setFlat(True)
            self.button_nextFrame.setEnabled(False)

    def start_continuous_view(self):
        self.camera.capture_video()
        if   True:
            self.start_continuous_view_qtimer()
        elif False:
            self.start_continuous_view_qthread()
        # ---  --- #
        self.isOn = True

    def stop_continuous_view(self):
        self.camera.stop_video()
        if   True:
            self.stop_continuous_view_qtimer()
        elif False:
            self.stop_continuous_view_qthread()
        # ---  --- #
        self.isOn = False

    def start_continuous_view_qthread(self):
        # ---  --- #
        self.thread = QThread()
        self.thread.setTerminationEnabled(True)
        # --- connect --- #
        self.contview.moveToThread(self.thread)
        self.thread.started.connect(self.contview.startFeed)
        self.contview.newshot.connect(self.update_image)
        self.contview.finished.connect(self.thread.quit)
        # ---  --- #
        self.thread.start()

    def stop_continuous_view_qthread(self):
        self.contview.stopFeed()

    def start_continuous_view_qtimer(self):
        # ---  --- #
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(1e3/self.fps) #ms

    def stop_continuous_view_qtimer(self):
        self.timer.stop()

    def changeCameraStyle(self):
        self.camera.stop_video()
        # ---  --- #
        indx = self.which_camera.currentIndex()
        if   indx == 0:
            self.camera = self.default_camera
            # ---  --- #
            self.exposure.setEnabled(True)
            self.cam_framerate.setEnabled(True)
            self.pixelclock.setEnabled(True)
        elif indx == 1:
            self.camera.stop_video()
            dir_path    = QFileDialog().getExistingDirectory()
            self.log.addText('NEW DIR PATH: {}'.format(dir_path))
            self.simu_camera.setDirectoryPath( dir_path )
            self.simu_camera.initialize()
            self.camera = self.simu_camera
            # ---  --- #
            self.exposure.setEnabled(False)
            self.cam_framerate.setEnabled(False)
            self.pixelclock.setEnabled(False)
class MainWindow(QMainWindow): # inherits from the QMainWindow class
    def __init__(self):
        super().__init__() # The super() method returns the parent object of the MainWindow class, and we call its constructor. This means that we first initiate the QWidget class constructor.
        #self.app = QApplication([]) # only one per application

        # --- paths --- #
        self.localpath  = os.path.dirname(os.path.realpath(__file__))
        self.importpath = 'Dependencies_import/'
        self.iconpath   = 'IMGdirectory/'
        # --- initialisations --- #
        self.initWindow()
        self.initWindowMenu()

        #self.show()
        #self.app.exec_()

    def initWindow(self):
        '''
        Initialize the MainWindow configuration and display.
        '''
        # --- geometry and position --- #
        x0, y0, w, h = 150, 100, 900, 800
        self.setGeometry(x0, y0, w, h)
        self.setWindToCenter() # use the method defined below to center the window in the screen
        # --- names and titles --- #
        mytitle = "Main window"
        self.setWindowTitle(mytitle)
        mainapp_iconpath = r"./" + self.importpath + self.iconpath + "icon_mainapp.png"
        self.setWindowIcon(QIcon(mainapp_iconpath))
        # --- Parent Widget : central widget --- #
        self.initMainWidget()
        self.initTabLayout()
        # --- make  log display tab --- #
        self.log        = LogDisplay()
        self.insertNewTabLogDisplay(self.log)
        # --- main attributes --- #
        self.cameraManag = CameraManagementWindow()
        self.initCamera()

    def initWindowMenu(self):
        '''
        Initialize the menu of the MainWindow.
        '''
        self.menubar = self.menuBar() # we define an attribute, menubar, which derives from the method menuBar() that comes from the QMainWindow parent object.
        # --- set the main menus --- #
        self.filemenu     = self.menubar.addMenu('&File')
        self.setupmenu    = self.menubar.addMenu('&Setups')
        self.toolsmenu    = self.menubar.addMenu('&Tools')
        self.cameramenu   = self.menubar.addMenu('&Camera')
        self.statusBar()
        # --- set the actions in the different menues --- #
        self.initFileMenu()
        self.initSetupMenu()
        self.initToolsMenu()
        self.initCameraMenu()
        #self.getFile()

    def initMainWidget(self):
        self.centralwidget = QWidget() # QMainWindow needs a QWidget to display Layouts. Thus we define a central widget so that all

    def initTabLayout(self):
        # ---  --- #
        self.centraltab    = QTabWidget()
        self.centraltab.setTabShape(0)
        self.centraltab.setTabsClosable(True)
        self.centraltab.tabCloseRequested.connect( self.closeTabe )
        self.setCentralWidget(self.centraltab)

    def initCamera(self):
        dir_path = '/home/cgou/ENS/STAGE/M2--stage/Camera_acquisition/Miscellaneous/Camera_views/'
        self.camera   = Camera(cam_id=0, log=self.log)
        if not self.camera.isCameraInit:
            self.camera = SimuCamera(0, directory_path=dir_path, log=self.log)
            self.log.addText( self.camera.__str__() )
        else:
            self.log.addText('Camera in use is: USB camera')

    def setWindToCenter(self):
        '''
        Set the MainWindow at the center of the desktop.
        '''
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def closeTabe(self, index):
        '''
        Remove the Tab of index index (integer).
        '''
        self.centraltab.removeTab(index)
        self.camera.stop_video()
        self.camera.close_camera()
        self.log.addText('Is camera closed ? {}'.format( not self.camera.isCameraInit ) )

    def getFile(self):
        '''
        Set the menue bar such that we can fetch a text file and display
        it on a textEdit widget
        '''
        self.textEdit = QTextEdit()
        grid          = QGridLayout()
        grid.addWidget(self.textEdit,3,1,5,1)
        self.centralwidget.setLayout(grid)

        openFile = QAction('Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.showDialog)

        self.filemenu.addAction(openFile)

    def initFileMenu(self):
        # --- Exit application --- #
        closeapp = QAction('&Exit', self) # QAction(QIcon('incon.png'), '&Exit', self)
        closeapp.triggered.connect(self.closeMainWindow)
        self.filemenu.addAction( '------' )
        self.filemenu.addAction(closeapp)

    def initSetupMenu(self):
        '''
        Make a new tab window with the display of the chosen structure (SWG, BS, ...).
        '''
        # --- Preview --- #
        openNewtab  = QAction('Preview', self)
        openNewtab.triggered.connect(self.insertNewTabPreview)
        self.setupmenu.addAction(openNewtab)
        # --- DC plot tab --- #
        openNewtab  = QAction('Peak comparison (PkComp)', self)
        openNewtab.triggered.connect(self.insertNewTabPeakComparison)
        self.setupmenu.addAction(openNewtab)
        # --- Lissajous plot tab --- #
        openNewtab  = QAction('Lissajous (Li)', self)
        openNewtab.triggered.connect(self.insertNewTabLissajousPlot)
        self.setupmenu.addAction(openNewtab)

    def initToolsMenu(self):
        '''
        Make a new tab window with the display of the chosen structure (SWG, BS, ...).
        '''
        # --- Application diagram --- #
        openNewtab  = QAction('App diagram', self)
        openNewtab.triggered.connect(self.insertNewTabAppDiagram)
        self.toolsmenu.addAction(openNewtab)

    def initCameraMenu(self):
        '''
        Make a new tab window with the display of the chosen structure (SWG, BS, ...).
        '''
        # --- Camera tab --- #
        openNewtab  = QAction('&Camera setup', self)
        openNewtab.triggered.connect(self.cameraManagementWindow)
        self.cameramenu.addAction(openNewtab)

    def cameraManagementWindow(self):
        self.cameraManag.show()

    def showDialog(self):
        '''
        Generate the window where we can browse for the wanted text file.
        '''
        fname = QFileDialog.getOpenFileName(self, 'Open file', './') #'/home/cgou')
        if fname[0]:
            f = open(fname[0], 'r')
            with f:
                data = f.read()
                self.textEdit.setText(data)

    def insertNewTabLogDisplay(self, log_objct):
        newtabindex = self.centraltab.addTab(log_objct,"Log")
        currentTbaBar = self.centraltab.tabBar()
        currentTbaBar.setTabButton(newtabindex, PyQt5.QtWidgets.QTabBar.RightSide, QLabel('')) # hide the close button
        self.centraltab.setCurrentIndex( newtabindex )

    def insertNewTabMainWidget(self):
        newtabindex = self.centraltab.addTab( self.centralwidget, "Main" ) # also: addTab(QWidget , QIcon , QString )
        self.centraltab.setCurrentIndex( newtabindex )

    def insertNewTabPreview(self):
        newtabindex = self.centraltab.addTab( Preview(camera=self.camera, log=self.log), "Preview" ) # also: addTab(QWidget , QIcon , QString )
        self.centraltab.setCurrentIndex( newtabindex )

    def insertNewTabAppDiagram(self):
        newtabindex = self.centraltab.addTab( self.centralwidget, "Main" ) # also: addTab(QWidget , QIcon , QString )
        self.centraltab.setCurrentIndex( newtabindex )

    def insertNewTabPeakComparison(self):
        newtabindex = self.centraltab.addTab( DCMeasurement(camera=self.camera, log=self.log), "PkComp" ) # also: addTab(QWidget , QIcon , QString )
        self.centraltab.setCurrentIndex( newtabindex )

    def insertNewTabLissajousPlot(self):
        newtabindex = self.centraltab.addTab( PhaseNetworkElements(camera=self.camera, log=self.log), "Lissa" ) # also: addTab(QWidget , QIcon , QString )
        self.centraltab.setCurrentIndex( newtabindex )

    def closeMainWindow(self):
        try:
            self.camera.stop_video()
            self.camera.close_camera()
        except:
            pass
        print('Is camera closed ? {}'.format( not self.camera.isCameraInit ) )
        self.close()