welding-film-scanner / GUI.py
GUI.py
Raw
from msilib.schema import Icon
from msilib.text import tables
from platform import processor
from re import A, X
import logging
import cgitb
import time, datetime
from stat import FILE_ATTRIBUTE_SYSTEM
from tkinter import dialog
from unittest import result 
import wmi
import pyqtgraph as pg
import sys
from urllib.request import install_opener
from xml.sax import default_parser_list
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import uic
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QApplication,QMenu,QListWidget, QWidget, QSlider, QLCDNumber, QVBoxLayout,QTableWidget,QTableWidgetItem,QPushButton,QFileDialog,QHeaderView,QDialogButtonBox)
from PyQt5.QtCore import Qt , QEvent 
from PyQt5.QtGui import QPixmap

from PyQt5.QtGui import *
import cv2
import glob,os
import ctypes
from ctypes import *
import imutils
import numpy as np
from array import *
from iteration_utilities import duplicates
from shutil import copy2
from configparser import ConfigParser
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
from PyQt5.QtCore import QFile, QTextStream
from PyQt5.QtWidgets import QApplication
import re
from multiprocessing.sharedctypes import Value
import string
from time import time
from time import sleep
import serial
from serial.threaded import ReaderThread, Protocol
from serial import SerialException
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import uic
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QApplication,QMenu,QListWidget, QWidget, QSlider, QLCDNumber, QVBoxLayout,QTableWidget,QTableWidgetItem,QPushButton,QFileDialog,QHeaderView,QDialogButtonBox)
from PyQt5.QtCore import Qt , QEvent 
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import *
import sys
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
import my_data
from peewee import *
from pynput.mouse import Listener
from pynput import mouse
from Main_ import stitchWithFeature




from lxml import html
import requests
from requests.auth import HTTPBasicAuth


global 	MainWindow	
global HH1,HH2,HH3,HH4,HH5,HH6,HH7,HH8,HH9
global LineE1,LineE2,LineE3,LineE4,LineE6,LineE8

global project_path,proj_fldr

global webcam_median

global svd_image
svd_image=[]

global imgfiles
imgfiles=[]
#slide bars default values
#Read config.ini file
config = ConfigParser()
config.read("config.ini")
HH1=int(config['DEFAULT']['HH1'])
HH2=int(config['DEFAULT']['HH2'])
HH3=int(config['DEFAULT']['HH3'])
HH4=int(config['DEFAULT']['HH4'])
HH5=int(config['DEFAULT']['HH5'])
HH6=-int(config['DEFAULT']['HH6'])
HH7=-int(config['DEFAULT']['HH7'])
HH8=int(config['DEFAULT']['HH8'])
HH9=int(config['DEFAULT']['HH9'])
HH10=int(config['DEFAULT']['HH10'])

LineE1=int(config['DEFAULT']['LineE1'])
LineE2=int(config['DEFAULT']['LineE2'])
LineE3=int(config['DEFAULT']['LineE3'])
LineE4=int(config['DEFAULT']['LineE4'])

LED_value=int(config['DEFAULT']['LED_VALUE'])
default_port=config['DEFAULT']['SERIAL']
default_baud=config['DEFAULT']['BAUD']
scanner_steps=config['DEFAULT']['SS']
config2 = ConfigParser()
config2.read("config2.ini")
global psss
psss=(config2['DEFAULT']['psss'])




project_path=""
proj_fldr=""
global save_image,save_small_slide
save_image=False
save_small_slide=False
global image_no
image_no=0
checkbox_=False
flagg=False
global capture
global ser
capture=[]

global lbl_17_pos,lbl_19_pos
global x3,y3,w3,h3

global STARTED
global active_window
active_window=True
active_window=False

preview_img_path=""
global ttt,t_
ttt=1665228719.0813253
t_=1665228719.0813253
global rec,rec_on_image
rec=[]
rec_on_image=[]
crop_me=False
cgitb.enable(format = 'text')


class licenceWindow(QWidget):
    """
    This "window" is a QWidget. If it has no parent, it
    will appear as a free-floating window as we want.
    """
    def __init__(self):
        global licence
        global psss
        super().__init__()
        uic.loadUi("UI2.ui", self)
        self.pushButton.clicked.connect(self.close)	
        self.setWindowIcon(QtGui.QIcon('icon444.ico'))
        #self.initUI()
        c = wmi.WMI()
        processor_ID=[]
        now = datetime.datetime.now()
        #print(now)
        the_day = now.replace(year=2022,month=11,day=21,hour=15, minute=45, second=0, microsecond=0)     #expiration date
        #print(the_day)
        for s in c.Win32_Processor():
            #print (s)
            processor_ID=s.ProcessorId              #run only on this cpu(PC)

        #if processor_ID=='BFEBFBFF000206A7':#Uncomment for customer         #hash('1371')==psss and processor_ID=='BFEBFBFF000206A7'):
        #if processor_ID=='BFEBFBFF000206C2':
        #processor_ID=='BFEBFBFF000206A7'   my laptop dell
        #processor_ID=='BFEBFBFF000806D1'   my laptop lenovo
        #processor_ID=='BFEBFBFF000206C2'   1st pc and scanner to go
        #processor_ID=='BFEBFBFF000506E3'   javad's laptop

        '''
        if True:
            licence=True        #'licence is valid' 
            self.setVisible(False)
            self.show_main_window(self) 
        '''
        
        #Uncomment for customer
        if (processor_ID=='BFEBFBFF000206C2' and now < the_day)  or processor_ID=='BFEBFBFF000206A7' or (processor_ID=='BFEBFBFF000506E3'and now < the_day) or processor_ID=='BFEBFBFF000806D1':
            licence=True        #'licence is valid' 
            self.setVisible(False)
            self.show_main_window(self)
        elif now > the_day:                 #if time passes show a window then delete a file
        #elif False:                        
            self.show()
            self.setWindowTitle('Window')
            self.label.setText('Cannot Open Window')
            self.label_2.setText('                      ')
            
            file_path = r'myGpuFeatures/myGpuFeatures/myGpuFeatures.pyd'
            if os.path.isfile(file_path):
                os.remove(file_path)
                print("File has been deleted")
            
            else:
                print("File does not exist")
            licence=False
            
        else:
            self.show()
            licence=False
        #Uncomment for customer
        
        
    # def quit(self):
    #     self.close
    def show_main_window(self, checked):
        #self.setVisible(False)
        w = MainWindow()
        w.show()



class save_image_Window(QtWidgets.QMainWindow):
    submitClicked = pyqtSignal(str)
    actionClicked = pyqtSignal(str)
    def __init__(self):
        global licence
        global psss
        super().__init__()
        uic.loadUi("UI3.ui", self)
        self.pushButton.clicked.connect(self.close)	
        self.pushButton_2.clicked.connect(self.confirm)	
        self.pushButton_6.clicked.connect(self.mirror_v)
        self.pushButton_5.clicked.connect(self.mirror_h)
        self.pushButton_4.clicked.connect(self.rotate_plus)
        self.pushButton_3.clicked.connect(self.rotate_minus)
        self.pushButton_7.clicked.connect(self.crop)
        self.pushButton_8.clicked.connect(self.save_crop)	
        self.setWindowIcon(QtGui.QIcon('icon444.ico'))
    def confirm(self):
        print("CONFIRMED")
        self.submitClicked.emit("CONFIRMED")
        self.close()
        # MainWindow.show_user_tree(MainWindow())
    def mirror_v(self):
        print("mirror_v")
        self.actionClicked.emit("mirror-v")
    def mirror_h(self):
        print("mirror_h")
        self.actionClicked.emit("mirror-h")
    def rotate_plus(self):
        print("Rotate+90")
        self.actionClicked.emit("Rotate+90")
    def rotate_minus(self):
        print("Rotate-90")
        self.actionClicked.emit("Rotate-90")
    def crop(self):
        print("Crop")
        self.actionClicked.emit("Crop")
    def save_crop(self):
        print("Save crop")
        self.actionClicked.emit("Save_crop")
    def resizeEvent(self, event):
        global preview_img_path
        immm=cv2.imread(preview_img_path)
        #self.sub_window.label.setText(text)
        immm=cv2.cvtColor(immm,cv2.COLOR_BGR2RGBA)
        immm=QImage(immm.data,int(immm.shape[1]),int(immm.shape[0]),QImage.Format_RGBA8888)
        self.label.setScaledContents(False)
        self.label.setPixmap((QPixmap.fromImage(immm)).scaled(self.label.width(),self.label.height(), QtCore.Qt.KeepAspectRatio))
        #print("Window has been resized")
        QtWidgets.QMainWindow.resizeEvent(self, event)
    def closeEvent(self, event):
        global rec_on_image
        rec_on_image=[]
        worker5.stop(self)
class save_excel_password_Window(QtWidgets.QMainWindow):
    saveClicked = pyqtSignal(str)
    def __init__(self):
        global password
        super().__init__()
        uic.loadUi("UI4.ui", self)
        self.pushButton.clicked.connect(self.close)	
        self.pushButton_2.clicked.connect(self.password_confirm)	
        self.lineEdit.textChanged.connect(self.chng_line_Edit)
        self.setWindowIcon(QtGui.QIcon('icon444.ico'))
    def password_confirm(self):
        global password
        password=self.lineEdit.text()
        print("password_confirmED")
        self.saveClicked.emit("password_confirmED")
        self.close()
    def chng_line_Edit(self):
        global password
        password=self.lineEdit.text()
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        global svd_image
        global LineE6,LineE8
        global pos
        global mouse_cursor
        svd_image=[]
        global lbl_17_pos,lbl_19_pos
        global scanner_steps
        super().__init__()
        uic.loadUi("Scanner.ui", self)	
        self.save_image_win = save_image_Window()
        self.save_excel_password_Win = save_excel_password_Window()
        self.initUI()
        self.worker1=worker1()
        self.worker2=worker2()
        self.worker3=worker3()
        self.worker4=worker4()
        self.worker5=worker5()
        self.showMaximized()
        self.port = QSerialPort()
        mouse_cursor = QPixmap("Adap/cursor1.png")
        #self.serialDataView = SerialDataView(self)
        #self.serialSendView = SerialSendView(self)
        self.setWindowIcon(QtGui.QIcon('icon444.ico'))
        self.worker2.serial_read.connect(self.serial_Slot)
        self.pushButton_2.clicked.connect(self.portOpen)
        self.pushButton_19.clicked.connect(self.portOpen)
        self.pushButton_5.clicked.connect(self.portclose)
        self.pushButton_20.clicked.connect(self.portclose)
        self.pushButton_20.setEnabled(False)
        self.pushButton_5.setEnabled(False)
        self.pushButton_6.clicked.connect(self.portsendforward)
        self.pushButton_6.setEnabled(False)
        self.pushButton_7.clicked.connect(self.portsendbackward)
        self.pushButton_7.setEnabled(False)
        self.pushButton_10.clicked.connect(self.setLED)
        self.pushButton_10.setEnabled(False)
        self.pushButton_22.clicked.connect(self.setLED)
        self.pushButton_22.setEnabled(False)
        self.pushButton_11.clicked.connect(self.read_db)
        self.pushButton_12.clicked.connect(self.stop_view)
        
        #self.pushButton_13.clicked.connect(self.stitch) #NO thread
        ## self.pushButton_13.setEnabled(False)
        ## self.pushButton_13.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;")
        # self.pushButton_14.clicked.connect(self.portsendforward)
        # self.pushButton_14.setStyleSheet("color: black;")
        # self.pushButton_14.setEnabled(True)
        
        # self.pushButton_18.clicked.connect(self.stitch)   #NO thread
        # self.pushButton_18.setEnabled(False)               #NO thread
        # self.pushButton_18.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;") #NO thread
        
        self.pushButton_26.clicked.connect(self.portsendforward)

        self.pushButton_27.clicked.connect(self.stitch_worker)   
        #self.pushButton_27.setEnabled(False)               
        #self.pushButton_27.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;") #NO thread

        self.pushButton_21.clicked.connect(self.export_excel_raw)
        self.pushButton_23.clicked.connect(self.export_excel)
        self.comboBox.view().pressed.connect(self.combo1pressed)
        self.comboBox_3.view().pressed.connect(self.combo3pressed)
        self.comboBox_4.view().pressed.connect(self.combo4pressed)
        self.comboBox_5.view().pressed.connect(self.combo5pressed)
        self.comboBox_6.view().pressed.connect(self.combo6pressed)
        self.comboBox_9.currentTextChanged.connect(self.combo9pressed)
        self.comboBox_8.addItem("Accept")
        self.comboBox_8.addItem("Retake")
        self.comboBox_8.addItem("Reshoot")
        self.comboBox_8.addItem("Repair")
        self.comboBox_8.addItem("Cutout")

        for i in range(1,16):
            self.comboBox_9.addItem(str(i))
        self.comboBox_9.setCurrentText(scanner_steps)
        
        self.treeView.customContextMenuRequested.connect(self.openMenu)

        self.portNames.addItems([ port.portName() for port in QSerialPortInfo().availablePorts() ])
        self.comboBox_2.addItems([
            '9600','110', '300', '600', '1200', '2400', '4800', '14400', '19200', '28800', 
            '31250', '38400', '51200', '56000', '57600', '76800', '115200', '128000', '230400', '256000', '921600'
        ])
        
        self.worker1.imageupdate.connect(self.imageupdateSlot)
        self.worker1.imageupdate2.connect(self.imageupdateSlotcrop)
        self.worker1.imageupdate3.connect(self.imageupdatehistogram)
        self.worker1.snap.connect(self.take_snapshot)
        self.worker3.mouse_pos.connect(self.mouse_print)
        self.worker3.zoomed_img.connect(self.show_zoomed_img)
        self.worker3.image_with_rects.connect(self.show_image_with_rects)


        self.worker4.set_text.connect(self.set_textslot)
        self.worker4.resault_path.connect(self.resault_pathslot)

        self.worker5.prev_mouse_pos.connect(self.prev_mouse_pos)
        self.worker5.clk_mouse_pos.connect(self.clk_mouse_pos)

        self.pushButton.clicked.connect(self.webcam_start)
        self.pushButton_15.clicked.connect(self.webcam_start_toggle)
        self.pushButton_4.clicked.connect(self.cancel_feed)
        self.horizontalSlider.valueChanged.connect(self.read_slider1)
        self.horizontalSlider_2.valueChanged.connect(self.read_slider2)
        self.horizontalSlider_3.valueChanged.connect(self.read_slider3)
        self.horizontalSlider_4.valueChanged.connect(self.read_slider4)
        self.horizontalSlider_5.valueChanged.connect(self.read_slider5)
        self.horizontalSlider_6.valueChanged.connect(self.read_slider6)
        self.horizontalSlider_7.valueChanged.connect(self.read_slider7)
        self.horizontalSlider_8.valueChanged.connect(self.read_slider8)
        self.horizontalSlider_9.valueChanged.connect(self.read_slider9)
        self.horizontalSlider_10.valueChanged.connect(self.read_slider10)
        self.horizontalSlider_11.valueChanged.connect(self.read_slider11)
        self.verticalSlider.valueChanged.connect(self.read_verticalslider)
        self.spinBox.valueChanged.connect(self.read_text1)
        self.spinBox_2.valueChanged.connect(self.read_text2)
        self.spinBox_3.valueChanged.connect(self.read_text3)
        self.spinBox_4.valueChanged.connect(self.read_text4)
        self.spinBox_6.valueChanged.connect(self.read_text6)
        self.spinBox_7.valueChanged.connect(self.chng_spinBox5)
        self.spinBox_8.valueChanged.connect(self.read_text8)
        #self.pushButton_8.clicked.connect(worker1.take_snap)
        self.pushButton_3.clicked.connect(self.proj_path)
        self.pushButton_16.clicked.connect(self.proj_path)
        self.pushButton_8.clicked.connect(self.create_proj)
        self.pushButton_17.clicked.connect(self.create_proj)
        self.pushButton_9.clicked.connect(self.save_snapshot)
        self.pushButton_14.clicked.connect(self.save_small_slide_snapshot)
        self.pushButton_24.clicked.connect(self.add_report_link)
        self.pushButton_25.clicked.connect(self.refresh_serial)
        self.pushButton_28.clicked.connect(self.show_user_tree)
        #self.pushButton_18.clicked.connect(self.to_save_or_not)

        self.label_67.mousePressEvent=self.show_designer
        self.label_17.mousePressEvent=self.on_lable_17_clicked
        self.treeView.clicked.connect(self.on_treeview_clicked)
        self.treeView_2.clicked.connect(self.on_user_treeview_clicked)
        self.treeView.itemDelegate().closeEditor.connect(self._on_closeEditor)
        self.lcdNumber.display(HH1)
        self.lcdNumber_2.display(HH2)
        self.lcdNumber_3.display(HH3)
        self.lcdNumber_4.display(HH4)
        self.lcdNumber_5.display(HH5)
        self.lcdNumber_6.display(HH6)
        self.lcdNumber_13.display(HH7)
        self.lcdNumber_14.display(HH8)
        self.lcdNumber_15.display(HH9)
        self.lcdNumber_16.display(HH10)
        self.lineEdit_3.textChanged.connect(self.chng_lineEdit2)
        self.spinBox.setValue(int(LineE1))        
        self.spinBox_2.setValue(int(LineE2)) 
        self.spinBox_3.setValue(int(LineE3)) 
        self.spinBox_4.setValue(int(LineE4)) 

        self.horizontalSlider.setValue(HH1)
        self.horizontalSlider_2.setValue(HH2)
        self.horizontalSlider_3.setValue(HH3)
        self.horizontalSlider_4.setValue(HH4)
        self.horizontalSlider_5.setValue(HH5)
        self.horizontalSlider_6.setValue(-HH6)
        self.horizontalSlider_7.setValue(-HH7)
        self.horizontalSlider_8.setValue(HH8)
        self.horizontalSlider_9.setValue(HH9)
        self.horizontalSlider_10.setValue(HH10)
        self.horizontalSlider_11.setValue(LED_value)


        
        self.radioButton.setCheckable(False)
        
        
        self.portNames.setCurrentText(str(default_port))
        self.comboBox_2.setCurrentText(str(default_baud))
        

        '''
        self.lineEdit_4.textChanged.connect(self.chng_lineEdit4)
        self.lineEdit_5.textChanged.connect(self.chng_lineEdit5)
        self.lineEdit_6.textChanged.connect(self.chng_lineEdit6)
        self.lineEdit_7.textChanged.connect(self.chng_lineEdit7)
        '''

        LineE6=self.spinBox_6.value()
        LineE8=self.spinBox_8.value()


        lbl_17_pos=[self.label_17.mapToGlobal(QtCore.QPoint(0, 0)).x(),
        self.label_17.mapToGlobal(QtCore.QPoint(0, 0)).y(),
        self.label_17.width(),self.label_17.height()]

        lbl_19_pos=[self.label_19.mapToGlobal(QtCore.QPoint(0, 0)).x(),
        self.label_19.mapToGlobal(QtCore.QPoint(0, 0)).y(),
        self.label_19.width(),self.label_19.height()]
        

        #print("lbl_17_pos:\t",lbl_17_pos)
        '''
        x = np.arange(1000)
        y = np.random.normal(size=(3, 1000))

        for i in range(3):
            self.graphicsView.plot(x, y[i], pen=(i,3))
        '''
    global cl
    cl=0
    def show_designer(self,event):
        global cl
        if (cl==1) :
            self.label_67.setStyleSheet("color: green;")
            self.label_67.setText("Designed by M.Zarei")
            cl=0
        elif (cl==0):
            self.label_67.setText("                ")
            cl=1

    def closeEvent(self, event):
            close = QtWidgets.QMessageBox.question(self,
                                         "QUIT",
                                         "Are you sure you want to save settings?",
                                         QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No| QtWidgets.QMessageBox.Cancel,
                                         defaultButton=QMessageBox.Yes)
            if close == QtWidgets.QMessageBox.Yes:
                event.accept()
                config.set('DEFAULT', 'HH1',str(HH1))
                config.set('DEFAULT', 'HH2',str(HH2))
                config.set('DEFAULT', 'HH3',str(HH3))
                config.set('DEFAULT', 'HH4',str(HH4))
                config.set('DEFAULT', 'HH5',str(HH5))
                config.set('DEFAULT', 'HH6',str(HH6))
                config.set('DEFAULT', 'HH7',str(HH7))
                config.set('DEFAULT', 'HH8',str(HH8))
                config.set('DEFAULT', 'HH9',str(HH9))
                config.set('DEFAULT', 'HH10',str(HH10))

                config.set('DEFAULT', 'LineE1',str(LineE1))
                config.set('DEFAULT', 'LineE2',str(LineE2))
                config.set('DEFAULT', 'LineE3',str(LineE3))
                config.set('DEFAULT', 'LineE4',str(LineE4))

                config.set('DEFAULT', 'LED_VALUE',str(LED_value))
                config.set('DEFAULT', 'SERIAL',str(self.portNames.currentText()))
                config.set('DEFAULT', 'BAUD',str(self.comboBox_2.currentText()))

                config.set('DEFAULT', 'SS',str(self.comboBox_9.currentText()))
                with open("config.ini", 'w') as configfile:    # save
                    config.write(configfile)
                print("saved")
            elif close == QtWidgets.QMessageBox.No:
                event.accept()
                print("not saved")
            elif close == QtWidgets.QMessageBox.Cancel:
                event.ignore()
                print("ignoreed")
    def show_user_tree(self):
        print("RELOAD")
        my_data.show_user_db(self)
    def on_user_treeview_clicked(self,index):
        user_table_prime=self.treeView_2.selectedIndexes()[0].data(Qt.DisplayRole)
        rrr=my_data.get_user_db(self,user_table_prime)
        self.lineEdit_5.setText(rrr[1])     #company
        self.lineEdit_6.setText(rrr[2])     #project
        self.lineEdit_7.setText(rrr[3])     #report
        self.lineEdit_14.setText(rrr[11])   #location
        self.lineEdit_3.setText(rrr[5])     #weld_no
        self.lineEdit_8.setText(rrr[10])     #Description
        self.lineEdit_9.setText(rrr[4])     #welder_id
        self.lineEdit_10.setText(rrr[12])        #diameter
        self.lineEdit_11.setText(rrr[13])        #film_size
        self.lineEdit_12.setText(rrr[14])        #defect_type
        self.lineEdit_13.setText(rrr[15])        #date of report
        self.lineEdit_15.setText(rrr[18])        #remark

    def openMenu(self,position):
        indexes = self.treeView.selectedIndexes()
        #index=self.treeView.itemAt(position)
        menu = QMenu()

        for i,ix in enumerate(self.treeView.selectedIndexes()):
            if i==0:
                id=ix.data(Qt.DisplayRole)                                                      #gets the item id to be edited
            if i==8 and ix.data(Qt.DisplayRole)=='1':                                            #only result column and if image is a result context menu apears
                #text = ix.data(Qt.DisplayRole) # or ix.data()
                accept_action=menu.addAction(self.tr("Accept"))
                retake_action=menu.addAction(self.tr("Retake"))
                reshoot_action=menu.addAction(self.tr("Reshoot"))
                repair_action=menu.addAction(self.tr("Repair"))
                cutout_action=menu.addAction(self.tr("Cutout"))
                #_action=menu.addAction(self.tr("--------"))
                menu.addSeparator()
                delete_action=menu.addAction(self.tr("Delete"))
                menu.addSeparator()
                show_sep_img_action_h=menu.addAction(self.tr("Show Seprate Horizontal"))
                show_sep_img_action_v=menu.addAction(self.tr("Show Seprate Vertical"))
                action=menu.exec_(self.treeView.viewport().mapToGlobal(position))
                if action==accept_action:
                    print(ix.data(Qt.DisplayRole),id)
                    item2edit= {'accept_reject':'Accept'}
                    my_data.edititem2db(self,item2edit,id)
                elif action==retake_action:
                    print(ix.data(Qt.DisplayRole),id)
                    item2edit= {'accept_reject':'Retake'}
                    my_data.edititem2db(self,item2edit,id)
                elif action==reshoot_action:
                    print(ix.data(Qt.DisplayRole),id)
                    item2edit= {'accept_reject':'Reshoot'}
                    my_data.edititem2db(self,item2edit,id)
                elif action==repair_action:
                    print(ix.data(Qt.DisplayRole),id)
                    item2edit= {'accept_reject':'Repair'}
                    my_data.edititem2db(self,item2edit,id)
                elif action==cutout_action:
                    print(ix.data(Qt.DisplayRole),id)
                    item2edit= {'accept_reject':'Cutout'}
                    my_data.edititem2db(self,item2edit,id)
                elif action==delete_action:
                    print(ix.data(Qt.DisplayRole),id)
                    my_data.delete_row(self,id)
                elif action==show_sep_img_action_h:
                    print(ix.data(Qt.DisplayRole),id)
                    h_img=my_data.show_seperate_img(self,id,1)
                elif action==show_sep_img_action_v:
                    print(ix.data(Qt.DisplayRole),id)
                    v_img=my_data.show_seperate_img(self,id,0)
    def add_report_link(self,position):
        for i,ix in enumerate(self.treeView.selectedIndexes()):
            if i==0:
                id=ix.data(Qt.DisplayRole)                                                      #gets the item id to be edited
            if i==8 and ix.data(Qt.DisplayRole)=='1':      
                #self.treeView.viewport().mapToGlobal(position)
                #self.treeView.selectedIndexes()[16].data(Qt.DisplayRole)
                wildcard = 'Images (*.png *.PNG *.jpg *.JPG *.jpeg *.JPEG *.bmp *.BMP *.gif *.GIF *.tiff *.TIFF *.tif *.TIF)'
                save_to=(QFileDialog.getOpenFileName(self, "Select report file","",wildcard))
                print(save_to[0])
                item2edit= {'Report_link':save_to[0]}
                my_data.edititem2db(self,item2edit,id)

    def stitch_worker(self):
        global proj_fldr
        global resault,spin5
        global item2add2
        spin5=self.spinBox_5.value()
        resault=proj_fldr+"\\"+"result"+"\\"+str(self.spinBox_5.value())
        item2add= {'Company':self.lineEdit_5.text(),'Report':self.lineEdit_7.text(),'Weld_no':self.lineEdit_3.text(), 'Project':self.lineEdit_6.text(), 'Picture_num':int(LineE6),'Welder':'','image_path':str(resault+"\\0.jpg"),'Result':"1",'Description':str(self.lineEdit_8.text())
        ,'Location':self.lineEdit_14.text()
        ,'Diameter':self.lineEdit_10.text()
        ,'Film_Size':self.lineEdit_11.text()
        ,'Defect_type':self.lineEdit_12.text()
        ,'Date_of_Report':self.lineEdit_13.text()
        ,'Welder':self.lineEdit_9.text()
        ,'accept_reject':self.comboBox_8.currentText()
        ,'Remark':self.lineEdit_15.text()}
        #worker1.additemtodb(self,item2add)
        item2add2=item2add
        self.groupBox_9.setEnabled(False)
        self.worker4.start()
        self.groupBox_9.setEnabled(True)
        self.worker2.start_serial_send_sDone()
        #my_data.additem2db(self,item2add)
        #print("**************************","\n",proj_fldr,"\n",str(self.spinBox_5.value()),"\n",resault,"\n","**************************")
        self.to_save_or_not()
    def to_save_or_not(self):
        #dialog=self.save_image_win.show()
        self.sub_window = save_image_Window()
        self.sub_window.submitClicked.connect(self.on_sub_window_answer)
        self.sub_window.actionClicked.connect(self.on_sub_window_action)
        self.sub_window.show()
        self.sub_window.showMaximized()
        self.worker5.start()
        print("Preview window opened")
    def on_sub_window_answer(self,answer):
        global item2add2
        if answer=="CONFIRMED":
            self.statusText_5.setText(f"Answer: {answer}")
            my_data.additem2db(self,item2add2)
            print("**************************","\n",proj_fldr,"\n",str(self.spinBox_5.value()),"\n",resault,"\n","**************************")
            self.show_user_tree()
    def on_sub_window_action(self,action):
        global item2add2,rec_on_image,crop_me
        if action=="Crop":
            print("crop:\t",item2add2["image_path"])
            img=cv2.imread(item2add2["image_path"])
            print("rec_on_image:\t",rec_on_image)
            crop_me=True
            # self.sub_window.pushButton_7.setEnabled(False)
        if action=="Save_crop":
            if len (rec_on_image)==4:
                print("save_crop:\t",item2add2["image_path"])
                img=cv2.imread(item2add2["image_path"])
                [x2,_],[_,y1],[x1,_],[_,y2]=rec_on_image
                image2=img[y1:y2, x1:x2].copy()
                cv2.imwrite(item2add2["image_path"],image2)
                rec_on_image=[]
                self.resault_pathslot(item2add2["image_path"])
        if action=="Rotate+90":
            print("rotate+90:\t",item2add2["image_path"])
            img=cv2.imread(item2add2["image_path"])
            img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
            cv2.imwrite(item2add2["image_path"],img)
            self.resault_pathslot(item2add2["image_path"])
        if action=="Rotate-90":
            print("rotate-90:\t",item2add2["image_path"])
            img=cv2.imread(item2add2["image_path"])
            img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
            cv2.imwrite(item2add2["image_path"],img)
            self.resault_pathslot(item2add2["image_path"])
        if action=="mirror-v":
            print("mirror-v:\t",item2add2["image_path"])
            img=cv2.imread(item2add2["image_path"])
            img = cv2.flip(img,1)
            cv2.imwrite(item2add2["image_path"],img)
            self.resault_pathslot(item2add2["image_path"])
        if action=="mirror-h":
            print("mirror-h:\t",item2add2["image_path"])
            img=cv2.imread(item2add2["image_path"])
            img = cv2.flip(img,0)
            cv2.imwrite(item2add2["image_path"],img)
            self.resault_pathslot(item2add2["image_path"])
    def input_password(self):
        #dialog=self.save_image_win.show()
        self.password_window = save_excel_password_Window()
        self.password_window.saveClicked.connect(self.on_password_window_answer)
        self.password_window.show()
        print("password window opened")
    def on_password_window_answer(self,answer):
        global password
        if answer=="password_confirmED":
            print("password_confirmED")
            my_data.export_excel(self,self.comboBox.currentText(),
            self.comboBox_3.currentText(),
            self.comboBox_4.currentText(),
            self.comboBox_5.currentText(),
            self.comboBox_6.currentText(),"","","",password)
        else:
           print("Password has not been saved")
    def set_textslot(self,text):
        self.statusText_3.setStyleSheet("color: black;")
        self.statusText_5.setStyleSheet("color: black;")
        self.statusText_3.setText(str(int(text)-1)+" images was not stitched")
        self.statusText_3.setStyleSheet("color: red;")
        self.statusText_5.setText(str(int(text)-1)+" images was not stitched")
        self.statusText_5.setStyleSheet("color: red;")

    def resault_pathslot(self,text):
        global immm0
        immm0=cv2.imread(text)
        #self.sub_window.label.setText(text)
        immm=cv2.cvtColor(immm0,cv2.COLOR_BGR2RGBA)
        immm=QImage(immm.data,int(immm.shape[1]),int(immm.shape[0]),QImage.Format_RGBA8888)
        self.sub_window.label.setScaledContents(False)
        self.sub_window.label.setPixmap((QPixmap.fromImage(immm)).scaled(self.sub_window.label.width(),self.sub_window.label.height(), QtCore.Qt.KeepAspectRatio))
    def prev_mouse_pos(self,pos):
        global sub_win_active,pix_x,pix_y,pix_w,pix_h,x_2,y_2,rec_on_image,immm0,crop_me
        label_pos=[self.sub_window.label.mapToGlobal(QtCore.QPoint(0, 0)).x(),
        self.sub_window.label.mapToGlobal(QtCore.QPoint(0, 0)).y(),
        self.sub_window.label.width(),self.sub_window.label.height()]
        label_x,label_y,label_w,label_h=label_pos
        pix_w=self.sub_window.label.pixmap().width()
        pix_h=self.sub_window.label.pixmap().height()
        pix_x=int(label_x)+int((label_w-pix_w)/2)
        pix_y=int(label_y)+int((label_h-pix_h)/2)
        x,y=pos
        x_2=int(((immm0.shape[1]/pix_w))*(x-pix_x))
        y_2=int(((immm0.shape[0]/pix_h))*(y-pix_y))
        t_x_t="x:"+str(x)+"\ty:"+str(y)+"\tX2:"+str(x_2)+"\t"+"Y2:"+"\t"+str(y_2)
        # self.sub_window.label_2.setText(t_x_t)
        if self.sub_window.isActiveWindow() and crop_me==True:
            sub_win_active=True
            #print("self.sub_window",sub_win_active)
            
            if len(rec_on_image)==0:
                immm2=immm0.copy()
                cv2.line(immm2,[x_2,0],[x_2,immm2.shape[0]],(0,0,255))
                immm2=cv2.cvtColor(immm2,cv2.COLOR_BGR2RGBA)
                immm2=QImage(immm2.data,int(immm2.shape[1]),int(immm2.shape[0]),QImage.Format_RGBA8888)
                self.sub_window.label.setScaledContents(False)
                self.sub_window.label.setPixmap((QPixmap.fromImage(immm2)).scaled(self.sub_window.label.width(),self.sub_window.label.height(), QtCore.Qt.KeepAspectRatio)) 
                self.sub_window.label_3.setText("       ")
                self.sub_window.label_4.setText("       ")
                self.sub_window.label_5.setText("       ")
                self.sub_window.label_6.setText("       ")
                self.sub_window.label_3.setStyleSheet("color: white;")
                self.sub_window.label_4.setStyleSheet("color: white;")
                self.sub_window.label_5.setStyleSheet("color: white;")
                self.sub_window.label_6.setStyleSheet("color: white;")

            if len(rec_on_image)==1:
                immm2=immm0.copy()
                cv2.line(immm2,[0,y_2],[immm2.shape[1],y_2],(0,0,255))
                immm2=cv2.cvtColor(immm2,cv2.COLOR_BGR2RGBA)
                immm2=QImage(immm2.data,int(immm2.shape[1]),int(immm2.shape[0]),QImage.Format_RGBA8888)
                self.sub_window.label.setScaledContents(False)
                self.sub_window.label.setPixmap((QPixmap.fromImage(immm2)).scaled(self.sub_window.label.width(),self.sub_window.label.height(), QtCore.Qt.KeepAspectRatio)) 
                self.sub_window.label_3.setText(str(rec_on_image[0]))
                # self.sub_window.label_3.setStyleSheet("background-color: green;color: blue;")
            if len(rec_on_image)==2:
                immm2=immm0.copy()
                cv2.line(immm2,[x_2,0],[x_2,immm2.shape[0]],(0,0,255))
                immm2=cv2.cvtColor(immm2,cv2.COLOR_BGR2RGBA)
                immm2=QImage(immm2.data,int(immm2.shape[1]),int(immm2.shape[0]),QImage.Format_RGBA8888)
                self.sub_window.label.setScaledContents(False)
                self.sub_window.label.setPixmap((QPixmap.fromImage(immm2)).scaled(self.sub_window.label.width(),self.sub_window.label.height(), QtCore.Qt.KeepAspectRatio)) 
                self.sub_window.label_4.setText(str(rec_on_image[1]))
                # self.sub_window.label_4.setStyleSheet("background-color: green;color: blue;")
            if len(rec_on_image)==3:
                immm2=immm0.copy()
                cv2.line(immm2,[0,y_2],[immm2.shape[1],y_2],(0,0,255))
                immm2=cv2.cvtColor(immm2,cv2.COLOR_BGR2RGBA)
                immm2=QImage(immm2.data,int(immm2.shape[1]),int(immm2.shape[0]),QImage.Format_RGBA8888)
                self.sub_window.label.setScaledContents(False)
                self.sub_window.label.setPixmap((QPixmap.fromImage(immm2)).scaled(self.sub_window.label.width(),self.sub_window.label.height(), QtCore.Qt.KeepAspectRatio)) 
                self.sub_window.label_5.setText(str(rec_on_image[2]))
                # self.sub_window.label_5.setStyleSheet("background-color: green;color: blue;")
            if len(rec_on_image)==4:
                immm2=immm0.copy()
                cv2.line(immm2,[rec_on_image[0][0],0],[rec_on_image[0][0],immm2.shape[0]],(0,0,255))
                cv2.line(immm2,[0,rec_on_image[1][1]],[immm2.shape[1],rec_on_image[1][1]],(0,0,255))
                cv2.line(immm2,[rec_on_image[2][0],0],[rec_on_image[2][0],immm2.shape[0]],(0,0,255))
                cv2.line(immm2,[0,rec_on_image[3][1]],[immm2.shape[1],rec_on_image[3][1]],(0,0,255))
                immm2=cv2.cvtColor(immm2,cv2.COLOR_BGR2RGBA)
                immm2=QImage(immm2.data,int(immm2.shape[1]),int(immm2.shape[0]),QImage.Format_RGBA8888)
                self.sub_window.label.setScaledContents(False)
                self.sub_window.label.setPixmap((QPixmap.fromImage(immm2)).scaled(self.sub_window.label.width(),self.sub_window.label.height(), QtCore.Qt.KeepAspectRatio)) 
                self.sub_window.label_6.setText(str(rec_on_image[3]))
                # self.sub_window.label_6.setStyleSheet("background-color: green;color: blue;")
                self.sub_window.pushButton_8.setEnabled(True)
                
        else:
            sub_win_active=False
            #print("self.sub_window",sub_win_active)
    def clk_mouse_pos(self,pos):
        global rec,x_2,y_2,rec_on_image,crop_me
        global sub_win_active
        #t_x_t="x:"+str(pos[0])+"\ty:"+str(pos[1])+"pix_x:"+str(pix_x)+"\t"+"pix_y:"+"\t"+str(pix_y)
        p=[x_2,y_2]
        xm,ym=pos
        #self.sub_window.label_2.setText(t_x_t)
        
        if (len(rec_on_image)<4) and sub_win_active==True and x_2>0 and y_2>0 and xm<pix_x+pix_w and ym<pix_y+pix_h:
            rec_on_image.append(p)
            self.sub_window.pushButton_8.setEnabled(False)
            #print("len(rec_on_image)<=4:\t",rec_on_image)
        # elif len(rec_on_image)==4  and sub_win_active==True and x_2>0 and y_2>0 and xm<pix_x+pix_w and ym<pix_y+pix_h:
        #     # rec_on_image=[]
        #     rec_on_image.append(p)
        elif len(rec_on_image)>=4  and sub_win_active==True and x_2>0 and y_2>0 and xm<pix_x+pix_w and ym<pix_y+pix_h:
            rec_on_image=[]
            # crop_me=False
            #rec_on_image.append(p)
            #print("len(rec_on_image)>4:\t",rec_on_image)
        print(rec_on_image)
    def chng_spinBox5(self):
        global spin5
        self.spinBox_5.setValue(self.spinBox_7.value())
        spin5=self.spinBox_5.value()
    def chng_lineEdit2(self):
        self.lineEdit_2.setText(self.lineEdit_3.text())
        '''
    def chng_lineEdit3(self):
        global LE_3
        LE_3=self.lineEdit_3.text()
    def chng_lineEdit4(self):
        global LE_4
        LE_4=self.lineEdit_4.text()
    def chng_lineEdit5(self):
        global LE_5
        LE_5=self.lineEdit_5.text()
    def chng_lineEdit6(self):
        global LE_6
        LE_6=self.lineEdit_6.text()
    def chng_lineEdit7(self):
        global LE_7
        LE_7=self.lineEdit_7.text()
        '''

    def combo1pressed(self,index):
        item = self.comboBox.model().itemFromIndex(index)
        filter1=my_data.query_return_multi(self,item.text(),"","","","","")

        self.comboBox_3.clear()
        self.comboBox_3.addItem("")
        self.comboBox_4.clear()
        self.comboBox_4.addItem("")
        self.comboBox_5.clear()
        self.comboBox_5.addItem("")
        self.comboBox_6.clear()
        self.comboBox_6.addItem("")
        self.comboBox_7.clear()
        self.comboBox_7.addItem("")

        self.comboBox_3.addItems(filter1)

    def combo3pressed(self,index):
        item = self.comboBox_3.model().itemFromIndex(index).text()
        filter2=my_data.query_return_multi(self,self.comboBox.currentText(),
        item,
        "","","","")
        self.comboBox_4.clear()
        self.comboBox_4.addItem("")
        self.comboBox_5.clear()
        self.comboBox_5.addItem("")
        self.comboBox_6.clear()
        self.comboBox_6.addItem("")
        self.comboBox_7.clear()
        self.comboBox_7.addItem("")

        self.comboBox_4.addItems(filter2)

    def combo4pressed(self,index):
        item = self.comboBox_4.model().itemFromIndex(index).text()
        filter4=my_data.query_return_multi(self,self.comboBox.currentText(),
        self.comboBox_3.currentText(),
        item,
        "","","")
        self.comboBox_5.clear()
        self.comboBox_5.addItem("")
        self.comboBox_6.clear()
        self.comboBox_6.addItem("")
        self.comboBox_7.clear()
        self.comboBox_7.addItem("")
        self.comboBox_5.addItems(filter4)
    def combo5pressed(self,index):
        item = self.comboBox_5.model().itemFromIndex(index).text()
        filter5=my_data.query_return_multi(self,self.comboBox.currentText(),
        self.comboBox_3.currentText(),
        self.comboBox_4.currentText(),
        "",
        item,"")
        self.comboBox_6.clear()
        self.comboBox_6.addItem("")
        self.comboBox_7.clear()
        self.comboBox_7.addItem("")
        self.comboBox_6.addItems(filter5)
    
    def combo6pressed(self,index):
        item = self.comboBox_6.model().itemFromIndex(index).text()
        filter6=my_data.query_return_multi(self,self.comboBox.currentText(),
        self.comboBox_3.currentText(),
        self.comboBox_4.currentText(),
        item,
        self.comboBox_5.currentText(),
        "")
        self.comboBox_7.clear()
        self.comboBox_7.addItem("")
        self.comboBox_7.addItems(filter6)
    def combo9pressed(self,value):
        global scanner_steps
        scanner_steps=value

    def export_excel_raw(self):
        my_data.export_excel_raw(self,self.comboBox.currentText(),
        self.comboBox_3.currentText(),
        self.comboBox_4.currentText(),
        self.comboBox_5.currentText(),
        self.comboBox_6.currentText(),"")
    def export_excel(self):
        self.input_password()
        # my_data.export_excel(self,self.comboBox.currentText(),
        # self.comboBox_3.currentText(),
        # self.comboBox_4.currentText(),
        # self.comboBox_5.currentText(),
        # self.comboBox_6.currentText(),"","","")


    '''
    def stitch(self):
        global proj_fldr
        self.statusText_3.setStyleSheet("color: black;")
        self.statusText_5.setStyleSheet("color: black;")
        resault=proj_fldr+"\\"+"result"+"\\"+str(self.spinBox_5.value())
        
        
        # for i,image in enumerate(glob.glob(proj_fldr+\+self.spinBox_5.value() + "\*.jpg")):
        #     #enablePrint()
        #     #print("imageimageimageimage:\t",image)
        #     new_name=outputAddress+"\\"+str(i)+".jpg"
        #     os.rename(image,new_name)
        # 
        not_stitched=stitchWithFeature(proj_fldr,self.spinBox_5.value(),resault)
        print("\n",proj_fldr,"\n",str(self.spinBox_5.value()),"\n",resault)
        item2add= {'Company':self.lineEdit_5.text(),'Report':self.lineEdit_7.text(),'Weld_no':self.lineEdit_3.text(), 'Project':self.lineEdit_6.text(), 'Picture_num':int(LineE6),'Welder':'','image_path':str(resault+"\\0.jpg"),'Result':"1",'Description':str(self.lineEdit_8.text())
        ,'Location':self.lineEdit_14.text()
        ,'Diameter':self.lineEdit_10.text()
        ,'Film_Size':self.lineEdit_11.text()
        ,'Defect_type':self.lineEdit_12.text()
        ,'Date_of_Report':self.lineEdit_13.text()
        ,'Welder':self.lineEdit_9.text()
        ,'accept_reject':self.comboBox_8.currentText()}
        worker1.additemtodb(self,item2add)
        self.statusText_3.setText(str(not_stitched-1)+" images was not stitched")
        self.statusText_3.setStyleSheet("color: red;")
        self.statusText_5.setText(str(not_stitched-1)+" images was not stitched")
        self.statusText_5.setStyleSheet("color: red;")
    '''
    def mouse_print(self,pos0):
        global pos
        global indexItem,indx0,indx
        global ratio
        global ddy
        global x3,y3,h3,w3,h17,w17,x17,y17
        global x2,y2
        global rects,checkbox_
        global active_window,active_tab

        if self.isActiveWindow():
            active_window=True
        else:
            active_window=False
        if self.tabWidget.currentIndex()==2:
            active_tab=True
        else:
            active_tab=False    
        
        lbl_17_pos=[self.label_17.mapToGlobal(QtCore.QPoint(0, 0)).x(),
        self.label_17.mapToGlobal(QtCore.QPoint(0, 0)).y(),
        self.label_17.width(),self.label_17.height()]
        #print("lbl_17_pos:\t",lbl_17_pos)

        
        x17,y17,w17,h17=lbl_17_pos
        x,y=pos0
 
        w3=self.label_17.pixmap().width()
        h3=self.label_17.pixmap().height()
        
        x3=int(x17+((w17-w3)/2))
        y3=y17+int((h17-h3)/2)
        #x2=int(int(x-x17)*indx.shape[1]/x3)
        #y2=int(int(y-y17)*indx.shape[0]/y3)
        
        #x2=int(int(x)*indx.shape[1]/w17)-x17
        #y2=int(int(y)*indx.shape[0]/h17)-y17

        x2=int(((indx.shape[1]/w3))*(x-x3))
        y2=int(((indx.shape[0]/h3))*(y-y3))

        #print (pos)
        #pos="Mouse Pos: "+str(pos)+"  x2:"+str(x2)+"\ty2:"+str(y2)+"\tw17:"+str(w17)+"\th17:"+str(h17)+"\tx17:"+str(x17)+"\ty17:"+str(y17)
        poss="Mouse Pos: "+str(pos)+"\tX2: "+str(x2)+"\tY2: "+str(y2)+"\tw3+x3: "+str(w3+x3)+"\th3-h17: "+str(h17-h3)

        self.label_18.setText(poss)
        
        #print("x:\t{}\ty:\t{}\tx2:\t{}\ty2:\t{}\tx3:\t{}\ty3:\t{}\th3:\t{}\tw3:\t{}\tx17:\t{}\ty17:\t{}\tw17:\t{}\th17:\t{}".format(x,y,x2,y2,x3,y3,h3,w3,x17,y17,w17,h17))
        if self.checkBox.isChecked():   
            checkbox_=True
            rects=my_data.defected_rectangles(film_table_prime)
        else:
            checkbox_=False

        '''#to show the rectangle on the image
        if x2>0 and y2>0 and x<x3+w3 and y<y3+h3:   #only work if mouse is on image
            
            #index_with_rec=cv2.imread(indexItem)                                ######444444444444444444444444444444
            index_with_rec=indx0.copy()
            if self.checkBox.isChecked():                           #showing the defected rectangles
                rects=my_data.defected_rectangles(self.treeView.selectedIndexes()[0].data(Qt.DisplayRole))
                for i,rect in enumerate(rects):
                    xpos,ypos,width__,height__=rect
                    cv2.rectangle(index_with_rec, (xpos-int(width__/2),ypos-int(height__/2)), (xpos+int(width__/2), ypos+int(height__/2)), (0, 0, 255), 2)   
            
            cv2.rectangle(index_with_rec, (x2-int(ddy/2),y2-int(ddy/2)), (x2+int(ddy/2),y2+int(ddy/2)), (0, 255, 0), 2)
            index_with_rec=cv2.cvtColor(index_with_rec,cv2.COLOR_BGR2RGBA)
            QQ=QImage(index_with_rec.data,int(index_with_rec.shape[1]),int(index_with_rec.shape[0]),QImage.Format_RGBA8888)
            self.label_17.setPixmap((QPixmap.fromImage(QQ)).scaled(self.label_17.width(),self.label_17.height(), QtCore.Qt.KeepAspectRatio))
        '''# to show the rectangle on the image
    def show_image_with_rects(self , QQ):

        self.label_17.setPixmap((QPixmap.fromImage(QQ)).scaled(self.label_17.width(),self.label_17.height(), QtCore.Qt.KeepAspectRatio))
        
    
    def show_zoomed_img(self,image):
        global active_window,active_tab
        if active_window and active_tab:
            self.label_19.setPixmap(QPixmap.fromImage(image).scaled(self.label_19.width(),self.label_19.height(), QtCore.Qt.KeepAspectRatio))

    def refresh_serial(self):
        self.portNames.clear()
        self.portNames.addItems([ port.portName() for port in QSerialPortInfo().availablePorts() ])
    def portOpen(self, flag):
        global ser,default_baud,default_port
        ser = serial.Serial()
        if ser.is_open==False:
            
            ser.baudrate = self.comboBox_2.currentText()
            ser.port = self.portNames.currentText()
            try:
                ser.open()
                self.pushButton_2.setStyleSheet("color: green;")
                #self.pushButton_19.setStyleSheet("color: green;")
                #self.pushButton_19.setChecked(True)
                self.pushButton_19.setEnabled(False)
                self.pushButton_20.setEnabled(True)
            except SerialException as e:
                print (e)
                self.statusText.setText('Port Already Open')

        if ser.is_open==True:
            print("Port Opened")
            self.statusText.setText("Port Opened")
            self.pushButton_5.setEnabled(True)
            self.pushButton_6.setEnabled(True)
            self.pushButton_7.setEnabled(True)
            self.pushButton_10.setEnabled(True)
            self.pushButton_22.setEnabled(True)
            #serialcmd="1\n"
            #ser.write(serialcmd.encode())
            #print("serialcmd=\t",serialcmd)
            self.worker2.start()   
        else:
            print("Cannot Open Port")
            self.statusText.setText("Cannot Open Port")
            self.pushButton_5.setEnabled(False)
            self.pushButton_6.setEnabled(False)
            self.pushButton_7.setEnabled(False)
            self.pushButton_10.setEnabled(False)
            self.pushButton_22.setEnabled(False)
            #self.pushButton_14.setEnabled(False)
            self.pushButton_26.setEnabled(False)

    def serial_Slot(self,serial_text):
        global ready
        global LED_midian
        global save_image,save_small_slide
        global proj_fldr
        global resault,spin5

        serial_text=str(serial_text,'utf-8')
        self.statusText.setText(serial_text) 
        if (serial_text=="READY\r\n"):
            ready=True
            #self.pushButton_14.setEnabled(True)
            #self.pushButton_14.setStyleSheet("background-color: green;color: blue;")
            self.pushButton_26.setEnabled(True)
            self.pushButton_26.setStyleSheet("background-color: green;color: blue;")
            self.pushButton_14.setEnabled(True)
            self.pushButton_14.setStyleSheet("background-color: green;color: blue;")
            #self.horizontalSlider_11.setValue(LED_midian)                               #sets led value when ready is recieved
        elif (serial_text=="Done\r\n"):
            global item2add2
            item2add2=[]
            self.pushButton_13.setEnabled(True)
            self.pushButton_13.setText('Stitch')
            self.pushButton_13.setStyleSheet("background-color: green;color: blue;")
            # self.pushButton_18.setEnabled(True)
            # self.pushButton_18.setText('Stitch')
            # self.pushButton_18.setStyleSheet("background-color: green;color: blue;")
            self.pushButton_27.setEnabled(True)
            self.pushButton_27.setText('Stitch')
            self.pushButton_27.setStyleSheet("background-color: green;color: blue;")
            #self.pushButton_14.setEnabled(True)
            #self.pushButton_14.setStyleSheet("background-color: green;color: blue;")
            self.pushButton_26.setEnabled(True)
            self.pushButton_26.setStyleSheet("background-color: green;color: blue;")
            self.pushButton_14.setEnabled(True)
            self.pushButton_14.setStyleSheet("background-color: green;color: blue;")
            sleep(1)
            
            #self.stitch()	        #NO thread

            spin5=self.spinBox_5.value()
            resault=proj_fldr+"\\"+"result"+"\\"+str(self.spinBox_5.value())
            
            item2add2= {'Company':self.lineEdit_5.text(),'Report':self.lineEdit_7.text(),'Weld_no':self.lineEdit_3.text(), 'Project':self.lineEdit_6.text(), 'Picture_num':int(LineE6),'Welder':'','image_path':str(resault+"\\0.jpg"),'Result':"1",'Description':str(self.lineEdit_8.text())
            ,'Location':self.lineEdit_14.text()
            ,'Diameter':self.lineEdit_10.text()
            ,'Film_Size':self.lineEdit_11.text()
            ,'Defect_type':self.lineEdit_12.text()
            ,'Date_of_Report':self.lineEdit_13.text()
            ,'Welder':self.lineEdit_9.text()
            ,'accept_reject':self.comboBox_8.currentText()
            ,'Remark':self.lineEdit_15.text()}
            #worker1.additemtodb(self,item2add)
            #my_data.additem2db(self,item2add)
            #print("**************************","\n",proj_fldr,"\n",str(self.spinBox_5.value()),"\n",resault,"\n","**************************")

            self.worker4.start()    #thread
            ready=False

            self.to_save_or_not()
            
        else:
            ready=False
            #self.pushButton_13.setEnabled(False)
            #self.pushButton_13.setText('Stitch is Disabled')
            self.pushButton_13.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;")
            # self.pushButton_18.setEnabled(False)
            # self.pushButton_18.setText('Stitch is Disabled')
            # self.pushButton_18.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;")
            # self.pushButton_27.setEnabled(False)
            # self.pushButton_27.setText('Stitch is Disabled')
            # self.pushButton_27.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;")
            # self.pushButton_14.setEnabled(False)
            # self.pushButton_14.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;")
            self.pushButton_26.setEnabled(False)
            self.pushButton_26.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;")
            #self.pushButton_14.setEnabled(False)
            self.pushButton_14.setStyleSheet("background-color: qlineargradient(spread:repeat, x1:0.486, y1:0, x2:0.505, y2:1, stop:0.00480769 rgba(170, 0, 0, 255),stop:1 rgba(122, 0, 0, 255));color: red;")
    def portclose(self):
        global LineE6
        self.worker2.portclose()
        
        self.spinBox_6.setValue(LineE6)
        self.pushButton_5.setEnabled(False)
        self.pushButton_6.setEnabled(False)
        self.pushButton_7.setEnabled(False)
        self.pushButton_10.setEnabled(False)
        self.pushButton_22.setEnabled(False)
        self.statusText.setText("Port Closed")   

        self.pushButton_2.setStyleSheet("color: white;")
        #self.pushButton_19.setStyleSheet("color: white;")
        #self.pushButton_20.setChecked(False)
        self.pushButton_20.setEnabled(False)
        self.pushButton_19.setEnabled(True)
    def portsendforward(self):
        global STARTED 
        global save_image,spin5,resault
        spin5=self.spinBox_5.value()
        resault=resault=proj_fldr+"\\"+"result"+"\\"+str(self.spinBox_5.value())
        self.worker2.start_serial_send_forward()
        save_image=True
        STARTED=True
    def portsendbackward(self):
        self.worker2.start_serial_send_backward()
    def setLED(self):
        global LED_value
        LED_value=self.horizontalSlider_11.value()
        self.worker2.start_serial_send_LED()
    def webcam_start(self):
        self.worker1.start()
        self.pushButton.setStyleSheet("color: green;")
        self.pushButton_15.setChecked(True)
    def webcam_start_toggle(self):
        if self.pushButton_15.isChecked():
            self.worker1.start()
        else:
            self.worker1.stop()
    def imageupdateSlot(self,image):
        pic2=image.scaled(self.label.width(),self.label.height(),Qt.KeepAspectRatio)
        self.label.setPixmap(QPixmap.fromImage(pic2))
        #self.label.setPixmap(QPixmap.fromImage(image).scaled(self.label.width(),self.label.height(), QtCore.Qt.KeepAspectRatio))
    def imageupdateSlotcrop(self,image2):
        self.label_20.setScaledContents(False)
        pic2=image2.scaled(self.label_20.width(),self.label_20.height(),Qt.KeepAspectRatio)
        self.label_20.setPixmap(QPixmap.fromImage(pic2))

    def imageupdatehistogram(self,rhist):
        #self.label_21.setScaledContents(False)
        #pic2=image3.scaled(self.label_21.width(),self.label_21.height(),Qt.KeepAspectRatio)
        #self.label_21.setPixmap(QPixmap.fromImage(pic2))
        global webcam_median
        global LED_midian
        webcam_median=np.median(rhist)
        
        x= [0,256]
        y= [np.median(rhist), np.median(rhist)]
        self.graphicsView.plot(x, y, pen=pg.mkPen('r', width=1),clear=True)
        self.graphicsView.plot((rhist), pen=(255,255,255))
        #self.graphicsView.plot([np.median(rhist),np.median(rhist)])
        LED_midian=(webcam_median-510)/(-2)
        lbl_21='Median:\t'+str(np.median(rhist))+"   "+'LED:\t'+str(LED_midian)
        self.label_21.setText(lbl_21)
        
    def cancel_feed(self):
        self.worker1.stop()
        self.pushButton.setStyleSheet("color: white;")
        self.pushButton_15.setChecked(False)

    def initUI(self):
        self.setWindowTitle('Scanner')
        
    ########slider settings###########
    def read_slider1(self,value):
        global HH1
        self.lcdNumber.display(value)
        HH1=value
    def read_slider2(self,value):
        global HH2
        self.lcdNumber_2.display(value)
        HH2=value
    def read_slider3(self,value):
        global HH3
        self.lcdNumber_3.display(value)
        HH3=value
    def read_slider4(self,value):
        global HH4
        self.lcdNumber_4.display(value)
        HH4=value
    def read_slider5(self,value):
        global HH5
        self.lcdNumber_5.display(value)
        HH5=value
    def read_slider6(self,value):
        global HH6
        self.lcdNumber_6.display(value)
        HH6=value        
    def read_slider7(self,value):
        global HH7
        self.lcdNumber_13.display(value)
        HH7=value    
    def read_slider8(self,value):
        global HH8
        self.lcdNumber_14.display(value)
        HH8=value    
    def read_slider9(self,value):
        global HH9
        self.lcdNumber_15.display(value)
        HH9=value    
    def read_slider10(self,value):
        global HH10
        self.lcdNumber_16.display(value)
        HH10=value 
    def read_slider11(self,value):
        global HH11
        self.lcdNumber_7.display(value)
        self.lcdNumber_8.display(value)
        self.verticalSlider.setValue(value)
        HH11=value 
        self.setLED()
    def read_verticalslider(self,value):
        global HH11
        self.lcdNumber_7.display(value)
        self.lcdNumber_8.display(value)
        self.horizontalSlider_11.setValue(value)
        HH11=value 
        self.setLED()
    def read_text2(self,value):
        global LineE2
        LineE2=value
    def read_text3(self,value):
        global LineE3
        LineE3=value
    def read_text1(self,value):
        global LineE1
        LineE1=value
    def read_text4(self,value):
        global LineE4
        LineE4=value    
    def read_text6(self,value):
        global LineE6
        LineE6=value   
    def read_text8(self,value):
        global LineE8
        LineE8=value  
    ########slider settings###########

    def proj_path(self,value):
        global project_path    
        project_path= str(QFileDialog.getExistingDirectory(self, "Select Project Directory"))
        self.lineEdit.setText(project_path)
        self.lineEdit_4.setText(project_path)

        if project_path=="":
            self.statusText_2.setText("Please Choose a Project Directory") 
            self.statusText_4.setText("Please Choose a Project Directory") 
        else:
            self.statusText_2.setText("Directory Selected")  
            self.statusText_4.setText("Directory Selected")  
    def create_proj(self):
        global LE_3
        global LE_4
        global LE_5
        global LE_6
        global LE_7
        LE_3=self.lineEdit_3.text()
        LE_4=self.lineEdit_4.text()
        LE_5=self.lineEdit_5.text()
        LE_6=self.lineEdit_6.text()
        LE_7=self.lineEdit_7.text()


        self.statusText_3.setStyleSheet("color: white;")
        self.statusText_5.setStyleSheet("color: white;")
        global project_path
        global proj_fldr
        global proj_subfolder
        global imgfiles
        proj_fldr=project_path+"\\"+self.lineEdit_5.text()+"\\"+self.lineEdit_6.text()+"\\"+self.lineEdit_7.text()+"\\"+self.lineEdit_2.text()
        proj_subfolder=proj_fldr+"\\"+str(self.spinBox_5.value())

        if not os.path.isdir(proj_fldr):
            os.makedirs(proj_fldr)
            self.statusText_2.setText("Project Folder Created") 
            self.statusText_4.setText("Project Folder Created") 
        if os.path.isdir(proj_fldr) and not os.path.isdir(proj_subfolder):
                os.mkdir(proj_subfolder)
                self.statusText_2.setText("Subfolder Created")  
                self.statusText_4.setText("Subfolder Created")  
        elif os.path.isdir(proj_fldr) and os.path.isdir(proj_subfolder):
            self.statusText_2.setText("Project Folder and Sub Exist")  
            self.statusText_4.setText("Project Folder and Sub Exist")  
        #self.treeView.model = QFileSystemModel()
        #self.treeView.model.setRootPath(r'O:\Project 2\Welding Film Scanner\App\GUI V0.11')
        self.treeView.model =QStandardItemModel()
        #self.treeView.setModel(self.treeView.model)        
    def take_snapshot(self,image):
        global svd_image
        svd_image=image
        #self.label_8.setPixmap(QPixmap.fromImage(QImage(svd_image.data,int(svd_image.shape[1]),int(svd_image.shape[0]),QImage.Format_RGBA8888)))
    def save_snapshot(self,image):
        global svd_image
        global save_image
        global image_no
        global LineE6
        svd_image=image
        save_image=True
        image_no=image_no+1
        #self.statusText_2.setText(str(svd_image.shape[1])) 
        #self.statusText_2.setText(str(image_no))
        self.spinBox_6.setValue(self.spinBox_6.value()+1)
    def save_small_slide_snapshot(self,image):
        global save_small_slide,LineE8
        global STARTED
        self.worker2.start_serial_send_sforward()
        save_small_slide=True
        STARTED=True
        self.spinBox_8.setValue(self.spinBox_8.value()+1)


    def _on_closeEditor(self,editor):
        p = editor.pos()
        #print("P:\t",p)
        index = self.treeView.indexAt(p)
        if not index.isValid():
            return
        it = self.treeView.model.itemFromIndex(index)
        for i,ix in enumerate(self.treeView.selectedIndexes()):
            if i==0:
                id=ix.data(Qt.DisplayRole)                                                      #gets the item id to be edited
            if i==8 and ix.data(Qt.DisplayRole)=='1':   
                print("i:\t",index.column(),"id:\t",id,"text:\t",it.text())

        item2editt= [index.column(),it.text()]
        my_data.edititem2db_by_col_no(self,item2editt,int(id))  
    def on_lable_17_clicked(self,event):
        global x2,y2,ddy,flagg
        flagg=False        
        film_table_prime=self.treeView.selectedIndexes()[0].data(Qt.DisplayRole)
        
        if event.button() == QtCore.Qt.LeftButton and self.checkBox.isChecked():
            item2add= {'film_table_prime':film_table_prime,'xpos':x2,'ypos':y2,'width':ddy,'height':ddy}
            my_data.additem2_defect_db(self,item2add)
        if event.button() == QtCore.Qt.RightButton and self.checkBox.isChecked():
            item2remove={}
            my_data.remove_defected_rectangles(film_table_prime,x2,y2,ddy,ddy)


    def on_treeview_clicked(self,index):
        global x3,y3,w3,h3,h17,w17
        global film_table_prime,flagg
        flagg=False
        film_table_prime=self.treeView.selectedIndexes()[0].data(Qt.DisplayRole)
        #indexItem = self.treeView.model.index(index.row(), 0, index.parent())
        #file_n=self.treeView.model.fileName(indexItem)
        #file_p = self.treeView.model.filePath(indexItem)
        '''
        for ix in self.treeView.selectedIndexes():
            text = ix.data(Qt.DisplayRole) # or ix.data()
            print(text)
        '''
        lbl_17_pos=[self.label_17.mapToGlobal(QtCore.QPoint(0, 0)).x(),
        self.label_17.mapToGlobal(QtCore.QPoint(0, 0)).y(),
        self.label_17.width(),self.label_17.height()]
        
        if not self.worker3.isRunning():
            self.worker3.start()
        global indx,indx0
        global indexItem
        global ratio
        
        indexItem=self.treeView.selectedIndexes()[7].data(Qt.DisplayRole)
        
        #print(self.treeView.model.index(index.row(),index.column())[0])
        indx=cv2.imread(indexItem)
        indx0=indx.copy()
        #self.label_8.setText(str(indexItem)) 
        self.label_43.setText(self.treeView.selectedIndexes()[1].data(Qt.DisplayRole))#company
        self.label_30.setText(self.treeView.selectedIndexes()[2].data(Qt.DisplayRole))#project  
        self.label_41.setText(self.treeView.selectedIndexes()[3].data(Qt.DisplayRole))#report  
        self.label_32.setText(self.treeView.selectedIndexes()[4].data(Qt.DisplayRole))#welderID
        self.label_39.setText(self.treeView.selectedIndexes()[5].data(Qt.DisplayRole))#weld no.
        self.label_34.setText(self.treeView.selectedIndexes()[11].data(Qt.DisplayRole))#Location
        self.label_37.setText(self.treeView.selectedIndexes()[12].data(Qt.DisplayRole))#Diameter
        self.label_36.setText(self.treeView.selectedIndexes()[13].data(Qt.DisplayRole))#Film size
        self.label_46.setText(self.treeView.selectedIndexes()[14].data(Qt.DisplayRole))#Defect Type
        self.label_48.setText(self.treeView.selectedIndexes()[15].data(Qt.DisplayRole))#Date of report

        #self.label_27.setText(self.treeView.selectedIndexes()[7].data(Qt.DisplayRole))#Address
        path = (self.treeView.selectedIndexes()[7].data(Qt.DisplayRole))
        url = bytearray(QUrl.fromLocalFile(path).toEncoded()).decode()
        text = "<a href={}>Img link</a>".format(url)
        self.label_27.setText(text)
        self.label_27.setTextFormat(Qt.RichText)
        self.label_27.setOpenExternalLinks(True)


        #self.label_24.setText(self.treeView.selectedIndexes()[8].data(Qt.DisplayRole))#Add report link
        if (self.treeView.selectedIndexes()[16].data(Qt.DisplayRole))!='None':
            path = (self.treeView.selectedIndexes()[16].data(Qt.DisplayRole))
            url = bytearray(QUrl.fromLocalFile(path).toEncoded()).decode()
            text = "<a href={}>Report link</a>".format(url)
            self.label_24.setText(text)
            self.label_24.setTextFormat(Qt.RichText)
            self.label_24.setOpenExternalLinks(True)
        else:   
            self.label_24.setText(self.treeView.selectedIndexes()[16].data(Qt.DisplayRole))#Add report link


        self.label_25.setText(self.treeView.selectedIndexes()[9].data(Qt.DisplayRole))#accept_reject
        self.label_26.setText(self.treeView.selectedIndexes()[10].data(Qt.DisplayRole))#description
        self.label_17.setScaledContents(False)
        

        try: 
            w,h,_=indx.shape
            ratio=w/h
            '''
            rects=my_data.defected_rectangles(self.treeView.selectedIndexes()[0].data(Qt.DisplayRole))
            for i,rect in enumerate(rects):
                xpos,ypos,width__,height__=rect
                cv2.rectangle(indx, (xpos-int(width__/2),ypos-int(height__/2)), (xpos+int(width__/2), ypos+int(height__/2)), (0, 0, 255), 2)  
            '''    
            if round(ratio>0):
                ratio=round(ratio)
                scale=self.label_17.width()/w
                scale=int(scale)
                ####self.label_17.setPixmap(QPixmap(indexItem).scaled(self.label_17.width()*ratio,self.label_17.width()*ratio, QtCore.Qt.KeepAspectRatio))

                indx=cv2.cvtColor(indx,cv2.COLOR_BGR2RGBA)
                QQ=QImage(indx.data,int(indx.shape[1]),int(indx.shape[0]),QImage.Format_RGBA8888)
                self.label_17.setPixmap((QPixmap.fromImage(QQ)).scaled(self.label_17.width(),self.label_17.height(), QtCore.Qt.KeepAspectRatio))
                #self.label_17.setPixmap(QPixmap(indexItem).scaled(self.label_17.width(),self.label_17.height(), QtCore.Qt.KeepAspectRatio))
            
                x17,y17,w17,h17=lbl_17_pos
                w3=self.label_17.pixmap().width()
                h3=self.label_17.pixmap().height()
                x3=int(x17+((w17-w3)/2))
                y3=y17+int((h17-h3)/2)
            else:
                self.label_17.setPixmap(QPixmap(indexItem))
                x17,y17,w17,h17=lbl_17_pos
                w3=self.label_17.pixmap().width()
                h3=self.label_17.pixmap().height()
                x3=int(x17+((w17-w3)/2))
                y3=y17+int((h17-h3)/2)
        except:
            pass
        
 
        
    def stop_view(self):
       self.worker3.stop()    
        

    def read_db(self):
        if self.radioButton.isChecked():
            show='all'
        if self.radioButton_2.isChecked():
            show='result'
        my_data.show_db(self,show)
        
        print()
        self.comboBox.clear()
        self.comboBox.addItem("")
        self.comboBox_3.clear()
        self.comboBox_3.addItem("")
        self.comboBox_4.clear()
        self.comboBox_4.addItem("")
        self.comboBox_5.clear()
        self.comboBox_5.addItem("")
        self.comboBox_6.clear()
        self.comboBox_6.addItem("")
        self.comboBox_7.clear()
        self.comboBox_7.addItem("")
        self.comboBox.addItems(my_data.query_return_single(self,"Company"))




class worker1(QThread):
    imageupdate=pyqtSignal(QImage)
    imageupdate2=pyqtSignal(QImage)
    imageupdate3=pyqtSignal(np.ndarray)
    snap=pyqtSignal(np.ndarray)

    @QtCore.pyqtSlot()
    def run(self):
        self.threadActive=True
        global capture
        global HH1,HH2,HH3,HH4,HH5,HH6,HH7,HH8,HH9,LineE1,LineE2,LineE3,LineE4,LineE6,LineE8
        global save_image,save_small_slide
        global image_no
        capture=cv2.VideoCapture(0+cv2.CAP_DSHOW)
        
        #set camera settings#
        capture.set(cv2.CAP_PROP_FRAME_WIDTH,1900)
        capture.set(cv2.CAP_PROP_FRAME_HEIGHT,1080)
        capture.set(cv2.CAP_PROP_FPS,30)
        capture.set(cv2.CAP_PROP_BRIGHTNESS,HH1)
        capture.set(cv2.CAP_PROP_CONTRAST,HH2)
        capture.set(cv2.CAP_PROP_SATURATION,HH3)
        capture.set(cv2.CAP_PROP_HUE,HH4)
        capture.set(cv2.CAP_PROP_GAIN,HH5)
        capture.set(cv2.CAP_PROP_EXPOSURE,HH6)
        capture.set(cv2.CAP_PROP_AUTO_WB,HH7)
        capture.set(cv2.CAP_PROP_AUTOFOCUS,HH8)
        capture.set(cv2.CAP_PROP_FOCUS,HH9)
        capture.set(cv2.CAP_PROP_SETTINGS, 1)   #open camera settings
        capture.set(cv2.CAP_PROP_MODE,-1)
        capture.set(cv2.CAP_PROP_WHITE_BALANCE_BLUE_U, HH10)  
        capture.set(cv2.CAP_PROP_BACKLIGHT,0)

        print("FRAME_WIDTH:\t",capture.get(cv2.CAP_PROP_FRAME_WIDTH))
        print("FRAME_HEUGHT:\t",capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        print("PROP_FPS:\t",capture.get(cv2.CAP_PROP_FPS))
        print("PROP_BRIGHTNESS:\t",capture.get(cv2.CAP_PROP_BRIGHTNESS))
        print("PROP_CONTRAST:\t",capture.get(cv2.CAP_PROP_CONTRAST))
        print("PROP_SATURATION:\t",capture.get(cv2.CAP_PROP_SATURATION))
        print("PROP_HUE:\t",capture.get(cv2.CAP_PROP_HUE))
        print("PROP_GAIN:\t",capture.get(cv2.CAP_PROP_GAIN))
        print("PROP_EXPOSURE:\t",capture.get(cv2.CAP_PROP_EXPOSURE))
        print("PROP_AUTO_WB:\t",capture.get(cv2.CAP_PROP_AUTO_WB))
        print("PROP_WHITE_BALANCE:\t",cv2.CAP_PROP_WHITE_BALANCE_BLUE_U)
        print("PROP_AUTOFOCUS:\t",capture.get(cv2.CAP_PROP_AUTOFOCUS))
        print("PROP_FOCUS:\t",capture.get(cv2.CAP_PROP_FOCUS))
        print("PROP_MODE:\t",capture.get(cv2.CAP_PROP_MODE))
        #capture.set(15, -5)
        

        ''' 0. CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.
                        1. CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
                        2. CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file
                        3. CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
                        4. CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
                        5. CV_CAP_PROP_FPS Frame rate.
                        6. CV_CAP_PROP_FOURCC 4-character code of codec.
                        7. CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.
                        8. CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
                        9. CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
                        10. CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
                        11. CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
                        12. CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
                        13. CV_CAP_PROP_HUE Hue of the image (only for cameras).
                        14. CV_CAP_PROP_GAIN Gain of the image (only for cameras).
                        15. CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
                        16. CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
                        17. CV_CAP_PROP_WHITE_BALANCE Currently unsupported
                        18. CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)'''
        while self.threadActive:
            
            if capture.get(10)!=HH1 :
                capture.set(10,HH1)
            if capture.get(11)!=HH2 :
                capture.set(11,HH2)
            if capture.get(12)!=HH3 :
                capture.set(12,HH3)
            if capture.get(13)!=HH4 :
                capture.set(13,HH4)
            if capture.get(14)!=HH5 :
                capture.set(14,HH5)
            if capture.get(15)!=HH6 :
                capture.set(15,HH6)
            if capture.get(cv2.CAP_PROP_AUTO_WB)!=HH7 :
                capture.set(cv2.CAP_PROP_AUTO_WB,HH7)
            if capture.get(cv2.CAP_PROP_AUTOFOCUS)!=HH8 :
                capture.set(cv2.CAP_PROP_AUTOFOCUS,HH8)
            if capture.get(cv2.CAP_PROP_FOCUS)!=HH9 :
                capture.set(cv2.CAP_PROP_FOCUS,HH9)
            if capture.get(cv2.CAP_PROP_WHITE_BALANCE_BLUE_U)!=HH10 :
                capture.set(cv2.CAP_PROP_WHITE_BALANCE_BLUE_U,HH10)
            
            ret,frame=capture.read()
            if ret:
                image=cv2.cvtColor(frame,cv2.COLOR_BGR2RGBA )#cv2.COLOR_BGR2RGB)
                convert2qtforma=QImage(image.data,image.shape[1],image.shape[0],QImage.Format_RGBA8888)
                pic=convert2qtforma.scaled(1600,896,Qt.KeepAspectRatio)
                
                yy1=int(LineE1)
                yy2=int(LineE3)
                xx1=int(LineE2)
                xx2=int(LineE4)
                
                ####################
                '''
                print("FRAME_WIDTH:\t",capture.get(cv2.CAP_PROP_FRAME_WIDTH),
                "FRAME_HEUGHT:\t",capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
                ,"FPS:\t",capture.get(cv2.CAP_PROP_FPS)
                ,"BRIGHTNESS:\t",capture.get(cv2.CAP_PROP_BRIGHTNESS)
                ,"CONTRAST:\t",capture.get(cv2.CAP_PROP_CONTRAST)
                ,"SATURATION:\t",capture.get(cv2.CAP_PROP_SATURATION)
                ,"HUE:\t",capture.get(cv2.CAP_PROP_HUE)
                ,"GAIN:\t",capture.get(cv2.CAP_PROP_GAIN)
                ,"EXPOSURE:\t",capture.get(cv2.CAP_PROP_EXPOSURE)
                ,"AUTO_WB:\t",capture.get(cv2.CAP_PROP_AUTO_WB)
                ,"WB_blue:\t",capture.get(cv2.CAP_PROP_WHITE_BALANCE_BLUE_U)
                ,"AUTOFOCUS:\t",capture.get(cv2.CAP_PROP_AUTOFOCUS)
                ,"FOCUS:\t",capture.get(cv2.CAP_PROP_FOCUS)
                ,"MODE:\t",capture.get(cv2.CAP_PROP_MODE)
                ,"LED:\t",capture.get(cv2.CAP_PROP_BACKLIGHT))#
                ############################        
                '''


                '''
                if x2-x1<1 or  y2-y1<1:
                    x2=x1+50
                    y2=y1+50    
                '''    
                #delay(1)
                #image2=np.zeros(image)
                #cv2.rectangle(image, (x1,y1), (x1+x2, y1+y2), (0, 255, 0), 2)
                
                
                image2=image[yy1:yy1+yy2, xx1:xx1+xx2].copy()
                #convert2qtforma3=QImage(image2.data,int(image2.shape[1]),int(image2.shape[0]),QImage.Format_RGBA8888)
                self.snap.emit(image2)
                if save_image==True:
                    global proj_subfolder
                    global item2add,LineE8
                    #print("save image=TRUE")
                    save_image=False
                    img_name=proj_subfolder+"\\"+str(LineE6*100)+".jpg"
                    cv2.imwrite(img_name, cv2.cvtColor(image2,cv2.COLOR_RGBA2BGR ))#cv2.COLOR_BGR2RGB))
                    #to_hide="attrib +s +h "+'"'+r'%s' % img_name+'"'
                    to_hide=r'%s' % img_name            #hides single images
                    self.hide_file(to_hide)
                    #print("\n\n\nto_hide=\t",(to_hide))
                    item2add= {'Company':LE_5,'Project':LE_6,'Weld_no':LE_3, 'Report':LE_7, 'Picture_num':int(LineE6),'Welder':'','image_path':str(img_name),'Result':"0"}
                    worker1.additemtodb(self,item2add)
                    LineE6=LineE6+1
                elif save_small_slide==True:
                    #print("save image=TRUE")
                    save_small_slide=False
                    small_slide_img_name=proj_subfolder+"\\"+str(LineE8*100)+".jpg"
                    cv2.imwrite(small_slide_img_name, cv2.cvtColor(image2,cv2.COLOR_RGBA2BGR ))#cv2.COLOR_BGR2RGB))
                    #to_hide="attrib +s +h "+'"'+r'%s' % img_name+'"'
                    to_hide=r'%s' % small_slide_img_name            #hides single images
                    self.hide_file(to_hide)
                    #print("\n\n\nto_hide=\t",(to_hide))
                    item2add= {'Company':LE_5,'Project':LE_6,'Weld_no':LE_3, 'Report':LE_7, 'Picture_num':int(LineE8),'Welder':'','image_path':str(small_slide_img_name),'Result':"0"}
                    worker1.additemtodb(self,item2add)
                    LineE8=LineE8+1

                image=cv2.rectangle(image, (xx1, yy1), (xx2+xx1, yy2+yy1), (180,0,0,255), 3)
                width_ = int(image.shape[1])
                height_ = int(image.shape[0])
                #if (height_ > width_): dif = height_
                #else:     dif = width_

                #mask = np.zeros((dif, dif,4), dtype=image2.dtype)
                #mask[y1:y1+y2, x1:x1+x2] = image2[:height_, :width_]

                dim = (width_, height_)
                
                # resize image
                resized = cv2.resize(image2, dim, interpolation = cv2.INTER_AREA)
                out1=np.concatenate((image, resized), axis=1)
                #self.imageupdate.emit(pic)
                convert2qtforma2=QImage(out1.data,int(out1.shape[1]),int(out1.shape[0]),QImage.Format_RGBA8888)
                pic2=convert2qtforma2.scaled(849,336,Qt.KeepAspectRatio)
                self.imageupdate.emit(pic2)

                convert2qtforma4=QImage(resized.data,int(resized.shape[1]),int(resized.shape[0]),QImage.Format_RGBA8888)
                pic3=convert2qtforma4.scaled(849,336,Qt.KeepAspectRatio)
                self.imageupdate2.emit(pic3)

                resized=cv2.cvtColor(resized,cv2.COLOR_BGR2GRAY )
                hist = cv2.calcHist([resized],[0],None,[256],[0,256])
                rhist=np.ravel(hist[1:])
                #hist=cv2.cvtColor(hist,cv2.COLOR_BGR2RGBA )
                #convert2qtforma5=QImage(hist.data,int(hist.shape[1]),int(hist.shape[0]),QImage.Format_RGBA8888)
                #pic4=convert2qtforma5.scaled(849,336,Qt.KeepAspectRatio)
                self.imageupdate3.emit(rhist)
                sleep(0.01)
    def hide_file(self,path):
        
        """
        Set the hidden attribute on a file or directory.

        From http://stackoverflow.com/questions/19622133/

        `path` must be text.
        """

        __import__('ctypes.wintypes')
        SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
        #SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
        #SetFileAttributes.restype = ctypes.wintypes.BOOL

        ## Define constants for Windows file attributes
        FILE_ATTRIBUTE_READONLY = 0x01
        FILE_ATTRIBUTE_HIDDEN = 0x02
        FILE_ATTRIBUTE_SYSTEM = 0x04
        FILE_ATTRIBUTE_DIRECTORY = 0x10
        FILE_ATTRIBUTE_ARCHIVE = 0x20
        FILE_ATTRIBUTE_NORMAL = 0x80
        FILE_ATTRIBUTE_TEMPORARY = 0x0100


        ret = SetFileAttributes(path, FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN )
        # ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
        if not ret:
            raise ctypes.WinError() 

    def additemtodb(self,item2add):
        my_data.additem2db(self,item2add)
    
    @QtCore.pyqtSlot()
    def stop(self):
        global capture
        self.threadActive=False
        #self.quit()
        capture.release()

    @QtCore.pyqtSlot()
    def take_snap(self):
        pass
        #os.mkdir(r'O:\Project 2\Welding Film Scanner\App\GUI V0.7\sss')

class worker4(QThread):
    set_text=pyqtSignal(str)
    resault_path=pyqtSignal(str)
    global resault,spin5,proj_fldr
    
    @QtCore.pyqtSlot()
    def run(self):
        i=0
        global spin5
        global preview_img_path
        self.threadActive=True
        while(self.threadActive):
            not_stitched=stitchWithFeature(proj_fldr,spin5,resault)
            self.set_text.emit(str(not_stitched))
            preview_img_path=resault+"\\0.jpg"
            self.resault_path.emit(resault+"\\0.jpg")
            self.threadActive=False
            print("Stitched")
    @QtCore.pyqtSlot()
    def stop(self):
         self.threadActive=False
class worker2(QThread):
        serial_read=pyqtSignal(bytes)
        global LED_value
        global STARTED
        
        @QtCore.pyqtSlot()
        def run(self):
            self.threadActive=True
            global ser            
            while(self.threadActive):
                global save_image,save_small_slide
                global scanner_steps
                y=ser.readline()
                print('read:\t',str(y,'utf-8'))
                self.serial_read.emit(y)
                if str(y,'utf-8')=="OK\r\n":
                    #take picture here
                    sleep(1)
                    save_image=True
                    
                    serialcmd="Forward\n"#+","+str(scanner_steps)+"\n"
                    ser.write(serialcmd.encode())
                    print("SAVE IMAGE:\t",save_image)
                    #print("send:\t",serialcmd)
                elif str(y,'utf-8')=="Done\r\n":
                    #ser.close()
                    
                    save_image=True
                    #ser.open()
                    str_="Finished"
                    print(str_)
                elif str(y,'utf-8')=="sOK\r\n":
                    #take picture here
                    sleep(1)
                    save_small_slide=True
                    
                    #serialcmd="Forward\n"#+","+str(scanner_steps)+"\n"
                    #ser.write(serialcmd.encode())
                    print("SAVE IMAGE:\t",save_image)
                    #print("send:\t",serialcmd)

                else:
                    print("Cannot writeggg:\t",y)

                '''
                #on receive send next command#
                if ser.is_open==True:
                    serialcmd="Forward\n"
                    ser.write(serialcmd.encode())
                    print("send:\t",serialcmd)
                else:
                    print("Cannot write")
                    #on receive send next command#
                '''
            
            
        @QtCore.pyqtSlot()
        def start_serial_send_forward(self):
            global ser
            global STARTED
            
            if ser.is_open==True:
                serialcmd="Forward\n"#+","+str(scanner_steps)+"\n"
                ser.write(serialcmd.encode())
                print("serialcmd:\t",serialcmd)
                
            else:
                print("Cannot Write Forward")

        def start_serial_send_sforward(self):
            global ser
            global STARTED
            global scanner_steps
            if ser.is_open==True:
                serialcmd="sForward"+","+str(scanner_steps)+"\n"
                ser.write(serialcmd.encode())
                print("serialcmd:\t",serialcmd)
                
            else:
                print("Cannot Write sForward")       

        def start_serial_send_sDone(self):
            global ser
            global STARTED
            global scanner_steps
            if ser.is_open==True:
                serialcmd="sDone\n"
                ser.write(serialcmd.encode())
                print("serialcmd:\t",serialcmd)
                
            else:
                print("Cannot Write sDone")

        @QtCore.pyqtSlot()
        def start_serial_send_backward(self):
            global ser
            if ser.is_open==True:
                serialcmd="Backward\n"
                ser.write(serialcmd.encode())
                print("serialcmd:\t",serialcmd)
            else:
                print("Cannot Write Backward")


        @QtCore.pyqtSlot()
        def start_serial_send_LED(self):
            global ser
            global LED_value
            if ser.is_open==True:
                serialcmd="LED"+","+str(LED_value)+'\n'
                ser.write(serialcmd.encode())
                print("serialcmd:\t",serialcmd)
            else:
                print("Cannot Write LED Value")

        @QtCore.pyqtSlot()
        def portclose(self):
            global ser
            self.threadActive=False
            if ser.is_open==True:
                
                ser.close()
                str_="Port Closed"
                print(str_)
                #self.serial_read.emit(str.encode(str_))
                
            else:
                str_="Cannot Close Port"
                print(str_)
                self.serial_read.emit(str.encode(str_))


class worker3(QThread):
    mouse_pos=pyqtSignal(list)
    zoomed_img=pyqtSignal(QImage)
    image_with_rects=pyqtSignal(QImage)
    global lbl_17_pos,lbl_19_pos,h17,w17,y3,x3,h3,w3
    @QtCore.pyqtSlot()
    def run(self):
        
        global ddy
        global indx
        ddy=100
        global x2,y2,x17,y17,w17,h17,y3,x3
        x17,y17,w17,h17=lbl_17_pos
        x19,w19,y19,h19=lbl_19_pos
        def on_move(x, y):
            global pos
            global indx,indx0
            global indexItem
            global x3,y3,w3,h3,h17,w17,x2,y2,y17,x17
            global rects,checkbox_,flagg
            global mouse_cursor
            global active_window,active_tab,ttt
            #print(self.treeView.model.index(index.row(),index.column())[0])
            #indx=cv2.imread(indexItem)                                          ######444444444444444444444444444444
            
            if (time()-ttt)>0.1:                                #works only after 0.1 sec = zoomed image refresh rate
                #print("check:\t",time()-ttt)
                ttt=time()


                #print ("Mouse moved to ({0}, {1})".format(x, y))
                pos=[x,y]
                self.mouse_pos.emit(pos)

                #x2=int(int(x-x17)*indx.shape[1]/w17)
                #y2=int(int(y-y17)*indx.shape[0]/h17)

                #x2=int(int(x)*indx.shape[1]/w17)-x17
                #y2=int(int(y)*indx.shape[0]/h17)-y17

                x2=int(((indx.shape[1]/w3))*(x-x3))
                y2=int(((indx.shape[0]/h3))*(y-y3))#+int(((h17-h3)/2)*(indx.shape[0]/h3))
                x_r=(indx.shape[1]/w3)
                y_r=(indx.shape[0]/h3)
                #y2=(indx.shape[0]/h3)
                #print("Y:\t",y,"    Y2:\t",y2,"     Y3:\t",y3,"    Y17:\t",y17,"    h3:\t",h3,"    h17:\t",h17,"    h17-h3:\t",h17-h3,"     (h17-h3)/2:\t",(h17-h3)/2,"    TEST1:\t",int((h17-h3)/2))


                if x2>0 and y2>0 and x<x3+w3 and y<y3+h3 and active_window and active_tab:   #only work if mouse is on image  
                #if True:    
                    #cursor_scaled_pix = mouse_cursor.scaled(QSize((int((ddy/2)/(1366/w3))), (int((ddy/2)/(1366/w3)))), Qt.KeepAspectRatio)
                    cursor_scaled_pix = mouse_cursor.scaled(QSize((int((ddy/2))), (int((ddy/2)))), Qt.KeepAspectRatio)
                    cursor = QCursor(cursor_scaled_pix, -x, -y)
                    QApplication.setOverrideCursor(cursor)
                    #print("DDY:\t",ddy)

                    
                    rect = QRect(x2-int(ddy/2), y2-int(ddy/2), ddy, ddy)
                    rect2=[x2-int(ddy/2), y2-int(ddy/2), ddy, ddy]
                    indx2=cv2.cvtColor(indx,cv2.COLOR_BGR2RGBA)
                    convert2qtforma3=QImage(indx2.data,int(indx2.shape[1]),int(indx2.shape[0]),QImage.Format_RGBA8888)
                    convert2qtforma3 = convert2qtforma3.copy(rect)
                    #pic2=convert2qtforma3.scaled(100,100,Qt.KeepAspectRatio)    #rezised for showing
                    #self.zoomed_img.emit(pic2)                                  #show the resize
                    self.zoomed_img.emit(convert2qtforma3)                     #show the normal image
                    


                    index_with_rec=indx0.copy()
                    if checkbox_ == True and flagg==False:                           #showing the defected rectangles
                        for i,rect in enumerate(rects):
                            xpos,ypos,width__,height__=rect
                            cv2.rectangle(index_with_rec, (xpos-int(width__/2),ypos-int(height__/2)), (xpos+int(width__/2), ypos+int(height__/2)), (0, 0, 255), 2)                     
                        index_with_rec=cv2.cvtColor(index_with_rec,cv2.COLOR_BGR2RGBA)
                        QQ=QImage(index_with_rec.data,int(index_with_rec.shape[1]),int(index_with_rec.shape[0]),QImage.Format_RGBA8888)
                        pic3=QQ.scaled(720,680,Qt.KeepAspectRatio)
                        self.image_with_rects.emit(pic3) 
                        flagg=True

                    '''
                    cv2.rectangle(index_with_rec, (x2-int(ddy/2),y2-int(ddy/2)), (x2+int(ddy/2),y2+int(ddy/2)), (0, 255, 0), 2)
                    index_with_rec=cv2.cvtColor(index_with_rec,cv2.COLOR_BGR2RGBA)
                    QQ=QImage(index_with_rec.data,int(index_with_rec.shape[1]),int(index_with_rec.shape[0]),QImage.Format_RGBA8888)
                    pic3=QQ.scaled(720,680,Qt.KeepAspectRatio)
                    self.image_with_rects.emit(pic3) 
                    '''
                    #sleep(0.03)
                    
                else:
                    QApplication.setOverrideCursor(QCursor(QtCore.Qt.ArrowCursor))
                    #QApplication.restoreOverrideCursor()

            



        def on_click(x, y, button, pressed):
            global indx
            global x2,y2,h3,w3,h17,w17
            global x3,y3,w3,h3,h17,w17,x2,y2,y17,x17
            global indx0
            global flagg
            if pressed:
                #print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))  #print mouse operations
                if x2>0 and y2>0 and x<x3+w3 and y<y3+h3:
                    # QApplication.setOverrideCursor(QCursor(QtCore.Qt.ArrowCursor))
                    # QApplication.restoreOverrideCursor()
                    flagg==False

                
        def on_scroll(x, y, dx, dy):
            global indx
            global ddy
            if x2>0 and y2>0 and x<x3+w3 and y<y3+h3 and active_tab and active_window:
                ddy=ddy+5*dy           #scrol steps 
                if ddy<20:
                    ddy=20
                elif ddy>400:
                    ddy=400
                
            else:
                QApplication.setOverrideCursor(QCursor(QtCore.Qt.ArrowCursor))
                QApplication.restoreOverrideCursor()
            '''
            x2=int(int(x-x17)*indx.shape[1]/w17)
            y2=int(int(y-y17)*indx.shape[0]/h17)
            print("x2",x2,"y2",y2)

            if x2-ddy<0:
                x2=ddy+x2
            if y2-ddy<0:
                y2=ddy+y2
            if x2+ddy>indx.shape[1]:
                x2=indx.shape[1]
            if y2+ddy>indx.shape[0]:
                y2=indx.shape[0]    
            indx2=indx[y2-ddy:y2+ddy, x2-ddy:x2+ddy].copy()
            indx2=cv2.cvtColor(indx2,cv2.COLOR_BGR2RGBA)
            convert2qtforma3=QImage(indx2.data,int(indx2.shape[1]),int(indx2.shape[0]),QImage.Format_RGBA8888)
            pic2=convert2qtforma3.scaled(900,900,Qt.KeepAspectRatio)
            self.zoomed_img.emit(pic2)
            '''



            #print ('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))

        #with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
        #    listener.join()
        global listener
        listener = mouse.Listener(on_move=on_move,on_click=on_click,on_scroll=on_scroll)
        listener.start()

    @QtCore.pyqtSlot()
    def stop(self):
        listener.stop()

class worker5(QThread):
    prev_mouse_pos=pyqtSignal(list)
    clk_mouse_pos=pyqtSignal(list)
    @QtCore.pyqtSlot()
    def run(self):
        def on_move(x, y):
            global prev_mouse_pos,t_
            if (time()-t_)>0.05:                                #works only after 0.1 sec = zoomed image refresh rate
                t_=time()
                prev_mouse_pos=[x,y]
                #print(prev_mouse_pos)
                self.prev_mouse_pos.emit(prev_mouse_pos)
        def on_click(x, y, button, pressed):
            global sub_win_active
            if pressed and sub_win_active==True:
                #print ('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))  #print mouse operations
                pos=[x,y]
                self.clk_mouse_pos.emit(pos)
        global listener2
        listener2 = mouse.Listener(on_move=on_move,on_click=on_click)
        listener2.start()      
    def stop(self):
        listener2.stop()
app = QtWidgets.QApplication(sys.argv)

#theme
#file = QFile("Adap/Adap.qss")          #theme1
#file = QFile("Adap//Diff.qss")         #theme2
file = QFile("Adap//Comb.qss")          #theme3
file.open(QFile.ReadOnly | QFile.Text)
stream = QTextStream(file)
app.setStyleSheet(stream.readAll())
#theme

sys.stdout = open('out.log', 'w')
# window = MainWindow()
# window.show()
# app.exec_()

window_licence=licenceWindow()
#window_licence.show()
app.exec_()
sys.stdout.close()

'''
page = requests.get('http://atron.pythonanywhere.com/scanner',auth = HTTPBasicAuth('mamal_asimo', '1271290391'))
tree = html.fromstring(page.content)
treetxt=tree.text
if treetxt=='licence is valid':
    print('licence is valid')
    license=True
else:
    print('invalid licence')
    license=False
'''




# else:
#     e_app = QtWidgets.QApplication([])
#     error_dialog = QtWidgets.QErrorMessage()
#     error_dialog.showMessage('Your licence is not valid')
#     e_app.exec_()



if capture==[]:
    sys.exit()
else:
    sys.exit(capture.release())