Esempio n. 1
0
 def __init__(self):
     super().__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.setWindowFlag(QtCore.Qt.WindowStaysOnTopHint)
     self.setWindowIcon(QtGui.QIcon('/tom.png'))
     # buttons
     self.ui.btnStart.clicked.connect(self.dispatcher)
     self.ui.btnStop.clicked.connect(self.stop_everything)
     self.ui.editButton.clicked.connect(self.edit_settings)
     self.ui.applyButton.clicked.connect(self.apply_settings)
     # settings
     with open('profiles.json', 'w') as profiles:
         try:
             self.settings = json.loads(profiles.read())
         except IOError:
             self.settings = {
                 "Session": "09:00:00",
                 "Work": "00:01:00",
                 "Rest": "00:15:00"
             }
             json.dump(self.settings, profiles)
     self.time_format = "%H:%M:%S"
     self.settings_refresh()
     # children
     self.rest_window = RestWindow(self.rest_delta.seconds)
     self.rest_window.rest_window_closed.connect(self.work)
     self.work_thread = WorkThread(self.work_delta.seconds)
     self.work_thread.update_timers_main.connect(self.work_timer)
     self.work_thread.done.connect(self.show_rest_window)
     self.session_thread = SessionThread(self.session_delta.seconds)
     self.session_thread.timer.connect(self.session_timer)
Esempio n. 2
0
    def __init__(self):
        # init config
        self.config = RawConfigParser()
        self.config.read_file(codecs.open('config.ini', encoding='utf8'))

        logger.info('Configuration loaded')
        # init database
        self.session = Session()

        # init Qt windows
        self.app = QApplication(sys.argv)

        self.window = QMainWindow()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.window)

        self.update_mpc_plugin_list()

        self.ui.mpc_title_frame_title.setText(
            self.config['options']['project_name'])
        self.window.setWindowTitle(self.config['options']['project_name'])
        self.ui.mpc_btn_import.clicked.connect(self.import_plugin)
        self.ui.mpc_plugins_list.itemClicked.connect(self.load_plugin_by_item)

        self.ui.ps_btn_back.clicked.connect(self.go_to_main_screen)
        self.ui.ps_delete_plugin_btn.clicked.connect(self.delete_plugin)

        self.go_to_main_screen()
        self.window.show()

        # todo: Delete this part before first release
        self.garbage_test_code()
        sys.exit(self.app.exec_())
Esempio n. 3
0
    def __init__(self):
        super(mainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Тут сделал более большой шрифт, но можно и уюбрать если что
        my_font = QtGui.QFont(self.ui.lineEdit.font())
        my_font.setPointSize(11)
        self.ui.label_2.setFont(my_font)
        self.ui.label.setFont(my_font)
        self.ui.groupBox.setFont(my_font)
        self.ui.radioButton.setFont(my_font)
        self.ui.radioButton_2.setFont(my_font)
        self.ui.label_3.setFont(my_font)
        self.ui.label_4.setFont(my_font)

        self.ui.pushButton.setFont(my_font)
        self.ui.pushButton_2.setFont(my_font)

        self.ui.menu_3.setFont(my_font)
        self.ui.menu.setFont(my_font)

        self.ui.tableWidget.setFont(my_font)

        self.ui.lineEdit.setFont(my_font)
        self.ui.lineEdit_2.setFont(my_font)
        self.ui.textBrowser.setFont(my_font)
class MyWindow(QMainWindow):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.dw = DragWidget()
        self.ui.VerticalLayout_Image.addWidget(self.dw)
        self.ui.actionSelect_Folder.triggered.connect(self.selectFolder)
        self.working_dir = '.'


#        self.getImageList()

    def selectFolder(self):
        self.working_dir = str(
            QFileDialog.getExistingDirectory(self, "Select Directory"))

    def getImageList(self):
        while True:
            self.image_list = glob.glob(os.path.join(self.working_dir,
                                                     "*.jpg"))
            if len(self.image_list) == 0:
                break
            else:
                self.dw.SetBackground(self.image_list[0])
Esempio n. 5
0
class MyModManager(QtWidgets.QMainWindow):
    """ Main application class """
    def __init__(self):
        super(MyModManager, self).__init__()
        self.title = 'Simple Total War: Warhammer II Mod Manager'
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.launchGameBtn.clicked.connect(self.launchGameClicked)
        self.ui.refreshBtn.clicked.connect(self.refreshBtnClicked)
        self.populateTable()
        self.setWindowTitle(self.title)

    def populateTable(self):
        mods_table_cols = [
            'order', 'active', 'uuid', 'game', 'packfile', 'name', 'category',
            'short', 'owned'
        ]
        hide_cols = ['game', 'packfile', 'owned']
        mods_table = self.ui.modListTbl
        mod_data = ModConfig()
        mod_data_model = ModTableModel(mod_data.mod_data)
        mods_table.setModel(mod_data_model)

    def refreshBtnClicked(self):
        self.populateTable()

    def launchGameClicked(self):
        os.startfile(steam_cmd)
Esempio n. 6
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.retranslateUi(self)
        self.db_path = r'database\sklad_db.sqlite3'
        self.ui.path_db.setText(self.db_path)

        self.save_db = QAction(QIcon('icon/save.png'), 'Сохранить', self)
        self.find_db_file = QAction(QIcon('icon/open_db.png'), 'Открыть БД',
                                    self)
        self.add_rec = QAction(QIcon('icon/add.png'), 'Добавить запись', self)
        self.del_rec = QAction(QIcon('icon/del.png'), 'Удалить запись', self)
        self.ui.toolBar.addAction(self.save_db)
        self.ui.toolBar.addAction(self.find_db_file)
        self.ui.toolBar.addAction(self.add_rec)
        self.ui.toolBar.addAction(self.del_rec)
        self.db = None
        self.table_model = None

        self.open_db()

        self.add_rec.triggered.connect(self.add_record_action)
        self.del_rec.triggered.connect(self.del_record_action)
        self.save_db.triggered.connect(self.save_change_db)
        self.find_db_file.triggered.connect(self.find_db_file_action)
        self.ui.comboBox.currentIndexChanged.connect(self.show_table)
Esempio n. 7
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.retranslateUi(self)
        self.db_path = r'database\database.sqlite3'
        self.ui.path_db.setText(self.db_path)

        self.open_db_file = QAction(QIcon('img/open.png'), 'load data', self)
        self.save_db = QAction(QIcon('img/save.png'), 'save', self)
        self.add_row = QAction(QIcon('img/add.png'), 'add', self)
        self.del_row = QAction(QIcon('img/del.png'), 'del', self)
        self.ui.toolBar.addAction(self.save_db)
        self.ui.toolBar.addAction(self.open_db_file)
        self.ui.toolBar.addAction(self.add_row)
        self.ui.toolBar.addAction(self.del_row)
        self.db = None
        self.table_model = None

        self.open_db()

        self.add_row.triggered.connect(self.add_row_action)
        self.del_row.triggered.connect(self.del_row_action)
        self.save_db.triggered.connect(self.save_change_db)
        self.open_db_file.triggered.connect(self.open_db_file_action)
        self.ui.comboBox.currentIndexChanged.connect(self.show_table)
Esempio n. 8
0
    def __init__(self, parent=None):
        super().__init__(parent)
        # Собираем окно
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.retranslateUi(self)
        self.db_path = r'database/database.sqlite3'
        self.ui.path_db.setText(self.db_path)

        # Собираем кнопки
        self.save_db = QAction(QIcon('icon/save.png'), 'Save', self)
        self.open_db_file = QAction(QIcon('icon/open-db.png'), 'Open', self)
        self.add_row = QAction(QIcon('icon/add.png'), 'Add row', self)
        self.del_row = QAction(QIcon('icon/del.png'), ' Del row', self)
        self.ui.toolBar.addAction(self.save_db)
        self.ui.toolBar.addAction(self.open_db_file)
        self.ui.toolBar.addAction(self.add_row)
        self.ui.toolBar.addAction(self.del_row)
        self.db = None
        self.table_model = None
        # Подключаемся к БД
        self.open_db()
        # действуем по триггерам
        self.add_row.triggered.connect(self.add_row_action)
        self.del_row.triggered.connect(self.del_row_action)
        self.save_db.triggered.connect(self.save_change_db)
        self.open_db_file.triggered.connect(self.open_db_file_action)
        self.ui.comboBox.currentIndexChanged.connect(self.show_table)
Esempio n. 9
0
class appWin(QMainWindow):
    def __init__(self):
        super(appWin, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.threadpool = QThreadPool()
        print('Multithreading with maximum {} thread'.format(
            self.threadpool.maxThreadCount()))

        self.timer = QTimer()
        self.timer.setInterval(0.1)
        self.timer.timeout.connect(self.on_timer_timeout)
        self.timer.start()
        self.count = 0

        self.ui.pushButton.clicked.connect(self.on_btn)

    def on_timer_timeout(self):
        self.count += 1
        self.ui.label.setText(str(self.count))

    def on_btn(self):
        # for i in range(5):
        #     # QApplication.processEvents()
        #     self.ui.label_2.setText(str(i+1))
        #     time.sleep(1)
        worker1 = Worker([1, 2, 3, 4], 'Ali', ui=self.ui, test='pp')
        self.threadpool.start(worker1)
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.dw = DragWidget()
     self.ui.VerticalLayout_Image.addWidget(self.dw)
     self.ui.actionSelect_Folder.triggered.connect(self.selectFolder)
     self.working_dir = '.'
Esempio n. 11
0
 def __init__(self):
     super(MyModManager, self).__init__()
     self.title = 'Simple Total War: Warhammer II Mod Manager'
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.launchGameBtn.clicked.connect(self.launchGameClicked)
     self.ui.refreshBtn.clicked.connect(self.refreshBtnClicked)
     self.populateTable()
     self.setWindowTitle(self.title)
Esempio n. 12
0
class Main_Window(QtWidgets.QMainWindow):
    """Главное окно с выбором метода"""
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.button_terms.clicked.connect(self.open_table_terms)
        self.ui.button_matrix.clicked.connect(self.open_table_matrix)
        self.ui.button_next.clicked.connect(self.open_next_window)
        self.ui.combo_box_method.currentIndexChanged.connect(
            lambda: self.change_method(self.ui.combo_box_method.currentIndex()
                                       ))

    def change_method(self, index):
        if index == 0:
            self.ui.spin_box_experts.setEnabled(True)
            self.ui.spin_box_terms.setEnabled(True)
            self.ui.spin_box_elements.setEnabled(True)
            self.ui.button_terms.setEnabled(True)
            self.ui.button_matrix.setEnabled(False)
            self.ui.button_next.setEnabled(False)
        elif index == 1:
            self.ui.spin_box_experts.setEnabled(False)
            self.ui.spin_box_terms.setEnabled(False)
            self.ui.spin_box_elements.setEnabled(True)
            self.ui.button_terms.setEnabled(False)
            self.ui.button_matrix.setEnabled(True)
            self.ui.button_next.setEnabled(False)
        elif index == 2:
            self.ui.spin_box_experts.setEnabled(False)
            self.ui.spin_box_terms.setEnabled(False)
            self.ui.spin_box_elements.setEnabled(False)
            self.ui.button_terms.setEnabled(False)
            self.ui.button_matrix.setEnabled(False)
            self.ui.button_next.setEnabled(False)

    def open_table_terms(self):
        """По кнопке "Ввод значений термов"
        открывается окно с таблицей термов"""
        self.table_terms = Window_terms(self)
        self.table_terms.show()
        self.hide()

    def open_table_matrix(self):
        """По кнопке "Ввод матрицы исходных данных"
        открывается окно с матрицей"""
        self.table_matrix = Window_matrix(self)
        self.table_matrix.show()
        self.hide()

    def open_next_window(self):
        """По кнопке "Построить функцию принадлежности"
        открывается окно с отрисовкой"""
        self.window_2 = Window_2(self)
        self.window_2.show()
        self.hide()
Esempio n. 13
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #self.setFixedSize(self.width(), self.height())

        statusbar = self.statusBar()

        self.label = QtGui.QLabel('300')
        statusbar.addPermanentWidget(self.label)

        slider = QtGui.QSlider(QtCore.Qt.Horizontal, statusbar)
        slider.setMinimum(50)
        slider.setMaximum(1000)
        slider.setValue(300)
        statusbar.addPermanentWidget(slider)

        slider.valueChanged.connect(self.ui.board.update_timer)
        slider.valueChanged.connect(self.update_label)

        self.statusBar().showMessage("Ovo je Game of Life")

        self.from_survive = QtGui.QSpinBox(self.ui.toolBar)
        self.from_survive.setMaximum(6)
        self.from_survive.setMinimum(1)
        self.from_survive.setValue(2)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('From survive: '))
        self.ui.toolBar.addWidget(self.from_survive)

        self.to_survive = QtGui.QSpinBox(self.ui.toolBar)
        self.to_survive.setMaximum(7)
        self.to_survive.setMinimum(2)
        self.to_survive.setValue(3)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('To survive: '))
        self.ui.toolBar.addWidget(self.to_survive)

        self.come_to_life = QtGui.QSpinBox(self.ui.toolBar)
        self.come_to_life.setMaximum(7)
        self.come_to_life.setMinimum(2)
        self.come_to_life.setValue(3)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('Come to life: '))
        self.ui.toolBar.addWidget(self.come_to_life)

        self.from_survive.valueChanged.connect(
            self.ui.board.scene.matrix.set_from_survive)
        self.to_survive.valueChanged.connect(
            self.ui.board.scene.matrix.set_to_survive)
        self.come_to_life.valueChanged.connect(
            self.ui.board.scene.matrix.set_come_to_life)

        self.ui.board.scene.matrix.changed.connect(self.update_statusbar)
        self.ui.board.scene.matrix.reseted.connect(self.update_statusbar)
Esempio n. 14
0
    def __init__(self, tipo=None, rut=None):
        'Constructor de la clase'
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.rut = rut
        self.tipo = tipo
        self.set_signals()
        self.showMaximized()
        self.config_user()

        self.setVisible(
            False
        )  # Se oculta la ventana principal mientras se cargan los componentes.

        # Se crea un QProgressDialog para notificar al usuario sobre las cargas del programa.
        progress = QtGui.QProgressDialog("Cargando modulos...", "", 0,
                                         self.num_mesas + 7)
        progress.setWindowTitle("Cargando...")
        progress.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        label = QtGui.QLabel()
        pixmap = QtGui.QPixmap('images/cafe_nostro_load_modulos.png')
        label.setPixmap(pixmap)
        progress.setLabel(label)
        progress.setCancelButton(None)
        progress.show()

        progress.setValue(0)
        self.ui.stackedWidget.addWidget(AdminUsers())  #2
        progress.setValue(1)
        self.ui.stackedWidget.addWidget(AdminProductos())  #3
        progress.setValue(2)
        self.ui.stackedWidget.addWidget(FormularioVenta(
            self.ui, self.rut, "0"))  #4
        progress.setValue(3)
        self.ui.stackedWidget.addWidget(AdminVentas(self.ui))  #5
        progress.setValue(4)
        self.ui.stackedWidget.addWidget(
            MesasVenta(self, self.num_mesas, self.rut))  #6
        progress.setValue(5)
        self.ui.stackedWidget.addWidget(Estadistica())  # 7
        progress.setValue(6)
        self.ui.stackedWidget.addWidget(
            FormularioVenta(self.ui, self.rut, "-1"))  # 8
        progress.setValue(7)

        pixmap = QtGui.QPixmap('images/cafe_nostro_load_mesas.png')
        label.setPixmap(pixmap)

        for i in range(1, self.num_mesas + 1):  #9 = primera mesa
            self.ui.stackedWidget.addWidget(
                FormularioVenta(self.ui, self.rut, str(i)))
            progress.setValue(i + 5)

        progress.setValue(self.num_mesas + 7)
        self.setVisible(True)
Esempio n. 15
0
    def __init__(self):
        super(window, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.set_signals()
        self.computing=Thread(target=self.compute)



        self.cf=cf([self.ui.l_gyro_x,self.ui.l_gyro_y,self.ui.l_gyro_z],[self.ui.l_acc_x,self.ui.l_acc_y,self.ui.l_acc_z],self.ui.l_status)
Esempio n. 16
0
 def __init__(self):
     super().__init__()
     self.ui = Ui_MainWindow()
     self.imgNumber = 0
     self.ui.setupUi(self)
     self.groupSize, self.imgIndex = 5, 0
     self.imgLabels = [
         self.ui.image1, self.ui.image2, self.ui.image3, self.ui.image4,
         self.ui.image5
     ]
Esempio n. 17
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # set up variables
        self.pixmap = QPixmap()
        self.f = QFileInfo()

        self.setAcceptDrops(True)
Esempio n. 18
0
 def __init__(self):
     super().__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     #self.setCentralWidget(homepage)
     #homepage.setParent(self.ui.window_frame)
     self.home_btn = qtw.QAction(qtg.QIcon('home_btn.png'), 'דף בית', self)
     self.ui.toolBar.addAction(self.home_btn)
     self.home_btn.triggered.connect(self.go_to_home_page)
     self.setStyleSheet(stylesheet.stylesheet)
Esempio n. 19
0
 def __init__(self):
     QtGui.QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.connect_btn_listeners()
     self.bt = PyBluetooth(self)
     self.worker_thread = BTReceiverThread()
     self.test_thread = TestThread(self.bt.bluetooth)
     self.connect(self.worker_thread, SIGNAL("appendToTerminal(QString)"), self.appendToTerminal)
     self.connect(self.test_thread, SIGNAL("finished(PyQt_PyObject)"), self.sendToUI)
Esempio n. 20
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)  
        self.main()

    def main(self):
        QMessageBox.about(self, "Info", "Enter movie info.")
Esempio n. 21
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self,None)#, QtCore.Qt.WindowStaysOnTopHint)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.today = datetime.date.today()
        self.resize(self.sizeHint())
        #self.check_net_connection()
        self.time_diff()
        self.total_counting()
        
        
        QtCore.QObject.connect(self.ui.date_start, QtCore.SIGNAL(_fromUtf8("dateChanged(QDate)")), self.time_diff)
        QtCore.QObject.connect(self.ui.date_end, QtCore.SIGNAL(_fromUtf8("dateChanged(QDate)")), self.time_diff)
        QtCore.QObject.connect(self.ui.spinBox_prepainment, QtCore.SIGNAL(_fromUtf8("valueChanged(QString)")), self.total_counting)
        QtCore.QObject.connect(self.ui.SpinBox_square, QtCore.SIGNAL(_fromUtf8("valueChanged(QString)")), self.total_counting)
        QtCore.QObject.connect(self.ui.spinBox_price, QtCore.SIGNAL(_fromUtf8("valueChanged(QString)")), self.total_counting)
  

    def time_diff(self):
        t_start = self.ui.date_start.date()
        t_end = self.ui.date_end.date()
        diff_from_now = self.today - t_start.toPyDate()
        diff_from_end = t_end.toPyDate() - t_start.toPyDate()
        Main.month_total = round(diff_from_end.days/30.)
        Main.month_from_now = round(diff_from_now.days/30.)
        print Main.month_total, Main.month_from_now
        self.total_counting()
        #timedelta1 = datetime.timedelta(days=1)
        #print now + timedelta1
        # 2015-03-09

    
    def total_counting(self):
        square = self.ui.SpinBox_square.value()
        price = self.ui.spinBox_price.value()
        Main.total_price = round(square*price)
        Main.balance_amount = Main.total_price - self.ui.spinBox_prepainment.value()
        Main.mon_payment = Main.balance_amount/(Main.month_total-1)
        self.ui.spinBox_total.setValue(int(Main.total_price))
        self.ui.spinBox_mon_pay.setValue(int(Main.mon_payment))
        self.ui.spinBox_balance_amount.setValue(int(Main.balance_amount))
        print Main.mon_payment,Main.total_price,Main.month_total
        
    def check_net_connection(self):
        try:
            r = requests.get('http://ukrstat.gov.ua/operativ/operativ2015/ct/icv/icv_u/icv_pm15_u.html')
            print r
            if '[404]' in r:
                raise requests.ConnectionError
            else:
                page_answer = r.content
        except requests.ConnectionError:
            self.ui.statusbar.showMessage('Page with index inflation not found!')
            self.ui.checkBox.setEnabled(False)         
Esempio n. 22
0
    def __init__(self):
        self.loading_screen()
        self.data = None
        self.output_data = None
        self.colors = [
            '#f0e443', '#f77e45', '#f74940', '#4bfa91', '#69d1d1', '#4a61f7'
        ]
        self.version = '1.0.1'
        self.map = [{
            'Excellent': 5,
            'Very Good': 4,
            'Good': 3,
            'Poor': 2,
            'Very Poor': 1
        }, {
            'Yes': 3,
            'Partially Completed': 2,
            'No': 1
        }]

        self.root = QMainWindow()
        self.window = Ui_MainWindow()
        self.window.setupUi(self.root)
        self.window.retranslateUi(self.root)

        self.window.menuFile.addAction(QIcon('icons/open.ico'), 'Open',
                                       self.open_func, 'Ctrl+O')
        self.window.menuFile.addSeparator()
        self.window.menuFile.addAction(QIcon('icons/save.ico'), 'Save',
                                       self.create_output, 'Ctrl+S')
        self.window.menuFile.addSeparator()
        self.window.menuFile.addAction(QIcon('icons/exit.ico'), 'Quit',
                                       lambda: exit(), 'Ctrl+Q')

        self.window.menuOptions.addAction(QIcon('icons/setting.ico'),
                                          'Setting', self.open_setting,
                                          'Ctrl+X')
        self.window.menuOptions.addAction(QIcon('icons/color'), 'Colors',
                                          self.change_graph_color, 'Ctrl+J')

        self.window.menuHelp.addAction(QIcon('icons/about.ico'), 'About',
                                       self.about_func, 'Ctrl+H')
        self.window.menuHelp.addAction(QIcon('icons/update.ico'),
                                       'Check for update', self.check_update,
                                       'Ctrl+U')

        self.window.open_button.clicked.connect(self.open_func)
        self.window.drop_button.clicked.connect(self.drop_func)
        self.window.select_button.clicked.connect(self.select_func)
        self.window.copy_csv_button.clicked.connect(self.copy_func)
        self.window.save_button.clicked.connect(self.create_output)

        self.window.column_list.setStyleSheet('color: blue;')

        self.root.show()
Esempio n. 23
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.button_terms.clicked.connect(self.open_table_terms)
        self.ui.button_matrix.clicked.connect(self.open_table_matrix)
        self.ui.button_next.clicked.connect(self.open_next_window)
        self.ui.combo_box_method.currentIndexChanged.connect(
            lambda: self.change_method(self.ui.combo_box_method.currentIndex()
                                       ))
Esempio n. 24
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.board = self.ui.board
        self.record = self.ui.record
        self.record.last_row = self.record.currentRow()

        self.engines = {}
        self.pos, _ = self.get_pos(0)
        self.mode = None
    def __init__(self):
        super().__init__()

        # Setup ui
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Create fetch thread
        self.thread = FetchPrice()

        # Connect signals
        self.ui.priceCheckButton.clicked.connect(self.update_price)
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.center()

    def center(self):
        setGeometry = self.frameGeometry()
        centerGeometry = QDesktopWidget().availableGeometry().center()
        setGeometry.moveCenter(centerGeometry)
        self.move(setGeometry.topLeft())
    def __init__(self):
        super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.set_callback()
        self.show()

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.ui.figure_layout.addWidget(self.canvas)
        self.ax = self.figure.add_subplot(111)
Esempio n. 28
0
    def __init__(self):
        super().__init__()
        self._ui = Ui_MainWindow()
        self._ui.setupUi(self)
        self.setWindowTitle("智能语音合成系统")
        self.setFixedSize(self.size())

        self.is_playing = False

        self.temp_file = gettempdir() + '/tempbaiduyuyin'
        self.temp_file_size = 0
        self.player = QMediaPlayer()
        print('临时文件:%s' % self.temp_file)
        self.connect()
Esempio n. 29
0
class MainWindow(QMainWindow):
    """ drag and drop image viewer """
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # set up variables
        self.pixmap = QPixmap()
        self.f = QFileInfo()

        self.setAcceptDrops(True)


# ---------------------------------------
# Drag / Drop code
# ---------------------------------------

    def dragEnterEvent(self, event):
        acceptedFileTypes = []
        acceptedFileTypes.append("jpg")
        acceptedFileTypes.append("png")
        acceptedFileTypes.append("bmp")
        print(acceptedFileTypes)

        if (event.mimeData().hasUrls())and \
                (len(event.mimeData().urls()) == 1):
            self.f = QFileInfo(event.mimeData().urls()[0].toLocalFile())
            print(self.f.suffix().lower())
            if self.f.suffix().lower() in acceptedFileTypes:
                event.acceptProposedAction()

    def dropEvent(self, event):
        print('Drop Event happening')
        print(self.f.absoluteFilePath())
        if (self.pixmap.load(self.f.absoluteFilePath())):
            self.ui.label.setPixmap(
                self.pixmap.scaled(self.ui.label.size(), Qt.KeepAspectRatio,
                                   Qt.SmoothTransformation))
        else:
            QMessageBox.critical(self, "Error",
                                 "The image file cannot be read!")

    def resizeEvent(self, event):
        if not (self.pixmap.isNull()):
            self.ui.label.setPixmap(
                self.pixmap.scaled(self.ui.label.width() - 5,
                                   self.ui.label.height() - 5,
                                   Qt.KeepAspectRatio,
                                   Qt.SmoothTransformation))
Esempio n. 30
0
class PyPoolMainWindow(QtGui.QMainWindow):
    log = QtCore.Signal(str)

    def __init__(self, parent=None):
        # Initialise the window and populate it with the GUI elements we've created in QtDesigner.
        super(PyPoolMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Set up the graphics widget.
        self.svg = None
        self.graphics_item = None
        self.scene = QtGui.QGraphicsScene()
        self.ui.graphicsView.setScene(self.scene)
Esempio n. 31
0
 def __init__(self):
     QMainWindow.__init__(self)
     Ui_MainWindow.__init__(self)
     self.setupUi(self)
     self.title = 'ECE Instrument Room Inventory Tool'
     self.label_puid.setText("XXXXX-XXXXX")
     self.label_puid.setMinimumWidth(500)
     self.initTables()
     self.text_search.textChanged.connect(self.searchTextChanged)
     self.initUI()
     self.initText()
     self.button_inductoradd.clicked.connect(self.buttonClicked)
     self.button_resistoradd.clicked.connect(self.buttonClicked)
     self.button_capadd.clicked.connect(self.buttonClicked)
     self.button_icadd.clicked.connect(self.buttonClicked)
Esempio n. 32
0
    def __init__(self):
        super(Start, self).__init__()
        self.id_counter = 1
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.nodes_list = []
        self.ui_buttons_list = []

        # buttons connectors
        self.ui.count_logic.clicked.connect(
            self.start_logic)  # logical start count func
        self.ui.count_static.clicked.connect(
            self.start_static)  # static start count func
        self.ui.add_node.clicked.connect(self.add_node)  # f*****g add node
        self.ui.clear.clicked.connect(self.clear)  # clear func
Esempio n. 33
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self,None)#, QtCore.Qt.WindowStaysOnTopHint)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        def set_device_info(self):
            for e,d in enumerate(device_info['model']):
                device_line = device_info['model'][e]+' ('+device_info['android_ver'][e]+'/'
                device_line = device_line+device_info['build_type'][e]+'/'+device_info['id'][e]+')'
                self.ui.cb_device.insertItem(e,device_line)
            self.ui.cb_device.insertItem(e+1,"All attached devices")
            #print device_info

        def set_build_type(self):
            try:
                for e,line in enumerate(open('config.ini','r').readlines()):
                    self.ui.cb_buildtype.insertItem(e,line.rstrip())
            except:
                self.ui.cb_buildtype.insertItem(0,"No config.ini file")

        set_build_type(self)
        set_device_info(self)
        try:
            self.tc_connection()
        except urllib2.URLError:
             self.ui.statusbar.showMessage('No Connection to TeamCity server!', 7000)
             local_dirs = glob.glob('.'+os.sep+'BuildsFromTC'+os.sep+'*')
             build_number_list =[line.split('_')[-1] for line in local_dirs]
             [self.ui.cb_number.insertItem(e,line) for e,line in enumerate(build_number_list)]

        QtCore.QObject.connect(self.ui.cb_buildtype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.tc_connection)
        QtCore.QObject.connect(self.ui.btn_start, QtCore.SIGNAL(_fromUtf8("clicked()")), self.install_main)
        QtCore.QObject.connect(self.ui.btn_clear_device, QtCore.SIGNAL(_fromUtf8("clicked()")), self.clear_application)
        QtCore.QObject.connect(self.ui.btn_start_test, QtCore.SIGNAL(_fromUtf8("clicked()")), self.start_test)
        QtCore.QObject.connect(self.ui.btn_run_all, QtCore.SIGNAL(_fromUtf8("clicked()")), self.run_all_test)
Esempio n. 34
0
File: main.py Progetto: olexiim/tsp
 def __init__(self, parent=None):
     QtGui.QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     
     self.disable_methods()
     self.clear_board()
     
     # init run button menu
     self.run_menu = QtGui.QMenu()
     self.run_menu.addAction("Run once", self.run_once)
     self.run_menu.addAction("Run checked methods", self.run_checked_methods)
     self.run_menu.addAction("Run all methods", self.run_all_variants)
     self.ui.run.setMenu(self.run_menu)
     
     # status bar
     self.timer_widget = QtGui.QLabel()
     self.run_timer = QtCore.QTimer(self)
     self.run_timer.timeout.connect(self.update_timer)
     
     # init stat table
     header_labels = ["##","Problem","Method","Neighborhood",
             "Solution cost","Time, sec", "Overall states"]
     self.ui.stat_table.setHorizontalHeaderLabels(header_labels)
     self.ui.stat_table.resizeColumnsToContents() # autoresize based on header text width
     self.ui.stat_table.setColumnWidth(1, 110) # extend Problem header width
     self.ui.stat_table.setColumnWidth(2, 120) # extend Problem header width
     self.ui.stat_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
     self.ui.stat_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
     
     QtCore.QObject.connect(self.ui.run,QtCore.SIGNAL("clicked()"), self.run_once)
     
     self.ui.actionGenerate_new.triggered.connect(self.new_random)
     self.ui.actionLoad_from_file.triggered.connect(self.new_load)
     self.ui.actionSave.triggered.connect(self.save_problem)
     self.ui.actionRestart.triggered.connect(self.restart)
     self.ui.actionRun_once.triggered.connect(self.run_once)
     self.ui.actionRun_checked_methods.triggered.connect(self.run_checked_methods)
     self.ui.actionRun_all_methods.triggered.connect(self.run_all_variants)
     self.ui.actionStop.triggered.connect(self.stop)
     self.ui.actionClear.triggered.connect(self.clear_statistics)
     self.ui.actionDelete_selected.triggered.connect(self.delete_selected_statistics)
     self.ui.actionImportTo_CSV.triggered.connect(self.import_to_csv)
     self.ui.actionExit.triggered.connect(self.close)
     self.ui.actionOptions.triggered.connect(self.popup_main_options_dlg)
     
     self.ui.methods_tree.itemDoubleClicked.connect(self.methods_tree_item_clicked)
     self.ui.stat_table.currentItemChanged.connect(self.stat_table_item_changed)
     self.ui.main_splitter.splitterMoved.connect(self.process_resize)
     self.ui.splitter_2.splitterMoved.connect(self.process_resize)
     
     self.ui.stat_table.keyPressEvent = self.process_statistics_keys_event
     
     self.ui.tab_widget.setCurrentIndex(0)
Esempio n. 35
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.board = self.ui.board
        self.record = self.ui.record
        self.record.last_row = self.record.currentRow()

        self.engines = {}
        self.pos, _ = self.get_pos(0)
        self.mode = None
Esempio n. 36
0
    def __init__(self, mpd_api, parent=None):
        QMainWindow.__init__(self, parent)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.mpd_api = mpd_api
        self.current_song = self.mpd_api.currentsong()

        self.setup_actions()

        self.setup_library()

        self.setup_playlists()

        self.setup_playlist()

        self.setup_database_songs()

        self.updater = updater(self)
        self.updater.start(1000)
        self.updater.update()
Esempio n. 37
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #self.setFixedSize(self.width(), self.height())

        statusbar = self.statusBar()

        self.label = QtGui.QLabel('300')
        statusbar.addPermanentWidget(self.label)

        slider = QtGui.QSlider(QtCore.Qt.Horizontal, statusbar)
        slider.setMinimum(50)
        slider.setMaximum(1000)
        slider.setValue(300)
        statusbar.addPermanentWidget(slider)

        slider.valueChanged.connect(self.ui.board.update_timer)
        slider.valueChanged.connect(self.update_label)

        self.statusBar().showMessage("Ovo je Game of Life")

        self.from_survive = QtGui.QSpinBox(self.ui.toolBar)
        self.from_survive.setMaximum(6)
        self.from_survive.setMinimum(1)
        self.from_survive.setValue(2)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('From survive: '))
        self.ui.toolBar.addWidget(self.from_survive)

        self.to_survive = QtGui.QSpinBox(self.ui.toolBar)
        self.to_survive.setMaximum(7)
        self.to_survive.setMinimum(2)
        self.to_survive.setValue(3)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('To survive: '))
        self.ui.toolBar.addWidget(self.to_survive)

        self.come_to_life = QtGui.QSpinBox(self.ui.toolBar)
        self.come_to_life.setMaximum(7)
        self.come_to_life.setMinimum(2)
        self.come_to_life.setValue(3)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('Come to life: '))
        self.ui.toolBar.addWidget(self.come_to_life)

        self.from_survive.valueChanged.connect(self.ui.board.scene.matrix.set_from_survive)
        self.to_survive.valueChanged.connect(self.ui.board.scene.matrix.set_to_survive)
        self.come_to_life.valueChanged.connect(self.ui.board.scene.matrix.set_come_to_life)

        self.ui.board.scene.matrix.changed.connect(self.update_statusbar)
        self.ui.board.scene.matrix.reseted.connect(self.update_statusbar)
Esempio n. 38
0
    def __init__(self, tipo=None, rut=None):
        'Constructor de la clase'
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.rut = rut
        self.tipo = tipo
        self.set_signals()
        self.showMaximized()
        self.config_user()

        self.setVisible(False) # Se oculta la ventana principal mientras se cargan los componentes.

        # Se crea un QProgressDialog para notificar al usuario sobre las cargas del programa.
        progress = QtGui.QProgressDialog("Cargando modulos...", "", 0, self.num_mesas+7)
        progress.setWindowTitle("Cargando...")
        progress.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        label = QtGui.QLabel()
        pixmap = QtGui.QPixmap('images/cafe_nostro_load_modulos.png')
        label.setPixmap(pixmap)
        progress.setLabel(label)
        progress.setCancelButton(None)
        progress.show()

        progress.setValue(0)
        self.ui.stackedWidget.addWidget(AdminUsers()) #2
        progress.setValue(1)
        self.ui.stackedWidget.addWidget(AdminProductos()) #3
        progress.setValue(2)
        self.ui.stackedWidget.addWidget(FormularioVenta(self.ui,self.rut,"0")) #4
        progress.setValue(3)
        self.ui.stackedWidget.addWidget(AdminVentas(self.ui)) #5
        progress.setValue(4)
        self.ui.stackedWidget.addWidget(MesasVenta(self,self.num_mesas,self.rut)) #6
        progress.setValue(5)
        self.ui.stackedWidget.addWidget(Estadistica()) # 7
        progress.setValue(6)
        self.ui.stackedWidget.addWidget(FormularioVenta(self.ui,self.rut,"-1")) # 8
        progress.setValue(7)

        pixmap = QtGui.QPixmap('images/cafe_nostro_load_mesas.png')
        label.setPixmap(pixmap)

        for i in range(1,self.num_mesas+1): #9 = primera mesa
            self.ui.stackedWidget.addWidget(FormularioVenta(self.ui,self.rut,str(i)))
            progress.setValue(i+5)

        
        progress.setValue(self.num_mesas+7)
        self.setVisible(True)
Esempio n. 39
0
 def __init__(self):
     QtGui.QMainWindow.__init__(self,None)#, QtCore.Qt.WindowStaysOnTopHint)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.today = datetime.date.today()
     self.resize(self.sizeHint())
     #self.check_net_connection()
     self.time_diff()
     self.total_counting()
     
     
     QtCore.QObject.connect(self.ui.date_start, QtCore.SIGNAL(_fromUtf8("dateChanged(QDate)")), self.time_diff)
     QtCore.QObject.connect(self.ui.date_end, QtCore.SIGNAL(_fromUtf8("dateChanged(QDate)")), self.time_diff)
     QtCore.QObject.connect(self.ui.spinBox_prepainment, QtCore.SIGNAL(_fromUtf8("valueChanged(QString)")), self.total_counting)
     QtCore.QObject.connect(self.ui.SpinBox_square, QtCore.SIGNAL(_fromUtf8("valueChanged(QString)")), self.total_counting)
     QtCore.QObject.connect(self.ui.spinBox_price, QtCore.SIGNAL(_fromUtf8("valueChanged(QString)")), self.total_counting)
Esempio n. 40
0
	def __init__(self):
		super(IPBA2, self).__init__(None)
		
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
	
		# set to NONE if no backup is loaded
		# and check its noneness to lock analysis functions
		self.backup_path = None
	
		#self.openBackup()
		
		self.loadPlugins()
		
		QtCore.QObject.connect(self.ui.fileTree, QtCore.SIGNAL("itemSelectionChanged()"), self.onTreeClick)
		
		self.ui.fileTree.setColumnWidth(0,200)
		self.ui.fileTree.setColumnWidth(2,16)
		
		self.ui.fileTree.setColumnHidden(1,True)
		self.ui.fileTree.setColumnHidden(3,True)
		
		self.ui.imagePreviewLabel.hide()
		
		# File menu
		QtCore.QObject.connect(self.ui.menu_openarchive, QtCore.SIGNAL("triggered(bool)"), self.openBackup)
		QtCore.QObject.connect(self.ui.menu_closearchive, QtCore.SIGNAL("triggered(bool)"), self.closeBackup)
		
		# About menu
		QtCore.QObject.connect(self.ui.actionAbout, QtCore.SIGNAL("triggered(bool)"), self.about)
		
		# attach context menu to rightclick on elements tree
		self.ui.fileTree.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.ui.fileTree, QtCore.SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)	
		
		# toolbar bindings
		self.ui.actionNext.triggered.connect(self.nextWindow)
		self.ui.actionPrev.triggered.connect(self.prevWindow)
		self.ui.actionTile.triggered.connect(self.tileWindow)
		
		self.ui.actionToggleRight.triggered.connect(self.toggleRight)
		self.showRightSidebar = True
		
		# show about window on startup
		self.about()
Esempio n. 41
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.grammar = Grammar()
        self.file_name = ''

        self.ui.parseGrammarButton.clicked.connect(self.on_parse_grammar_click)
        self.ui.transformGrammarButton.clicked.connect(self.on_transform_grammar_click)
        self.ui.actionNew.triggered.connect(self.on_new_click)
        self.ui.actionLoad.triggered.connect(self.on_load_click)
        self.ui.actionSave.triggered.connect(self.on_save_click)
        self.ui.actionSave_as.triggered.connect(self.on_save_as_click)
        self.ui.actionExit.triggered.connect(self.on_exit)

        self.ui.actionSave.setEnabled(False)
Esempio n. 42
0
 def __init__(self):
     QtGui.QMainWindow.__init__(self,None, QtCore.Qt.WindowStaysOnTopHint)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.line_date.setText(str(symbol_date)+"R1")
     self.ui.line_info.installEventFilter(self)
     
     for n in range(1, 17):
         label = self.ui.__getattribute__('label_' + str(n))
         label.mousePressEvent = left_click(label.mousePressEvent, label)
         try:
             QtCore.QObject.connect(label, QtCore.SIGNAL('leftClicked()'), self.__getattribute__('link_activation_'+str(n)))
         except:
             print "Link not found at label position -",str(n)
         
     
     QtCore.QObject.connect(self.ui.line_info, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.info_changed )
     QtCore.QObject.connect(self.ui.btn_clean, QtCore.SIGNAL(_fromUtf8("clicked()")), self.list_clean )
     QtCore.QObject.connect(self.ui.btn_label, QtCore.SIGNAL(_fromUtf8("clicked()")), self.label_creation)
     QtCore.QObject.connect(self.ui.line_info, QtCore.SIGNAL(_fromUtf8("returnPressed()")), self.list_clean)
     QtCore.QObject.connect(self.ui.list_mail, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem*)")), self.mail_selection)
     QtCore.QObject.connect(self.ui.list_size, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem*)")), self.size_selection)
     QtCore.QObject.connect(self.ui.comboBox, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.box_selection)
Esempio n. 43
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # signals oracle
        self.signal = MySignal()

        # loading settings from file
        self.json = {}
        self.path_settings = os.path.join(os.path.dirname( os.path.realpath(__file__) ), "settings.json")

        if not os.path.exists(self.path_settings):
            try:
                f = open(self.path_settings, "w")
                # f.open()
                self.json["path_destination_photos"] = ""
                self.json["path_destination_videos"] = ""
                f.write(json.dumps(self.json))
                f.close()
            except Exception as e:
                print "Nie można utworzyć pliku ustawień!"
                print e
        else:
            try:
                f = open(self.path_settings, "r")
                # f.open()
                self.json = json.loads(f.read())
                f.close()
            except Exception as e:
                print "Nie mogę otworzyć pliku ustawień"
                print e


        self.path_source = ""
        self.path_destination_photos = ""
        self.path_destination_videos = ""
        self.path_dir_name = ""

        self.files_type = None
        self.media_files = []
        self.found_videos = []
        self.found_photos = []
        self.found_videos_strings = []
        self.found_photos_strings = []
        self.media_files_strings = []
        self.first_file = 0
        self.last_file = 0
        self.event_name = None

        # signals connecting
        self.ui.pushButton_choose.clicked.connect(self.open_choose_files_dialog)
        self.ui.pushButton_grrrab.clicked.connect(self.open_copy_dialog)
        self.ui.pushButton_manual_source.clicked.connect(self.open_source_directory_dialog)
        self.ui.pushButton_manual_dst_photos.clicked.connect(self.open_photos_directory_dialog)
        self.ui.pushButton_manual_dst_videos.clicked.connect(self.open_videos_directory_dialog)
        self.ui.pushButton_auto_source.clicked.connect(self.auto_find_source)
        self.ui.pushButton_auto_dst_photos.clicked.connect(self.auto_find_destination_photos)
        self.ui.pushButton_auto_dst_videos.clicked.connect(self.auto_find_destination_videos)

        # todo: do it if bored: manually edited paths
        # self.ui.lineEdit_path_source.textEdited.connect(self.source_directory_edited)
        # self.ui.lineEdit_path_dst_photos.textEdited.connect(self.videos_directory_edited)
        # self.ui.lineEdit_path_dst_camera.textEdited.connect(self.photos_directory_edited)

        self.signal.sigSourceDirectoryChanged.connect(self.set_source_directory)
        self.signal.sigVideoDirectoryChanged.connect(self.set_video_directory)
        self.signal.sigPhotosDirectoryChanged.connect(self.set_photos_directory)
        self.signal.sigFilesTypeChanged.connect(self.set_files_type)
        # self.signal.sigTargetDirectoryChanged.connect()

        # paths setups
        self.signal.sigPhotosDirectoryChanged.emit(self.json.get("path_destination_photos"))
        self.signal.sigVideoDirectoryChanged.emit(self.json.get("path_destination_videos"))
Esempio n. 44
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self,None)#, QtCore.Qt.WindowStaysOnTopHint)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        def set_device_info(self):
            for e,d in enumerate(device_info['model']):
                device_line = device_info['model'][e]+' ('+device_info['android_ver'][e]+'/'
                device_line = device_line+device_info['build_type'][e]+'/'+device_info['id'][e]+')'
                self.ui.cb_device.insertItem(e,device_line)
            self.ui.cb_device.insertItem(e+1,"All attached devices")
            #print device_info

        def set_build_type(self):
            try:
                for e,line in enumerate(open('config.ini','r').readlines()):
                    self.ui.cb_buildtype.insertItem(e,line.rstrip())
            except:
                self.ui.cb_buildtype.insertItem(0,"No config.ini file")

        set_build_type(self)
        set_device_info(self)
        try:
            self.tc_connection()
        except urllib2.URLError:
             self.ui.statusbar.showMessage('No Connection to TeamCity server!', 7000)
             local_dirs = glob.glob('.'+os.sep+'BuildsFromTC'+os.sep+'*')
             build_number_list =[line.split('_')[-1] for line in local_dirs]
             [self.ui.cb_number.insertItem(e,line) for e,line in enumerate(build_number_list)]

        QtCore.QObject.connect(self.ui.cb_buildtype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.tc_connection)
        QtCore.QObject.connect(self.ui.btn_start, QtCore.SIGNAL(_fromUtf8("clicked()")), self.install_main)
        QtCore.QObject.connect(self.ui.btn_clear_device, QtCore.SIGNAL(_fromUtf8("clicked()")), self.clear_application)
        QtCore.QObject.connect(self.ui.btn_start_test, QtCore.SIGNAL(_fromUtf8("clicked()")), self.start_test)
        QtCore.QObject.connect(self.ui.btn_run_all, QtCore.SIGNAL(_fromUtf8("clicked()")), self.run_all_test)

    def device_id(self):
        for device_id in device_info['id']:
            if device_id in self.ui.cb_device.currentText():
                device_id = [device_id]
                break
            if 'All' in self.ui.cb_device.currentText():
                device_id = device_info['id']
            else:
                device_id = False
                continue
        return device_id

    def device_name(self):
        for device_id in device_info['id']:
            if device_id in self.ui.cb_device.currentText():
                device_id = [device_id]
                break
            if 'All' in self.ui.cb_device.currentText():
                device_id = device_info['id']
            else:
                device_id = False
                continue
        return device_id

    def tc_connection(self):
        global build_info
        self.ui.cb_number.clear()
        build_info = {'build_id':[],'buildNumber':[],'status':[],'branchId':[], 'href':[],'webUrl':[]}
        page = 'HTTPS://' + SERVER + '/teamCity/httpAuth/app/rest/builds/?locator=buildType:'
        page = page + str(self.ui.cb_buildtype.currentText()).rstrip()+'&count=200&start=0'
        page_xml = get_page_xml(page)
        page_parse(page_xml,build_info)
        [self.ui.cb_number.insertItem(e,line) for e,line in enumerate(build_info['buildNumber']) ]

    def check_new_tcbuild(self, old_build_number):
        new_build_number = get_artifacts(build_info)[1]
        if old_build_number != new_build_number:
            return str(new_build_number)
        else:
            return None

    def install_main(self, build_number = None):
        global dir_name
        thread_list=[]
        zip_name= 'temp.zip'
        device_id = self.device_id()
        if os.path.exists(os.path.abspath('.')+'\\BuildsFromTC'):
            os.popen('rmdir '+os.sep+'BuildsFromTC')

        if build_number == None:
            build_number = str(self.ui.cb_number.currentText())
        artifacts_info = get_artifacts(build_info,build_number) # TC link for downloading and build number
        
        if 'Release' in str(self.ui.cb_buildtype.currentText()):
            dir_name = './BuildsFromTC'+os.sep+'Release'+os.sep+str(self.ui.cb_number.currentText())
        else:
            dir_name = './BuildsFromTC'+os.sep+'Develop'+os.sep+str(self.ui.cb_number.currentText())
        urllib.urlretrieve(artifacts_info[0], zip_name)
        artifact_release(zip_name,dir_name)

        for device in device_id:
            device_name = device_info['model'][device_info['id'].index(device)]
            run_test = [device, dir_name[2:], build_number, device_name]
            if run_test not in run_test_list :
                run_test_list.append([device, dir_name[2:], build_number, device_name])

            thread_list.append(Thread(target=adb_install, args=(dir_name,device)))
        [tr.start() for tr in thread_list]
        [tr.join() for tr in thread_list]
        self.ui.statusbar.showMessage('Packages are installed!',45000)

    def clear_application(self):
        device_id = self.device_id()
        thread_list=[]
        for device in device_id:
            filter = 'com.samsung.'
            thread_list.append(Thread(target=delete_3d_party_apk, args=(device,filter)))
        [tread.start() for tread in thread_list]
        [tread.join() for tread in thread_list]
        self.ui.statusbar.showMessage('Start package un-installation! Filter '+filter, 45000)
        print 'Clear all data with '+filter

    def start_test(self):
        global run_test_list
        ch_state = self.ui.chbox_new_auto.checkState()
        try:
            testcount = int(self.ui.cb_random.currentText())
            print 'Test count for test is',testcount
        except ValueError:
            print 'Random Test count!'
            testcount = None
        i=0
        count = int(self.ui.cb_count.currentText())
        while i<count:
            print "+++++++++++++++++++++++++++++++++++++++++++++++++++"
            print "    Run cycle {0} from {1} cycles. ".format(i,count)
            print "+++++++++++++++++++++++++++++++++++++++++++++++++++"
            thread_list=[]
            if testcount is None:
                testcount = random.randint(200,300)
            seed = random.randint(1, 10000)
            for test in run_test_list:
                thread_list.append(Thread(target=start_run_test,
                                          args=(test[0],test[1],test[2],test[3],testcount,seed,ch_state)))
            [tr.start() for tr in thread_list]
            [tr.join() for tr in thread_list]
            i+=1

            if i<int(self.ui.cb_count.currentText()) and self.ui.chb_latest.checkState()==2:
                if self.check_new_tcbuild(test[2]) != None:
                    build_number = self.check_new_tcbuild(test[2])
                    run_test_list=[]
                    print "\n New build number was found and applied!"
                    self.install_main(build_number)

    def run_all_test(self):
        window.setHidden(True)
        self.install_main()
        self.start_test()
        window.setHidden(False)
        print("All test were finished!")
        self.ui.statusbar.showMessage('All test were finished!')
Esempio n. 45
0
class window(QtGui.QMainWindow):

    def __init__(self):
        super(window, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.set_signals()
        self.computing=Thread(target=self.compute)



        self.cf=cf([self.ui.l_gyro_x,self.ui.l_gyro_y,self.ui.l_gyro_z],[self.ui.l_acc_x,self.ui.l_acc_y,self.ui.l_acc_z],self.ui.l_status)
    def set_signals(self):

        self.ui.pb_scan.clicked.connect(self.scan)

        self.ui.pb_conn.clicked.connect(self.pb_conn_clicked1)
        self.ui.pb_disc.clicked.connect(self.pb_disc_clicked1)

    # ustawienie polaczenie
    def pb_conn_clicked1(self):

        # self.computing.start()

        uri=self.ui.cb_device.currentText()
        self.ui.l_status.setText("connecting to {}".format(uri))
        self.cf.connect(uri)
        self.ui.pb_scan.setEnabled(False)
        self.ui.cb_device.setEnabled(False)
        self.ui.pb_disc.setEnabled(True)
        self.ui.pb_conn.setEnabled(False)

    # # rozlacznie
    def pb_disc_clicked1(self):


        self.ui.l_status.setText("Disconnecting ...")
        self.cf.close()

        self.ui.cb_device.setEnabled(True)
        self.ui.pb_disc.setEnabled(False)
        self.ui.pb_conn.setEnabled(True)

        self.ui.pb_scan.setEnabled(True)

    # funkcja wyszukiwania + wypelnienie cb
    def scan(self):
        # find USB devices
        dev = usb.core.find(find_all=True)

        a=cflib.crtp.scan_interfaces()
        self.ui.cb_device.clear()

        k=0
        kk=0
        for cfg in dev:
            if cfg.idVendor==6421:
                for i in a:
                    self.ui.cb_device.addItem(i[0].replace(str(kk),str(k),1))
                kk=k
                k+=1
        if len(a)>0:
            self.ui.pb_conn.setEnabled(True)
        else:
            self.ui.pb_conn.setEnabled(False)

    def compute(self):
        self.roll=0
        self.pitch=0
        self.yaw=0
        x=0
        y=0
        z=0
        time.sleep(5)
        while True:
            if self.cf.is_connected:
                # print self.ui.l_acc_x.text()
                # self.convertion()
                # acc=[float(self.ui.l_acc_x.text[3:]),float(self.ui.l_acc_y.text[3:]),float(self.ui.l_acc_z.text)[3:]]
                gyro=[float(self.ui.l_acc_x.text()[3:]),float(self.ui.l_acc_y.text()[3:]),float(self.ui.l_acc_z.text()[3:])]
                self.roll+=gyro[0]/ 100.0
                self.pitch+=gyro[1]/ 100.0
                self.yaw+=gyro[2]/ 100.0
                self.update_gui()
                time.sleep(0.1)


    def update_gui(self):
        self.ui.l_pitch.setText("Pitch: {:.3f}".format(self.pitch))
        self.ui.l_roll.setText("Roll: {:.3f}".format(self.roll))
        self.ui.l_yaw.setText("Pitch: {:.3f}".format(self.yaw))
Esempio n. 46
0
 def setupUi(self, w):
     Ui_MainWindow.setupUi(self, w)
     self.filter_table._current_page = 1
     self.filter_table._num_filtered_record = 0
     self.set_columns()
Esempio n. 47
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #self.setFixedSize(self.width(), self.height())

        statusbar = self.statusBar()

        self.label = QtGui.QLabel('300')
        statusbar.addPermanentWidget(self.label)

        slider = QtGui.QSlider(QtCore.Qt.Horizontal, statusbar)
        slider.setMinimum(50)
        slider.setMaximum(1000)
        slider.setValue(300)
        statusbar.addPermanentWidget(slider)

        slider.valueChanged.connect(self.ui.board.update_timer)
        slider.valueChanged.connect(self.update_label)

        self.statusBar().showMessage("Ovo je Game of Life")

        self.from_survive = QtGui.QSpinBox(self.ui.toolBar)
        self.from_survive.setMaximum(6)
        self.from_survive.setMinimum(1)
        self.from_survive.setValue(2)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('From survive: '))
        self.ui.toolBar.addWidget(self.from_survive)

        self.to_survive = QtGui.QSpinBox(self.ui.toolBar)
        self.to_survive.setMaximum(7)
        self.to_survive.setMinimum(2)
        self.to_survive.setValue(3)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('To survive: '))
        self.ui.toolBar.addWidget(self.to_survive)

        self.come_to_life = QtGui.QSpinBox(self.ui.toolBar)
        self.come_to_life.setMaximum(7)
        self.come_to_life.setMinimum(2)
        self.come_to_life.setValue(3)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addWidget(QtGui.QLabel('Come to life: '))
        self.ui.toolBar.addWidget(self.come_to_life)

        self.from_survive.valueChanged.connect(self.ui.board.scene.matrix.set_from_survive)
        self.to_survive.valueChanged.connect(self.ui.board.scene.matrix.set_to_survive)
        self.come_to_life.valueChanged.connect(self.ui.board.scene.matrix.set_come_to_life)

        self.ui.board.scene.matrix.changed.connect(self.update_statusbar)
        self.ui.board.scene.matrix.reseted.connect(self.update_statusbar)

    def update_statusbar(self):
        self.ui.statusBar.showMessage('Live cells: %d' %
                                      len(self.ui.board.scene.matrix.get_live_cells()))

    def update_label(self, value):
        self.label.setText(str(value))

    @QtCore.Slot()
    def on_actionSave_triggered(self):
        file_name = QtGui.QFileDialog.getSaveFileName(self)
        f = open(file_name, 'w')
        f.write(self.ui.board.scene.matrix.to_string())

    @QtCore.Slot()
    def on_actionOpen_triggered(self):
        from gol import GOLMatrix
        f = QtGui.QFileDialog.getOpenFileName(self)
        self.ui.board.scene.set_matrix(GOLMatrix.from_string(open(f, 'r').read()))
        self.ui.board.scene.matrix.reseted.emit()
Esempio n. 48
0
class MainWindow(QtGui.QMainWindow):
    photos_file_types = (".jpg", ".jpeg", ".JPG", ".JPEG")
    videos_file_types = (".MTS")

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # signals oracle
        self.signal = MySignal()

        # loading settings from file
        self.json = {}
        self.path_settings = os.path.join(os.path.dirname( os.path.realpath(__file__) ), "settings.json")

        if not os.path.exists(self.path_settings):
            try:
                f = open(self.path_settings, "w")
                # f.open()
                self.json["path_destination_photos"] = ""
                self.json["path_destination_videos"] = ""
                f.write(json.dumps(self.json))
                f.close()
            except Exception as e:
                print "Nie można utworzyć pliku ustawień!"
                print e
        else:
            try:
                f = open(self.path_settings, "r")
                # f.open()
                self.json = json.loads(f.read())
                f.close()
            except Exception as e:
                print "Nie mogę otworzyć pliku ustawień"
                print e


        self.path_source = ""
        self.path_destination_photos = ""
        self.path_destination_videos = ""
        self.path_dir_name = ""

        self.files_type = None
        self.media_files = []
        self.found_videos = []
        self.found_photos = []
        self.found_videos_strings = []
        self.found_photos_strings = []
        self.media_files_strings = []
        self.first_file = 0
        self.last_file = 0
        self.event_name = None

        # signals connecting
        self.ui.pushButton_choose.clicked.connect(self.open_choose_files_dialog)
        self.ui.pushButton_grrrab.clicked.connect(self.open_copy_dialog)
        self.ui.pushButton_manual_source.clicked.connect(self.open_source_directory_dialog)
        self.ui.pushButton_manual_dst_photos.clicked.connect(self.open_photos_directory_dialog)
        self.ui.pushButton_manual_dst_videos.clicked.connect(self.open_videos_directory_dialog)
        self.ui.pushButton_auto_source.clicked.connect(self.auto_find_source)
        self.ui.pushButton_auto_dst_photos.clicked.connect(self.auto_find_destination_photos)
        self.ui.pushButton_auto_dst_videos.clicked.connect(self.auto_find_destination_videos)

        # todo: do it if bored: manually edited paths
        # self.ui.lineEdit_path_source.textEdited.connect(self.source_directory_edited)
        # self.ui.lineEdit_path_dst_photos.textEdited.connect(self.videos_directory_edited)
        # self.ui.lineEdit_path_dst_camera.textEdited.connect(self.photos_directory_edited)

        self.signal.sigSourceDirectoryChanged.connect(self.set_source_directory)
        self.signal.sigVideoDirectoryChanged.connect(self.set_video_directory)
        self.signal.sigPhotosDirectoryChanged.connect(self.set_photos_directory)
        self.signal.sigFilesTypeChanged.connect(self.set_files_type)
        # self.signal.sigTargetDirectoryChanged.connect()

        # paths setups
        self.signal.sigPhotosDirectoryChanged.emit(self.json.get("path_destination_photos"))
        self.signal.sigVideoDirectoryChanged.emit(self.json.get("path_destination_videos"))

    def closeEvent(self, event):
        f = open(self.path_settings, "w")
        # f.open()
        f.write(json.dumps(self.json))
        f.close()

    # todo: do it if bored: manually edited paths
    # def source_directory_edited(self):
    #     self.signal.sigSourceDirectoryChanged.emit(self.ui.lineEdit_path_source.text())
    #
    # def videos_directory_edited(self):
    #     self.signal.sigVideoDirectoryChanged.emit(self.ui.lineEdit_path_dst_camera.text)
    #
    # def photos_directory_edited(self):
    #     self.signal.sigPhotosDirectoryChanged.emit(self.ui.lineEdit_path_dst_photos.text)

    def auto_find_source(self):
        if platform.system() == "Windows":
            dl = 'EFGHIJKLMNOPQRSTUVWXYZ'
            drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]
            if len(drives) == 1:
                self.signal.sigSourceDirectoryChanged.emit(drives[0])

        else:
            # todo: make linux port
            print "Feature not supported in linux. ~Soon~"
        

    def auto_find_destination_photos(self):
        pass

    def auto_find_destination_videos(self):
        pass

    def set_files_type(self, type):
        if type == "photo":
            self.files_type = "photo"
            self.media_files = self.found_photos
            self.media_files_strings = self.found_photos_strings
        elif type == "video":
            self.files_type = "video"
            self.media_files = self.found_videos
            self.media_files_strings = self.found_videos_strings
        else:
            raise Exception("Invalid file type!")

    def set_source_directory(self, path):
        # todo: put some assets here

        path = os.path.normpath(path)

        if os.path.isdir(str(path)):
            self.path_source = path
            self.ui.lineEdit_path_source.setText(path)
            self.ui.label_status_source.setText("<font color='green'>Ok!</font>")
        else:
            print u"Niepoprawny katalog źródłowy"

    def set_photos_directory(self, path):
        # todo: put some assets here
        path = os.path.normpath(path)

        if os.path.isdir(str(path)):
            self.path_destination_photos = path
            self.json["path_destination_photos"] = path
            self.ui.lineEdit_path_dst_photos.setText(path)
            self.ui.label_status_dst_photos.setText("<font color='green'>Ok!</font>")
        else:
            print u"Niepoprawny katalog zdjęć"

    def set_video_directory(self, path):
        # todo: put some assets here
        path = os.path.normpath(path)

        if os.path.isdir(str(path)):
            self.path_destination_videos = path
            self.json["path_destination_videos"] = path
            #todo : rename this lineedit to "video"
            self.ui.lineEdit_path_dst_videos.setText(path)
            self.ui.label_status_dst_video.setText("<font color='green'>Ok!</font>")
        else:
            print u"Niepoprawny katalog kamery"

    def open_choose_files_dialog(self):
        #sprawdz czy podano dane

        if not (os.path.isdir(self.path_destination_videos) and\
            os.path.isdir(self.path_destination_photos) and\
            os.path.isdir(self.path_source)):
            reply = QtGui.QMessageBox.critical(self, u"Uzupełnij dane",\
                u"Nie wszystkie dane zostały uzupełnione.",\
                QtGui.QMessageBox.Ok)
            return

        # Clean up
        self.files_type = ""
        self.found_videos = []
        self.found_photos = []
        self.found_photos_strings = []
        self.found_videos_strings = []

        #zaladuj nazwy i daty
        for root, dirs, files in os.walk(self.path_source):
            for name in files:
                if name.endswith(self.photos_file_types):
                    mf = MediaFile(path=os.path.join(root,name))
                    t =  mf.date
                    mf.type = "photo"
                    if mf.date is not None:
                        self.found_photos.append(mf)
                        self.found_photos_strings.append(name + "  " + time.strftime("%Y-%m-%d %H:%M", t))
                elif name.endswith(self.videos_file_types):
                    mf = MediaFile(path=os.path.join(root,name))
                    t =  mf.date
                    mf.type = "video"
                    if mf.date is not None:
                        self.found_videos.append(mf)
                        self.found_videos_strings.append(name + "  " + time.strftime("%Y-%m-%d %H:%M", t))


        if len(self.found_photos) == 0 and len(self.found_videos) == 0:
            reply = QtGui.QMessageBox.critical(self, u"Nie znaleziono plikow",\
                u"Przykto mi, ale nie znaleziono plików",\
                QtGui.QMessageBox.Ok)
            return
        elif len(self.found_photos) > 0 and len(self.found_videos) == 0:
            self.signal.sigFilesTypeChanged.emit("photo")
        elif len(self.found_videos) > 0 and len(self.found_photos) == 0:
            self.signal.sigFilesTypeChanged.emit("video")
        else:
            dlg = SelectTypeDialog(mw = self)
            dlg.show()
            dlg.exec_()

            if self.files_type != "photo" and self.files_type != "video":
                print "asdasdasd"
                return # no files type selected


        self.last_file = len(self.media_files) - 1
        #odpal

        a = ChooseDialog(mw = self)
        a.show()
        a.exec_()

    def open_copy_dialog(self):
        if not (os.path.isdir(self.path_destination_videos) and\
            os.path.isdir(self.path_destination_photos) and\
            os.path.isdir(self.path_source)):
            reply = QtGui.QMessageBox.critical(self, u"Uzupełnij dane",\
                u"Nie wszystkie dane zostały uzupełnione.",\
                QtGui.QMessageBox.Ok)
            return

        a = CopyDialog(mw = self)
        a.show()
        a.exec_()

    def open_source_directory_dialog(self):
        selected_dir = self.openFile(directory=True)[0]
        if os.path.isdir(selected_dir):
            self.signal.sigSourceDirectoryChanged.emit(selected_dir)

    def open_videos_directory_dialog(self):
        selected_dir = self.openFile(directory=True)[0]
        if os.path.isdir(selected_dir):
            self.signal.sigVideoDirectoryChanged.emit(selected_dir)

    def open_photos_directory_dialog(self):
        selected_dir = self.openFile(directory=True)[0]
        if os.path.isdir(selected_dir):
            self.signal.sigPhotosDirectoryChanged.emit(selected_dir)

    def openFile(self, directory = False):
        dialog = QtGui.QFileDialog()
        if directory:
            dialog.setFileMode(QtGui.QFileDialog.Directory)
            dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
        dialog.exec_()

        return dialog.selectedFiles()
Esempio n. 49
0
class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.grammar = Grammar()
        self.file_name = ''

        self.ui.parseGrammarButton.clicked.connect(self.on_parse_grammar_click)
        self.ui.transformGrammarButton.clicked.connect(self.on_transform_grammar_click)
        self.ui.actionNew.triggered.connect(self.on_new_click)
        self.ui.actionLoad.triggered.connect(self.on_load_click)
        self.ui.actionSave.triggered.connect(self.on_save_click)
        self.ui.actionSave_as.triggered.connect(self.on_save_as_click)
        self.ui.actionExit.triggered.connect(self.on_exit)

        self.ui.actionSave.setEnabled(False)

    def on_parse_grammar_click(self):
        self.grammar = Grammar()
        try:
            self.grammar.parse_from_text(str(self.ui.grammarTextEdit.toPlainText()))
            self.ui.grammarTextEdit.setText(self.grammar.to_plain_text())
            self.ui.statusLabel.setText("Parsing completed")
        except GrammarException as e:
            self.ui.statusLabel.setText(e.get_error_msg())

    def on_transform_grammar_click(self):
        try:
            self.grammar.parse_from_text(str(self.ui.grammarTextEdit.toPlainText()))
            self.grammar.transform_grammar()
            self.ui.grammarTextEdit.setText(self.grammar.to_plain_text())
            self.ui.statusLabel.setText("Transformation completed")
        except GrammarException as e:
            self.ui.statusLabel.setText(e.get_error_msg())

    def on_new_click(self):
        self.grammar = Grammar()
        self.file_name = ''
        self.ui.grammarTextEdit.clear()
        self.ui.actionSave.setEnabled(False)
        self.ui.statusLabel.clear()

    def on_load_click(self):
        file_name = QtGui.QFileDialog.getOpenFileName(self, 'Open file', filter="Grammar files (*.grm)")
        if file_name != '':
            f = open(file_name, 'r')
            self.ui.grammarTextEdit.setText(f.read())
            f.close()
            self.grammar = Grammar()
            self.file_name = file_name
            self.ui.actionSave.setEnabled(True)
            self.ui.statusLabel.clear()

    def on_save_click(self):
        f = open(self.file_name, 'w')
        f.write(str(self.ui.grammarTextEdit.toPlainText()))
        f.close()

    def on_save_as_click(self):
        file_name = QtGui.QFileDialog.getSaveFileName(self, 'Save to file', filter="Grammar files (*.grm)")
        if file_name != '':
            f = open(file_name, 'w')
            f.write(str(self.ui.grammarTextEdit.toPlainText()))
            f.close()
            self.file_name = file_name

    def on_exit(self):
        sys.exit(0)
Esempio n. 50
0
class Tagui(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.board = self.ui.board
        self.record = self.ui.record
        self.record.last_row = self.record.currentRow()

        self.engines = {}
        self.pos, _ = self.get_pos(0)
        self.mode = None

        #self.load_position('example_pos.ari')

    def on_actionLoadGame_triggered(self,checked=None):
        if checked is None: return 
        self.load_record()

    def on_actionLoadPosition_triggered(self,checked=None):
        if checked is None: return 
        self.load_position()

    def on_actionSavePosition_triggered(self,checked=None):
        if checked is None: return 
        self.save_position()

    def on_actionNewGame_triggered(self,checked=None):
        if checked is None: return 
        self.board.update_pos(self.make_empty_pos())
        self.record.clear()
        self.board.mode = MODE_PLAY
        

    def on_actionExit_triggered(self,checked=None):
        quit()

    def load_record(self, fn=None):
        if not fn:
            fd = QtGui.QFileDialog(self)
            fn = fd.getOpenFileName()
        if isfile(fn):
            self.record.clear()
            self.record.addItem('record')
            self.record.addItems(open(fn).readlines())
            self.record.setSelectionMode(self.record.SingleSelection)
            self.record.setCurrentRow(0)
            self.board.mode = MODE_REPLAY

    def load_position(self, fn=None):
        if not fn:
            fd = QtGui.QFileDialog(self)
            fn = fd.getOpenFileName()
        if isfile(fn):
            self.record.clear()
            lines = open(fn).readlines()
            lines[0] = lines[0].replace('s', 'b').replace('g', 'w')
            _, self.pos = board.parse_long_pos(lines)
            self.board.update_pos(self.pos)
            self.board.mode = MODE_PLAY

    def save_position(self, fn=None):
        if not self.pos:
            return 
        
        if not fn:
            dialog = QtGui.QFileDialog(self)
            fn = dialog.getSaveFileName()
            
            fd = open(fn, 'w')

            row = int(self.record.currentRow())/2 or 0
            row += 1
            fd.write("%s%s\n" % (row, ['w', 'b'][self.pos.color]))
            fd.write(self.pos.to_long_str())
            fd.write("\n")
            fd.close()

    def add_engine(self, name, cmd):
        self.engines[name] = EngineController(StdioEngine(cmd, None))
        
    def on_button_back_clicked(self, checked=None):
        if checked is None: return
        row = self.record.currentRow() 
        assert row > 0, "cannot go back"
        self.record.setCurrentRow(row - 1)
        
    def on_button_forward_clicked(self, checked=None):
        if checked is None: return

    def add_engine(self, name, cmd):
        self.engines[name] = EngineController(StdioEngine(cmd, None))
        
    def on_button_back_clicked(self, checked=None):
        if checked is None: return
        row = self.record.currentRow() 
        assert row > 0, "cannot go back"
        self.record.setCurrentRow(row - 1)
        
    def on_button_forward_clicked(self, checked=None):
        if checked is None: return
        row = self.record.currentRow() 
        assert row < self.record.count() - 1, "cannot go forward"
        self.record.blockSignals(True) 
        row += 1
        self.record.setCurrentRow(row)
        self.record.blockSignals(False) 
        self.start_move_animation(row)
        self.record_update()

    def on_record_currentRowChanged(self):
        row = self.record.currentRow()
        if row + 1 == self.record.count():
            return
        if row - self.record.last_row == 1: 
            self.start_move_animation(row)
            self.record_update()
            return
        self.pos, _ = self.get_pos(row)
        self.board.update_pos(self.pos)
        self.record_update()

    def record_update(self):
        row = self.record.currentRow()
        self.record.last_row = row
        self.ui.button_back.setEnabled(True)
        self.ui.button_forward.setEnabled(True)
        if row == 0: 
            self.ui.button_back.setEnabled(False)
        if row >= self.record.count() - 1:
            self.ui.button_forward.setEnabled(False)

    def make_empty_pos(self):
        bitboards = list([list(x) for x in board.BLANK_BOARD])
        return board.Position(board.COL_GOLD, 4, bitboards)

    def get_pos(self, row, separate_last_move=False):
        moves = map(lambda x: str(x.text()).strip(), [self.record.item(index) for index in xrange(1, row + 1)])
        pos = self.make_empty_pos()
        if row == 0: #moves == ['record'] or moves == []:
            return pos, []

        if not separate_last_move:
            moves.append(' ')

        moves = map(lambda x: x[x.find(' ') + 1:], moves)
        for m in moves[:-1]: 
            try: 
                steps = board.parse_move(m)
                pos = pos.do_move(steps)
            except ValueError:
                break

        return pos, moves[-1]

    def start_move_animation(self, move_num):
        self.pos, _ = self.get_pos(move_num)
        pos, last_move = self.get_pos(move_num, separate_last_move=True)
        self.board.update_pos(pos)
        if last_move: 
            steps = board.parse_move(last_move)
            self.board.start_move_animation(steps)

    def start_search(self, name):
        self.engines[name].newgame()
        #self.engines[name].setoption('tcmove', '%s' % self.engine.ttm )
        self.engines[name].setposition(self.pos)
        self.engine.go() 

        while True:
            resp = self.engine.get_response()
            if resp.type == "bestmove":
                resp.message = resp.move
            if resp.type == "log":
                if resp.message.split(' ')[-1] == "over":
                    break

    def __del__(self): 
        for engine in self.engines.values():
            engine.quit()
            engine.cleanup()
Esempio n. 51
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self,None, QtCore.Qt.WindowStaysOnTopHint)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.line_date.setText(str(symbol_date)+"R1")
        self.ui.line_info.installEventFilter(self)
        
        for n in range(1, 17):
            label = self.ui.__getattribute__('label_' + str(n))
            label.mousePressEvent = left_click(label.mousePressEvent, label)
            try:
                QtCore.QObject.connect(label, QtCore.SIGNAL('leftClicked()'), self.__getattribute__('link_activation_'+str(n)))
            except:
                print "Link not found at label position -",str(n)
            
        
        QtCore.QObject.connect(self.ui.line_info, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.info_changed )
        QtCore.QObject.connect(self.ui.btn_clean, QtCore.SIGNAL(_fromUtf8("clicked()")), self.list_clean )
        QtCore.QObject.connect(self.ui.btn_label, QtCore.SIGNAL(_fromUtf8("clicked()")), self.label_creation)
        QtCore.QObject.connect(self.ui.line_info, QtCore.SIGNAL(_fromUtf8("returnPressed()")), self.list_clean)
        QtCore.QObject.connect(self.ui.list_mail, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem*)")), self.mail_selection)
        QtCore.QObject.connect(self.ui.list_size, QtCore.SIGNAL(_fromUtf8("itemClicked(QListWidgetItem*)")), self.size_selection)
        QtCore.QObject.connect(self.ui.comboBox, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.box_selection)
        
        
    activation=lambda self,x,y: self.link_activation(x,y)
    
    # shit code !!! be carefull!
    def link_activation_1(self):
        self.activation(linked_item[0][0],linked_item[0][1],) 
    def link_activation_2(self):
        self.activation(linked_item[1][0],linked_item[1][1],)
    def link_activation_3(self):
        self.activation(linked_item[2][0],linked_item[2][1],)    
    def link_activation_4(self):
        self.activation(linked_item[3][0],linked_item[3][1],)    
    def link_activation_5(self):
        self.activation(linked_item[4][0],linked_item[4][1],)    
    # def for 6 not supported! combo box!  
    def link_activation_7(self):
        self.activation(linked_item[5][0],linked_item[5][1],)    
    def link_activation_8(self):
        self.activation(linked_item[6][0],linked_item[6][1],)    
    def link_activation_9(self):
        self.activation(linked_item[7][0],linked_item[7][1],)    
    def link_activation_10(self):
        self.activation(linked_item[8][0],linked_item[8][1],)    
    def link_activation_11(self):
        self.activation(linked_item[9][0],linked_item[9][1],)    
    def link_activation_12(self):
        self.activation(linked_item[10][0],linked_item[10][1],)    
    def link_activation_13(self):
        self.activation(linked_item[11][0],linked_item[11][1],)
    def link_activation_14(self):
        self.activation(linked_item[12][0],linked_item[12][1],) 
    def link_activation_15(self):
        self.activation(linked_item[13][0],linked_item[13][1],) 
    def link_activation_16(self):
        self.activation(linked_item[14][0],linked_item[14][1],) 

        
    def link_activation(self,label,line):

        label = self.ui.__getattribute__('label_' + str(label))
        obj_text = self.ui.__getattribute__(line)
        
        print label.text(),label.objectName()

        try:
            item_text=str(obj_text.text())
        except:
            item_text=str(obj_text.toPlainText())
                
        myClipBoard.setText(_fromUtf8(item_text),QtGui.QClipboard.Clipboard)
        clipboard_text= myClipBoard.text("plain",QtGui.QClipboard.Selection)
        print 'copy',item_text
        self.ui.statusBar.showMessage('Successfully copied!',1000)


    def eventFilter(self, object, event):
        if (object is self.ui.line_info):
            if (event.type() == QtCore.QEvent.DragEnter):
                if event.mimeData().hasUrls():
                    event.accept()   # must accept the dragEnterEvent or else the dropEvent can't occur !!!
                    print "accept"
                else:
                    event.ignore()
                    print "ignore"
            if (event.type() == QtCore.QEvent.Drop):
                if event.mimeData().hasUrls():   # if file or link is dropped
                    urlcount = len(event.mimeData().urls())  # count number of drops
                    url_list = event.mimeData().urls()  #[0] get first url
                    for url in url_list:
                        try:
                            path=str(url.toString())[8:].decode(sys.getdefaultencoding())
                        except:
                            pass
                        try:    
                            size='{:,}'.format(os.path.getsize(path))
                            file_name=os.path.basename(path)
                            binary_size[file_name]=size
                            self.ui.list_size.addItem(file_name+" : "+size+" Bytes")
                                                    
                            print file_name+" : "+size+" Bytes"
                        except:
                            print "Drop file failed"

            return False # lets the event continue to the edit
        return False  

    def label_creation(self):
        from base64 import b16encode as e1, b32encode as e3, b64encode as e6
        open('temp.data','w').close()
        f=open('temp.data','a')
        try:
            child.kill(shell=None)
        except:
            print 'Child label not started!'
        
        save_to_file= (
               self.ui.line_project.text(),
               self.ui.line_code.text(),
               self.ui.line_csc.text(),
               self.ui.line_modem.text(),
               self.ui.line_template.text(),
               self.ui.line_full.text(),
               self.ui.line_partial.toPlainText() ,
               self.ui.line_approver.text(),
               self.ui.line_p4port.text(),
               self.ui.label_name.toPlainText(),
               str(self.ui.comboBox.currentText()),
               )
        
        [f.write(e1(e3(e6(str(line))))[::-1]+'\n') for line in save_to_file]
        f.close()
        try:
            child=subprocess.Popen('start main_label', shell=None) #for exe
            #child=subprocess.Popen('python main_label.py', shell=None)
        except:
           child= subprocess.Popen('main_label')
        '''   
        finally:
           child= subprocess.Popen('python main_label.py') '''
            
        print "Saved to file temp.data!"

    def box_selection(self):
        bin_type=str(self.ui.comboBox.currentText())
        try:
            self.ui.line_template.setText(p4[bin_type]["Path/Template"])
            self.ui.line_p4port.setText(p4[bin_type]["Server"])
            self.ui.line_full.setText(p4[bin_type]["Full"])
            self.ui.line_partial.setPlainText(p4[bin_type]["Partials"])
        except:
            print u"\nFail in Bin Type fields insert \n"
        print self.ui.comboBox.currentText()
        
        self.label_insert(project,model,info_text)
        
    def label_insert(self,project,model,info_text):
        
        bin_type=str(self.ui.comboBox.currentText()) #get current box str
        fget_label_new(info_text,model)                   # find labels in text
        for bins in p4["LABEL_MARK"]:
        
            # check label presence
            
            if model[:-2] in p4["LABEL"]:
                self.ui.label_name.setPlainText("\n".join(p4["LABEL"][bin_type]))
                
            if model not in p4["LABEL"][bin_type]:
                for bins in p4["LABEL_MARK"]:
                    if bin_type == bins:
                        for label_version in p4[bin_type]["VERSION"]:
                            lab=project+"_"+label_version+"_"+str(symbol_date)+"R1_"+bin_type+"_OFFICIAL"
                            if lab not in p4["LABEL"][bin_type]:
                                p4["LABEL"][bin_type].append(lab)
        # if
        self.ui.label_name.setPlainText("\n".join(p4["LABEL"][bin_type]))
        self.ui.comboBox.setFocus()
        
    def info_changed(self):
        global project,model,info_text
        p4["LABEL"]={"CODE":[],"CSC":[],"MODEM":[]}
        p4["LABEL_MARK"]=[]
        info_text=''
        for symbol in self.ui.line_info.text():
            try:
                info_text+=str(symbol).decode(sys.getdefaultencoding())
            except:
                pass
            
        fget_p4_path_port(info_text)
        fget_full_partials(info_text)
                
        if "Recipients\t" in info_text or "samsung.com" in info_text: # get id for mail list from parcing 
            for i in mail_list(info_text):   
                self.ui.list_mail.addItem(str(i))
                
        if "Project\t" in info_text or "SM-" in info_text or "GT-" in info_text: # get project name from parcing 
            project=fget_project(info_text)
            model=(project.split("_")[0]).split("-")[-1]
            print model
            self.ui.line_project.setText(project)
            
        if "Approval User\t" in info_text and ")" in info_text:
            info_approver=fget_approver(info_text)
            self.ui.line_user.setText(info_approver[0])
            self.ui.line_approver.setText(info_approver[1])
            
        if "Project Manager\t" in info_text and ")" in info_text:
            self.ui.line_manager.setText(fget_manager(info_text))
        
        if "Code Version" in info_text or "CSC Version" in info_text or "CP Version" in info_text:
            
            fget_versions(info_text)
            fversion_name_correction(model)
            fget_label_new(info_text, model)
            print p4["LABEL"]

            fmake_smd_name()
 
            self.ui.line_code.setText(", ".join(p4["CODE"]["VERSION"]))
            self.ui.line_csc.setText(", ".join(p4["CSC"]["VERSION"]))
            self.ui.line_modem.setText(", ".join(p4["MODEM"]["VERSION"]))
            
            self.ui.line_smd.setPlainText("\n".join(p4["SMD_NAME"]))
            self.ui.line_smd_home.setPlainText("\n".join(p4["SMD_NAME_HOME"]))

            
        self.box_selection()
        
        self.label_insert(project,model,info_text)
        
        #print p4
        self.ui.line_info.clear()
 
    def size_selection(self):
        if self.ui.list_size.currentItem().text()!="Select all":
            item_text=self.ui.list_size.currentItem().text()
            myClipBoard.setText(item_text,QtGui.QClipboard.Clipboard)
            clipboard_text= myClipBoard.text("plain",QtGui.QClipboard.Selection)
            print item_text
        else:        
            size_list=''
            for i in xrange(self.ui.list_size.count()):
                size_list+=self.ui.list_size.item(i).text()+"\n"
            size_list.replace("Select all\n",'')
            print size_list,"-"*60
            
            myClipBoard.setText(size_list,QtGui.QClipboard.Clipboard)
            clipboard_text= myClipBoard.text("plain",QtGui.QClipboard.Selection)
            print clipboard_text  
        
    def mail_selection(self):
        if self.ui.list_mail.currentItem().text()!="Select all":
            item_text=self.ui.list_mail.currentItem().text()
            myClipBoard.setText(item_text,QtGui.QClipboard.Clipboard)
            clipboard_text= myClipBoard.text("plain",QtGui.QClipboard.Selection)
            print item_text
        else:        
            mail_list=''
            for i in xrange(self.ui.list_mail.count()):
                mail_list+=self.ui.list_mail.item(i).text()+";"
            mail_list.replace("Select all;",'')
            print mail_list
            myClipBoard.setText(mail_list,QtGui.QClipboard.Clipboard)
            clipboard_text= myClipBoard.text("plain",QtGui.QClipboard.Selection)
            print clipboard_text        
      
    def list_clean(self):
        self.ui.list_mail.clear()
        self.ui.list_mail.addItem("Select all")
        self.ui.list_size.clear()
        self.ui.list_size.addItem("Select all") 
Esempio n. 52
0
class IPBA2(QtGui.QMainWindow):

	def __init__(self):
		super(IPBA2, self).__init__(None)
		
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
	
		# set to NONE if no backup is loaded
		# and check its noneness to lock analysis functions
		self.backup_path = None
	
		#self.openBackup()
		
		self.loadPlugins()
		
		QtCore.QObject.connect(self.ui.fileTree, QtCore.SIGNAL("itemSelectionChanged()"), self.onTreeClick)
		
		self.ui.fileTree.setColumnWidth(0,200)
		self.ui.fileTree.setColumnWidth(2,16)
		
		self.ui.fileTree.setColumnHidden(1,True)
		self.ui.fileTree.setColumnHidden(3,True)
		
		self.ui.imagePreviewLabel.hide()
		
		# File menu
		QtCore.QObject.connect(self.ui.menu_openarchive, QtCore.SIGNAL("triggered(bool)"), self.openBackup)
		QtCore.QObject.connect(self.ui.menu_closearchive, QtCore.SIGNAL("triggered(bool)"), self.closeBackup)
		
		# About menu
		QtCore.QObject.connect(self.ui.actionAbout, QtCore.SIGNAL("triggered(bool)"), self.about)
		
		# attach context menu to rightclick on elements tree
		self.ui.fileTree.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.ui.fileTree, QtCore.SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)	
		
		# toolbar bindings
		self.ui.actionNext.triggered.connect(self.nextWindow)
		self.ui.actionPrev.triggered.connect(self.prevWindow)
		self.ui.actionTile.triggered.connect(self.tileWindow)
		
		self.ui.actionToggleRight.triggered.connect(self.toggleRight)
		self.showRightSidebar = True
		
		# show about window on startup
		self.about()
		
	# toggle right sidebar
	def toggleRight(self):
		
		sidebarObjects = [self.ui.fileInfoText, self.ui.imagePreviewLabel, self.ui.label_4]
	
		if (self.showRightSidebar == True):
			self.showRightSidebar = False
			for sidebarObject in sidebarObjects:
				sidebarObject.hide()
		else:
			self.showRightSidebar = True
			for sidebarObject in sidebarObjects:
				sidebarObject.show()			
		

	def about(self):
	
		newWidget = AboutWindow()
		subWindow = QtGui.QMdiSubWindow()
		subWindow.setWidget(newWidget)
		subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.ui.mdiArea.addSubWindow(subWindow)
		subWindow.show()		

		
	def loadPlugins(self):
	
		pluginsPackage = "ipba2-plugins"
	
		print("\n**** Loading plugins...")
		self.pluginsList = []
		
		pluginsdir = os.path.join(os.path.dirname(__file__), pluginsPackage)
		print("Loading plugins from dir: %s"%pluginsdir)
		
		for module in os.listdir(pluginsdir):
			if module[-3:] != '.py' or module[0:4] != "plg_":
				continue
			modname = pluginsPackage + "." + module[:-3]
			
			# check whether module can be imported
			try:
				__import__(modname)
			except:
				self.error("Error while trying to load plugin file: %s"%modname)
				continue

			# check whether module has PLUGIN_NAME() method (optional)
			try:
				moddescr = getattr(sys.modules[modname], "PLUGIN_NAME")
				print("Loading plugin: %s - %s..."%(modname, moddescr))
			except:
				print("Loading plugin: %s - (name not available)..."%modname)
				print(sys.exc_info())
				moddescr = modname
			
			# check whether module has main() method
			try:
				getattr(sys.modules[modname], "main")
				hasMain = True
			except:
				hasMain = False	

			# add entry to plugins menu
			if (hasMain):
				entry = self.ui.menuPlugins.addAction(moddescr)
				self.connect(entry, QtCore.SIGNAL('triggered()'), 
					lambda modname=modname: self.runPlugin(modname))
				print("- window")

			# check whether module has report() method
			try:
				getattr(sys.modules[modname], "report")
				hasReport = True
			except:
				hasReport = False	

			# add entry to reports menu
			if (hasReport):
				entry = self.ui.menuReports.addAction(moddescr)
				self.connect(entry, QtCore.SIGNAL('triggered()'), 
					lambda modname=modname: self.runReport(modname))
				print("- report")
			
			if (hasReport == False and hasMain == False):
				print("- Error: plugin %s has no useful method."%(modname))
				continue
			
				
	def runPlugin(self, modname):
		
			if (self.backup_path == None):
				return
				
			# check if plugin already open
			alreadyOpenWindows = self.ui.mdiArea.subWindowList()
			for openWindow in alreadyOpenWindows:
				if (openWindow.widget().__class__.__name__ in dir(sys.modules[modname])):
					self.ui.mdiArea.setActiveSubWindow(openWindow)
					return
	
			try:
				mainMethod = getattr(sys.modules[modname], 'main')
				newWidget = mainMethod(self.cursor, self.backup_path)
			except:
				self.error("Unable to run plugin %s"%modname)
				return
			
			if (newWidget == None):
				return
				
			subWindow = QtGui.QMdiSubWindow()
			subWindow.setWidget(newWidget)
			subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)
			self.ui.mdiArea.addSubWindow(subWindow)
			subWindow.show()		

	def runReport(self, modname): # mario piccinelli, fabio sangiacomo
	
			if (self.backup_path == None):
				return
	
			# getting report method from selected plugin
			try:
				reportMethod = getattr(sys.modules[modname], 'report')
				contentString, files = reportMethod(self.cursor, self.backup_path)
			except:
				self.error("Unable to run report function in %s"%modname)
				return
			
			# builds page header
			headerString = ""
			headerString += '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n'
			headerString += '"http://www.w3.org/TR/html4/loose.dtd">\n'
			headerString += '<html><head><title>WhatsAppBrowser</title>\n'
			headerString += '<meta name="GENERATOR" content="iPBA WhatsApp Browser">\n'
			# adds page style
			headerString += html_util.css_style
			# adds javascript to make the tables sortable
			headerString += '\n<script type="text/javascript">\n'
			headerString += html_util.sortable
			headerString += '</script>\n\n'
			headerString += '</head><body>\n'
			
			filename = QtGui.QFileDialog.getSaveFileName(self, "Report file", modname.split(".")[-1].split("_")[-1], ".html")		
			filename = filename[0]
			
			if (len(filename) == 0):
				return
			
			# manage external resources for reports
			if (files):
				
				if (len(files)>0):
				
					# create path for resources
					resourcesIndex = 0
					baseResourcesPath = modname.split(".")[-1].split("_")[-1]
					resourcesPath = os.path.join(os.path.dirname(filename), )
					while (os.path.isdir(resourcesPath)):
						resourcesIndex += 1
						resourcesPath = os.path.join(os.path.dirname(filename), "%s%03i"%(baseResourcesPath, resourcesIndex))
					os.makedirs(resourcesPath)
				
					# copy files in resource path
					# each file is [effective-filename-with-abs-path, realfilename.ext]
					for file in files:					
						shutil.copyfile(file[0], os.path.join(resourcesPath, file[1]))
						
					# in report body, overwrites each occurrence of $IPBA2RESOURCESPATH$ with the real name of the resources dir
					contentString = contentString.replace("$IPBA2RESOURCESPATH$", "%s%03i"%(baseResourcesPath, resourcesIndex))
			
			# finish building output
			returnString = headerString + contentString + "</body></html>"			
			
			# write output
			try:
				file = open(filename, 'w')
				file.write(returnString)
				file.close()
			except:
				self.error("Error while trying to write report file.")


	def error(self, text):
		msgBox = QtGui.QMessageBox()
		msgBox.setText(text)
		
		detailedText = "Type: %s"%sys.exc_info()[0].__name__
		detailedText += "\nDescription: %s"%str(sys.exc_info()[1])
		detailedText += "\nFile: %s"%os.path.split(sys.exc_info()[2].tb_frame.f_code.co_filename)[1]
		detailedText += "\nLine: %s"%str(sys.exc_info()[2].tb_lineno)
		
		msgBox.setDetailedText(detailedText)
		msgBox.exec_()		
		
		
	def openBackup(self):
		newBackupPath = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", "", QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks);
		
		if (newBackupPath == None):
			return

		if (len(newBackupPath) == 0):
			return
		
		self.backup_path = newBackupPath
		
		# clear main UI
		self.ui.backupInfoText.clear()
		self.ui.fileInfoText.clear()
		self.ui.imagePreviewLabel.clear()
		self.ui.fileTree.clear()
		self.ui.mdiArea.closeAllSubWindows()
		
		# attempt to repair db files (windows only, user can cancel)
		answer = self.repairDBFiles()
		if (answer == False):
			self.backup_path = None
			return
		
		# open archive path	
		self.readBackupArchive()


	def closeBackup(self):
		self.backup_path = None
		
		# clear main UI
		self.ui.backupInfoText.clear()
		self.ui.fileInfoText.clear()
		self.ui.imagePreviewLabel.clear()
		self.ui.fileTree.clear()
		self.ui.mdiArea.closeAllSubWindows()


	def nextWindow(self):
		self.ui.mdiArea.activateNextSubWindow()
	def prevWindow(self):
		self.ui.mdiArea.activatePreviousSubWindow()
	def tileWindow(self):
		self.ui.mdiArea.tileSubWindows()

	# builds context menu
	def ctxMenu(self, pos):

		# managing "standard" files
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return

		if (currentSelectedElement.text(1) == "X"):	
			realFileName = os.path.join(self.backup_path, currentSelectedElement.text(0))
		
		else:
			data = self.getSelectedFileData()
			if (data == None): return
			realFileName = os.path.join(self.backup_path, data['fileid'])
		
		filemagic = self.readMagic(realFileName)
		
		showMenu = False
		
		menu =  QtGui.QMenu();
		
		# if sqlite
		if (filemagic.partition("/")[2] == "sqlite"):
			action1 = QtGui.QAction("Open with SQLite Browser", self)
			action1.triggered.connect(self.openSelectedSqlite)
			menu.addAction(action1)
			showMenu = True

		# if ASCII
		if (filemagic.partition("/")[0] == "text"):
			action1 = QtGui.QAction("Open with ASCII Viewer", self)
			action1.triggered.connect(self.openSelectedText)
			menu.addAction(action1)
			showMenu = True

		# if image
		if (filemagic.partition("/")[0] == "image"):
			action1 = QtGui.QAction("Open with Image Viewer", self)
			action1.triggered.connect(self.openSelectedImage)
			menu.addAction(action1)
			showMenu = True

		# if binary plist
		if (filemagic.partition("/")[2] == "binary_plist" or filemagic.partition("/")[2] == "plist"):
			action1 = QtGui.QAction("Open with Plist Viewer", self)
			action1.triggered.connect(self.openSelectedPlist)
			menu.addAction(action1)
			showMenu = True
	
		# if HEX (in any case)
		if True:
			action1 = QtGui.QAction("Open with Hex Viewer", self)
			action1.triggered.connect(self.openSelectedHex)
			menu.addAction(action1)
			showMenu = True
			
		# export (any file)
		if True:
			action1 = QtGui.QAction("Export", self)
			action1.triggered.connect(self.exportSelectedFile)
			menu.addAction(action1)
			showMenu = True			
		
		if (showMenu):
			menu.exec_(self.ui.fileTree.mapToGlobal(pos));
	
	# CONTEXT MENU ACTIONS --------------------------------------------------------------------------
	
	def openSelectedSqlite(self):
		
		element = self.getSelectedFileData()
		if (element == None): return
		
		realFileName = os.path.join(self.backup_path, element['fileid'])
	
		newWidget = SqliteWidget(realFileName)
		newWidget.setTitle(element['file_name'] + " - SQLite Browser")
#		self.ui.mdiArea.addSubWindow(newWidget, QtCore.Qt.SubWindow)
#		newWidget.show()
		subWindow = QtGui.QMdiSubWindow()
		subWindow.setWidget(newWidget)
		subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.ui.mdiArea.addSubWindow(subWindow)
		subWindow.show()
		
	def openSelectedPlist(self):
		
		# managing "standard" files
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return

		if (currentSelectedElement.text(1) == "X"):	
			realFileName = os.path.join(self.backup_path, currentSelectedElement.text(0))
			title = currentSelectedElement.text(0) + " - Plist Viewer"
		else:
			element = self.getSelectedFileData()
			if (element == None): return
			realFileName = os.path.join(self.backup_path, element['fileid'])
			title = element['file_name'] + " - Plist Viewer"
	
		newWidget = PlistWidget(realFileName)
		newWidget.setTitle(title)
#		self.ui.mdiArea.addSubWindow(newWidget, QtCore.Qt.SubWindow)
#		newWidget.show()
		subWindow = QtGui.QMdiSubWindow()
		subWindow.setWidget(newWidget)
		subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.ui.mdiArea.addSubWindow(subWindow)
		subWindow.show()

	def openSelectedImage(self):
		
		element = self.getSelectedFileData()
		if (element == None): return
		
		realFileName = os.path.join(self.backup_path, element['fileid'])
	
		newWidget = ImageWidget(realFileName)
		newWidget.setTitle(element['file_name'] + " - Image Viewer")
#		self.ui.mdiArea.addSubWindow(newWidget, QtCore.Qt.SubWindow)
#		newWidget.show()	
		subWindow = QtGui.QMdiSubWindow()
		subWindow.setWidget(newWidget)
		subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.ui.mdiArea.addSubWindow(subWindow)
		subWindow.show()
			
	def openSelectedHex(self):
	
		# managing "standard" files
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return

		if (currentSelectedElement.text(1) == "X"):	
			realFileName = os.path.join(self.backup_path, currentSelectedElement.text(0))
			title = currentSelectedElement.text(0) + " - Hex editor"
		else:
			element = self.getSelectedFileData()
			if (element == None): return
			realFileName = os.path.join(self.backup_path, element['fileid'])
			title = element['file_name'] + " - Hex editor"
	
		newWidget = HexWidget(realFileName)
		newWidget.setTitle(title)
#		self.ui.mdiArea.addSubWindow(newWidget, QtCore.Qt.SubWindow)
#		newWidget.show()
		subWindow = QtGui.QMdiSubWindow()
		subWindow.setWidget(newWidget)
		subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.ui.mdiArea.addSubWindow(subWindow)
		subWindow.show()
			
	def openSelectedText(self):
	
		# managing "standard" files
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return

		if (currentSelectedElement.text(1) == "X"):	
			realFileName = os.path.join(self.backup_path, currentSelectedElement.text(0))
			title = currentSelectedElement.text(0) + " - Text Viewer"
		else:
			element = self.getSelectedFileData()
			if (element == None): return
			realFileName = os.path.join(self.backup_path, element['fileid'])
			title = element['file_name'] + " - Text Viewer"
	
		newWidget = TextWidget(realFileName)
		newWidget.setTitle(title)
#		self.ui.mdiArea.addSubWindow(newWidget, QtCore.Qt.SubWindow)
#		newWidget.show()
		subWindow = QtGui.QMdiSubWindow()
		subWindow.setWidget(newWidget)
		subWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.ui.mdiArea.addSubWindow(subWindow)
		subWindow.show()
			
	def exportSelectedFile(self):
	
		# managing "standard" files
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return

		if (currentSelectedElement.text(1) == "X"):	
			realFileName = os.path.join(self.backup_path, currentSelectedElement.text(0))
			newName = currentSelectedElement.text(0)
		else:
			element = self.getSelectedFileData()
			if (element == None): return
			realFileName = os.path.join(self.backup_path, element['fileid'])
			newName = element['file_name']
	
		exportPath = QtGui.QFileDialog.getExistingDirectory(self, "Select export path", "", QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks);
		if (len(exportPath) == 0): return
		
		try:
			shutil.copy(realFileName, os.path.join(exportPath, newName))
			QtGui.QMessageBox.about(self, "Confirm", "File exported in %s."%exportPath)
		except:
			self.error("Error while exporting file.")
			
	#-----------------------------------------------------------------------------------------------

	# Repairs sqlite files (windows only) by Fabio Sangiacomo <*****@*****.**> 
	
	def repairDBFiles(self):
	
		if os.name == 'nt':

			print "Checking SQLite files integrity (windows only)..."
		
			zipfilename = os.path.join(self.backup_path, 'original_files.zip')

			# skips this phase if original_files.zip is already present into backup_path
			if (os.path.exists(zipfilename) == 0):   
			
				reply = QtGui.QMessageBox.question(self, 'Repair database files', "On Windows platforms, the SQLite3 files in the iOS backup must be repaired before being read by iPBA2. The original files will be saved in a zip file named original_files.zip in the backup folder. Nonetheless it is STRONGLY advised to work on a copy of the backup dir, not on the original evidence. Are you sure you wanna continue?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
				if (reply == QtGui.QMessageBox.No):
					return False

				#------------------ reading file dir and checking magic for sqlite databases -------------------------------

				# list sqlite files to be repaired
				sqliteFiles = []
				backupFiles = os.listdir(self.backup_path)

				# starts progress window
				progress = QtGui.QProgressDialog("Searching for databases to repair...", "Abort", 0, len(backupFiles), self)
				progress.setWindowModality(QtCore.Qt.WindowModal)
				progress.setMinimumDuration(0)
				progress.show()
				QtGui.QApplication.processEvents()            	
				
				readCount = 0
				for backupFile in backupFiles:
					item_realpath = os.path.join(self.backup_path,backupFile)
					if (os.path.exists(item_realpath) == 0):
						continue	
					filemagic = magic.file(item_realpath)
					if (filemagic.partition("/")[2] == "sqlite"):
						sqliteFiles.append([backupFile, item_realpath])
					readCount += 1
					
					QtGui.QApplication.processEvents() 
					if (progress.wasCanceled()):
						return False
						
					progress.setValue(readCount)
				
				progress.setValue(progress.maximum())

				#------------------- converting sqlite files found in the previous step ----------------------------------

				# starts progress window
				progress = QtGui.QProgressDialog("Repairing databases...", "Abort", 0, len(sqliteFiles), self)
				progress.setWindowModality(QtCore.Qt.WindowModal)
				progress.setMinimumDuration(0)
				progress.setCancelButton(None)
				progress.show()
				QtGui.QApplication.processEvents()
		
				print '\nRepairing the databases ... '
				zf = zipfile.ZipFile(zipfilename, mode='w')
				
				convertedCount = 0
				for sqliteFile in sqliteFiles:
					fname = sqliteFile[0]
					item_realpath = sqliteFile[1]

					print("Repairing database: %s"%fname)

					# dump the database in an SQL text format (Temp.sql temporary file)
					os.system('echo .dump | sqlite3 "%s" > Temp.sql' % item_realpath)

					# saves the original file into the archive and releases the archive handle
					current = os.getcwd()
					os.chdir(self.backup_path)
					zf.write(fname)
					os.chdir(current)

					#Removes original file
					os.remove(item_realpath)

					#Overwrites the original file with the Temp.sql content
					os.system('echo .quit | sqlite3 -init Temp.sql "%s"' % item_realpath)

					#Removes temporary file
					if os.path.exists("Temp.sql"):
						os.remove("Temp.sql")
					
					# update progress bar
					convertedCount += 1
					progress.setValue(convertedCount)
					
					QtGui.QApplication.processEvents()

				progress.setValue(progress.maximum())
				
				zf.close()
				
				return True
			
			else:
				return True

	
	# return database ID of the currently selected element
	def getSelectedElementID(self):
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return None
		
		return currentSelectedElement.text(3)
		
	
	# return DB record for selected item
	def getSelectedElementData(self):
	
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return None,None
		
		item_id = currentSelectedElement.text(3)
	
		data = self.getElementFromID(item_id)
		if (data == None): return None,None

		item_type = currentSelectedElement.text(1)
		
		return data, item_type			
	
	
	# return DB record for selected item (only files "-")
	def getSelectedFileData(self):
		data, item_type = self.getSelectedElementData()
		if (data == None): return None
		if (item_type != '-'): return None
		return data
	
	
	FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])
	def hex2nums(self, src, length=8):
		N=0; result=''
		while src:
		   s,src = src[:length],src[length:]
		   hexa = ' '.join(["%02X"%ord(x) for x in s])
		   s = s.translate(self.FILTER)
		   N+=length
		   result += (hexa + " ")
		return result	


	def getElementFromID(self, id):
		query = "SELECT * FROM indice WHERE id = ?"
		self.cursor.execute(query, (id,))
		data = self.cursor.fetchone()
		
		if (data == None): return None
		
		if (len(data) == 0): 
			return None
		else:
			return data

	def readMagic(self, item_realpath):

		# check for existence 
		if (os.path.exists(item_realpath) == 0):
			return None
		
		# print file type (from magic numbers)
		filemagic = magic.file(item_realpath)
		return filemagic


	def openFile(self):

		element = self.getSelectedFileData()
		if (element == None): return
		
		realFileName = os.path.join(self.backup_path, element['fileid'])
		filemagic = self.readMagic(realFileName)
		
		# if sqlite file
		if (filemagic.partition("/")[2] == "sqlite"):
			newWidget = SqliteWidget(realFileName)
			newWidget.setTitle(element['file_name'] + " - SQLite Browser")
			self.ui.mdiArea.addSubWindow(newWidget)
			newWidget.show()
		
		# if graphics file
		elif (filemagic.partition("/")[0] == "image"):
			newWidget = ImageWidget(realFileName)
			newWidget.setTitle(element['file_name'] + " - Image Viewer")
			self.ui.mdiArea.addSubWindow(newWidget)
			newWidget.show()	
		
	
	def onTreeClick(self):
	
		# managing "standard" files
		currentSelectedElement = self.ui.fileTree.currentItem()
		if (currentSelectedElement): pass
		else: return

		if (currentSelectedElement.text(1) == "X"):	
			item_realpath = os.path.join(self.backup_path, currentSelectedElement.text(0))

			if (os.path.exists(item_realpath)):		
				self.ui.fileInfoText.clear()
				self.ui.fileInfoText.append("<strong>File</strong>: " + currentSelectedElement.text(0))
			
				filemagic = self.readMagic(item_realpath)
				self.ui.fileInfoText.append("")
				self.ui.fileInfoText.append("<strong>File type: </strong>" + filemagic)
				
			else:
				print("...troubles while opening file %s (does not exist)"%item_realpath)
			
			return
	
		data, item_type = self.getSelectedElementData()
		item_id = self.getSelectedElementID()
		if (data == None or item_id == None): return
		
		item_name = str(data['file_name'])
		item_permissions = str(data['permissions'])
		item_userid = str(data['userid'])
		item_groupid = str(data['groupid'])
		item_mtime = str(datetime.datetime.fromtimestamp(int(data['mtime'])))
		item_atime = str(datetime.datetime.fromtimestamp(int(data['atime'])))
		item_ctime = str(datetime.datetime.fromtimestamp(int(data['ctime'])))
		item_filecode = str(data['fileid'])
		item_link_target = str(data['link_target'])
		item_datahash = str(data['datahash'])
		item_flag = str(data['flag'])
		
		item_domain_type = str(data['domain_type'])
		item_domain = str(data['domain'])
		item_fullpath = str(data['file_path'])
		
		self.ui.fileInfoText.clear()
		
		self.ui.fileInfoText.append("<strong>File</strong>: " + item_name)
		self.ui.fileInfoText.append("<strong>Domain type</strong>: " + item_domain_type)
		self.ui.fileInfoText.append("<strong>Domain</strong>: " + item_domain)
		self.ui.fileInfoText.append("<strong>Full path</strong>: " + item_fullpath)
		self.ui.fileInfoText.append("")		
		self.ui.fileInfoText.append("<strong>Element type</strong>: " + item_type)
		self.ui.fileInfoText.append("<strong>Permissions</strong>: " + item_permissions)
		self.ui.fileInfoText.append("<strong>Data hash</strong>: " + item_datahash)
		self.ui.fileInfoText.append("<strong>User id</strong>: " + item_userid)
		self.ui.fileInfoText.append("<strong>Group id</strong>: " + item_groupid)
		self.ui.fileInfoText.append("<strong>Last modify time</strong>: " + item_mtime)
		self.ui.fileInfoText.append("<strong>Last access Time</strong>: " + item_atime)
		self.ui.fileInfoText.append("<strong>Creation time</strong>: " + item_ctime)
		self.ui.fileInfoText.append("<strong>File Key (obfuscated file name)</strong>: " + item_filecode)
		self.ui.fileInfoText.append("<strong>Flag</strong>: " + item_flag)

		# file properties (from properties table, which is data from mbdb file)
		query = "SELECT property_name, property_val FROM properties WHERE file_id = %s" % item_id
		self.cursor.execute(query)
		data = self.cursor.fetchall()
		if (len(data) > 0):
			self.ui.fileInfoText.append("")
			self.ui.fileInfoText.append("<strong>Element properties (from mdbd file)</strong>:")
			for element in data:
				self.ui.fileInfoText.append("%s: %s" %(element[0], element[1]))

		# treat sym links
		if (item_type == "l"):
			self.ui.fileInfoText.append("")
			self.ui.fileInfoText.append("<strong>This item is a symbolic link to another file.</strong>")
			self.ui.fileInfoText.append("<strong>Link Target</strong>: " + item_link_target)
			
		# treat directories
		if (item_type == "d"):
			self.ui.fileInfoText.append("")
			self.ui.fileInfoText.append("<strong>This item represents a directory.</strong>")		

		# cursor back at top left
		textCursor = self.ui.fileInfoText.textCursor() 
		textCursor.setPosition(0) 
		self.ui.fileInfoText.setTextCursor(textCursor) 	

		# if not file, stop here
		if (item_type != "-"): return
		
		# check file magic
		realFileName = os.path.join(self.backup_path, item_filecode)
		filemagic = self.readMagic(realFileName)
		self.ui.fileInfoText.append("")
		self.ui.fileInfoText.append("<strong>File type (from header data)</strong>: " + filemagic)

		# if image, draw preview
		view = self.ui.imagePreviewLabel
		if (filemagic.partition("/")[0] == "image"):
			pic = QtGui.QPixmap(realFileName).scaled(200, 200, QtCore.Qt.KeepAspectRatio)	
			view.setPixmap(pic) 
			if (self.showRightSidebar):
				view.show() 
		else:
			view.clear()
			view.hide()
	
	def readBackupArchive(self):
		
		self.backup_path = os.path.abspath(self.backup_path)

		# if exists Manifest.mbdx, then iOS <= 4
		iOSVersion = 5
		mbdxPath = os.path.join(self.backup_path, "Manifest.mbdx")
		if (os.path.exists(mbdxPath)):
			iOSVersion = 4
		
		# decode Manifest files
		mbdbPath = os.path.join(self.backup_path, "Manifest.mbdb")
		if (os.path.exists(mbdbPath)):
			mbdb = mbdbdecoding.process_mbdb_file(mbdbPath)
		else:
			#usage()
			print("\nManifest.mbdb not found in path \"%s\". Are you sure this is a correct iOS backup dir?\n"%(self.backup_path))
			sys.exit(1)
		
		# decode mbdx file (only iOS 4)
		if (iOSVersion == 4):
			mbdxPath = os.path.join(self.backup_path, "Manifest.mbdx")
			if (os.path.exists(mbdxPath)):
				mbdx = mbdbdecoding.process_mbdx_file(mbdxPath)
			else:
				#usage()
				print("\nManifest.mbdx not found in path \"%s\". Are you sure this is a correct iOS backup dir, and are you sure this is an iOS 4 backup?\n"%(self.backup_path))
				sys.exit(1)	

		# prepares DB
		database = sqlite3.connect(':memory:') # Create a database file in memory
		database.row_factory = sqlite3.Row
		self.cursor = database.cursor() # Create a cursor
		
		self.cursor.execute(
			"CREATE TABLE indice (" + 
			"id INTEGER PRIMARY KEY AUTOINCREMENT," +
			"type VARCHAR(1)," +
			"permissions VARCHAR(9)," +
			"userid VARCHAR(8)," +
			"groupid VARCHAR(8)," +
			"filelen INT," +
			"mtime INT," +
			"atime INT," +
			"ctime INT," +
			"fileid VARCHAR(50)," +
			"domain_type VARCHAR(100)," +
			"domain VARCHAR(100)," +
			"file_path VARCHAR(100)," +
			"file_name VARCHAR(100)," + 
			"link_target VARCHAR(100)," + 
			"datahash VARCHAR(100)," + 
			"flag VARCHAR(100)"
			");"
		)
		
		self.cursor.execute(
			"CREATE TABLE properties (" + 
			"id INTEGER PRIMARY KEY AUTOINCREMENT," +
			"file_id INTEGER," +
			"property_name VARCHAR(100)," +
			"property_val VARCHAR(100)" +
			");"
		)
		
		# starts progress window
		progress = QtGui.QProgressDialog("Reading backup...", "Abort", 0, 2*len(mbdb.items())/10, self)
		progress.setWindowModality(QtCore.Qt.WindowModal)
		progress.setMinimumDuration(0)
		progress.setCancelButton(None)
		progress.show()
		QtGui.QApplication.processEvents()
		
		# count items parsed from Manifest file
		items = 0;
		
		# populates database by parsing manifest file
		for offset, fileinfo in mbdb.items():
			
			# iOS 4 (get file ID from mbdx file)
			if (iOSVersion == 4):
			
				if offset in mbdx:
					fileinfo['fileID'] = mbdx[offset]
				else:
					fileinfo['fileID'] = "<nofileID>"
					print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
			
			# iOS 5 (no MBDX file, use SHA1 of complete file name)
			elif (iOSVersion == 5):
				fileID = hashlib.sha1()
				fileID.update("%s-%s"%(fileinfo['domain'], fileinfo['filename']) )
				fileinfo['fileID'] = fileID.hexdigest()	
		
			# decoding element type (symlink, file, directory)
			if (fileinfo['mode'] & 0xE000) == 0xA000: obj_type = 'l' # symlink
			elif (fileinfo['mode'] & 0xE000) == 0x8000: obj_type = '-' # file
			elif (fileinfo['mode'] & 0xE000) == 0x4000: obj_type = 'd' # dir
			
			# separates domain type (AppDomain, HomeDomain, ...) from domain name
			[domaintype, sep, domain] = fileinfo['domain'].partition('-');
			
			# separates file name from file path
			[filepath, sep, filename] = fileinfo['filename'].rpartition('/')
			if (type == 'd'):
				filepath = fileinfo['filename']
				filename = "";

			# Insert record in database
			query = "INSERT INTO indice(type, permissions, userid, groupid, filelen, mtime, atime, ctime, fileid, domain_type, domain, file_path, file_name, link_target, datahash, flag) VALUES(";
			query += "'%s'," 	% obj_type
			query += "'%s'," 	% mbdbdecoding.modestr(fileinfo['mode']&0x0FFF)
			query += "'%08x'," 	% fileinfo['userid']
			query += "'%08x'," 	% fileinfo['groupid']
			query += "%i," 		% fileinfo['filelen']
			query += "%i," 		% fileinfo['mtime']
			query += "%i," 		% fileinfo['atime']
			query += "%i," 		% fileinfo['ctime']
			query += "'%s'," 	% fileinfo['fileID']
			query += "'%s'," 	% domaintype.replace("'", "''")
			query += "'%s'," 	% domain.replace("'", "''")
			query += "'%s'," 	% filepath.replace("'", "''")
			query += "'%s'," 	% filename.replace("'", "''")
			query += "'%s'," 	% fileinfo['linktarget']
			query += "'%s'," 	% self.hex2nums(fileinfo['datahash']).replace("'", "''")
			query += "'%s'" 	% fileinfo['flag']
			query += ");"
			self.cursor.execute(query)
			
			# check if file has properties to store in the properties table
			if (fileinfo['numprops'] > 0):
		
				query = "SELECT id FROM indice WHERE "
				query += "domain = '%s' " % domain.replace("'", "''")
				query += "AND fileid = '%s' " % fileinfo['fileID']
				query += "LIMIT 1"
				 
				self.cursor.execute(query);
				id = self.cursor.fetchall()
				
				if (len(id) > 0):
					index = id[0][0]
					properties = fileinfo['properties']
					for property in properties.keys():
						query = "INSERT INTO properties(file_id, property_name, property_val) VALUES (";
						query += "'%i'," % index
						query += "'%s'," % property
						query += "'%s'" % self.hex2nums(properties[property]).replace("'", "''")
						query += ");"
						
						self.cursor.execute(query);
			
				#print("File: %s, properties: %i"%(domain + ":" + filepath + "/" + filename, fileinfo['numprops']))
				#print(fileinfo['properties'])
				
			# manage progress bar
			items += 1;
			if (items%10 == 0):
				progress.setValue(items/10)

		database.commit() 
		
		# print banner
		print("\nWorking directory: %s"%self.backup_path)
		print("Read elements: %i" %items)
		
		# add STANDARD files
		standardFiles = QtGui.QTreeWidgetItem(None)
		standardFiles.setText(0, "Standard files")
		self.ui.fileTree.addTopLevelItem(standardFiles)
		
		for elementName in ['Manifest.plist', 'Info.plist', 'Status.plist']:
			newItem = QtGui.QTreeWidgetItem(standardFiles)
			newItem.setText(0, elementName)
			newItem.setText(1, "X")
			self.ui.fileTree.addTopLevelItem(newItem)		

		# retrieve domain families
		self.cursor.execute("SELECT DISTINCT(domain_type) FROM indice");
		domain_types = self.cursor.fetchall()
		
		for domain_type_u in domain_types:
			
			domain_type = str(domain_type_u[0])
			
			newDomainFamily = QtGui.QTreeWidgetItem(None)
			newDomainFamily.setText(0, domain_type)
			
			self.ui.fileTree.addTopLevelItem(newDomainFamily)
			
			# show new domain family in main view
			QtGui.QApplication.processEvents()
			
			# retrieve domains for the selected family
			query = "SELECT DISTINCT(domain) FROM indice WHERE domain_type = \"%s\" ORDER BY domain" % domain_type
			self.cursor.execute(query);
			domain_names = self.cursor.fetchall()
			
			for domain_name_u in domain_names:
				domain_name = str(domain_name_u[0])			
				
				newDomain = QtGui.QTreeWidgetItem(newDomainFamily)
				newDomain.setText(0, domain_name)
				
				if (len(domain_names) > 1):
					self.ui.fileTree.addTopLevelItem(newDomain)
			
				# retrieve paths for selected domain
				query = "SELECT DISTINCT(file_path) FROM indice WHERE domain_type = \"%s\" AND domain = \"%s\" ORDER BY file_path" %(domain_type, domain_name)
				self.cursor.execute(query)
				paths = self.cursor.fetchall()
				
				for path_u in paths:
					path = str(path_u[0])
					
					if (len(domain_names) > 1):
						newPath = QtGui.QTreeWidgetItem(newDomain)
					else:
						newPath = QtGui.QTreeWidgetItem(newDomainFamily)
					
					newPath.setText(0, path)
					self.ui.fileTree.addTopLevelItem(newPath)
					
					# retrieve files for selected path
					query = "SELECT file_name, filelen, id, type FROM indice WHERE domain_type = \"%s\" AND domain = \"%s\" AND file_path = \"%s\" ORDER BY file_name" %(domain_type, domain_name, path)
					self.cursor.execute(query)
					files = self.cursor.fetchall()
					
					for file in files:
						file_name = str(file[0].encode("utf-8"))
						if (file[1]) < 1024:
							file_dim = str(file[1]) + " b"
						else:
							file_dim = str(file[1] / 1024) + " kb"
						file_id = int(file[2])
						file_type = str(file[3])

						newFile = QtGui.QTreeWidgetItem(newPath)
						newFile.setText(0, file_name)
						newFile.setToolTip(0, file_name)
						newFile.setText(1, file_type)
						newFile.setText(2, str(file_dim))
						newFile.setText(3, str(file_id))
						self.ui.fileTree.addTopLevelItem(newFile)
						
						# manage progress bar
						items = items + 1
						if (items%10 == 0):
							progress.setValue(items/10)

		
		deviceinfo = plistutils.deviceInfo(os.path.join(self.backup_path, "Info.plist"))
		for element in deviceinfo.keys():
			self.ui.backupInfoText.append("<strong>%s</strong>: %s"%(element, deviceinfo[element]))
		
		textCursor = self.ui.backupInfoText.textCursor() 
		textCursor.setPosition(0) 
		self.ui.backupInfoText.setTextCursor(textCursor) 
		
		# clear progressbar
		progress.setValue(progress.maximum())
Esempio n. 53
0
class MyMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def afterRun(self):
        self._employeeListNextUrl = None
        self._employeeListPrevUrl = None
        self.ui.statusBar.showMessage(u"Устанавливается соединение...")
        self._c = Connection("amihailov.pro", "/rtsup/api")
        self.employee_list_get_first_page()
        self.ui.statusBar.showMessage(u"Приложение успешно инициализировано", 1000)
        self.connectSignalsToSlots()

    def connectSignalsToSlots(self):
        self.ui.employeeListForwardButton.clicked.connect(self.employee_list_get_next_page)
        self.ui.employeeListBackButton.clicked.connect(self.employee_list_get_prev_page)
        self.ui.employeeListExistCheckbox.stateChanged.connect(self.employee_list_exist_changed)
        self.ui.employeeListTable.cellClicked.connect(self.employee_list_cell_clicked)
        self.ui.equipmentExistCheckbox.stateChanged.connect(self.equipment_exist_changed)
        self.ui.equipmentListBox.currentIndexChanged.connect(self.equipment_details_update)
        self.ui.tasksListBox.currentIndexChanged.connect(self.tasks_details_update)
        self.ui.taskEquipmentBox.currentIndexChanged.connect(self.tasks_equipment_details_update)
        self.ui.taskEquipmentAttachBox.currentIndexChanged.connect(self.tasks_equipment_attach_update)
        self.ui.taskEquipmentAttachButton.clicked.connect(self.attach_equipment_to_task)
        self.ui.taskEquipmentDetachButton.clicked.connect(self.detach_equipment_from_task)
        self.ui.newTaskButton.clicked.connect(self.publish_new_task)
        self.ui.exportToExcel.clicked.connect(self.export_to_excel)

    def reset_employee_list(self, data):
        succeed, employees = data
        if succeed:
            t = self.ui.employeeListTable
            t.clearContents()
            t.setRowCount(0)
            size = len(employees["objects"])
            t.setRowCount(size)
            for i in xrange(size):
                e = employees["objects"][i]
                t.setVerticalHeaderItem(i, QtGui.QTableWidgetItem("%d" % e["id"]))
                t.setItem(i, 0, QtGui.QTableWidgetItem(e["snils"]))
                t.setItem(i, 1, QtGui.QTableWidgetItem(e["name"]))
            t.resizeColumnsToContents()
            legend = self.ui.employeeListPageIndicator
            legend.setText(u"%d из %d" % (employees["meta"]["page"], employees["meta"]["total_pages"]))
            self._employeeListNextUrl = employees["meta"]["uri_next"]
            self._employeeListPrevUrl = employees["meta"]["uri_previous"]
        else:
            print "Cannot receive data"

    def employee_list_update_buttons(self):
        self.ui.employeeListForwardButton.setEnabled(self._employeeListNextUrl is not None)
        self.ui.employeeListBackButton.setEnabled(self._employeeListPrevUrl is not None)

    def employee_list_get_first_page(self, onlyExist=True):
        self.ui.statusBar.showMessage(u"Запрашивается первая страница списка сотрудников...")
        self.reset_employee_list(self._c.get_employee_list(exist=(1 if onlyExist else 0)))
        self.employee_list_update_buttons()
        self.ui.statusBar.showMessage(u"Данные успешно получены", 1000)

    def employee_list_get_next_page(self):
        self.ui.statusBar.showMessage(u"Запрашивается следующая страница списка сотрудников...")
        self.reset_employee_list(self._c._sendrecv("GET", self._employeeListNextUrl))
        self.employee_list_update_buttons()
        self.ui.statusBar.showMessage(u"Данные успешно получены", 1000)

    def employee_list_get_prev_page(self):
        self.ui.statusBar.showMessage(u"Запрашивается предыдущая страница списка сотрудников...")
        self.reset_employee_list(self._c._sendrecv("GET", self._employeeListPrevUrl))
        self.employee_list_update_buttons()
        self.ui.statusBar.showMessage(u"Данные успешно получены", 1000)

    def employee_list_exist_changed(self, state):
        self.ui.statusBar.showMessage(u"Переключение режима отображения списка сотрудников...")
        self.employee_list_get_first_page(state is not 0)
        self.ui.statusBar.showMessage(u"Режим успешно переключен", 1000)

    def employee_list_cell_clicked(self, row, column):
        try:
            employee_id = self.ui.employeeListTable.verticalHeaderItem(row).text()
            employee_id_int = int(employee_id)
            self.get_employee_details(employee_id_int)
        except:
            self.ui.statusBar.showMessage(u"Ошибка при запросе информации о сотруднике #%s#" % employee_id, 1000)

    def get_employee_details(self, id):
        self.ui.statusBar.showMessage(u"Запрашивается информация о сотруднике %d..." % id)
        succeed, self._currentEmployee = self._c.get_employee(id)
        if succeed:
            self.employee_details_update()
            self.employee_operations_update()
            self.employee_equipment_update()
            self.employee_tasks_update()
            self.tasks_equipment_attach_update()
            self.ui.statusBar.showMessage(u"Данные о сотруднике #%d успешно получены" % id, 1000)
        else:
            self.ui.statusBar.showMessage(u"Неудача при получении данных о сотруднике #%d" % id, 1000)

    def employee_details_update(self):
        gData = self._currentEmployee["object"]["general"]
        self.ui.employeeTab.setCurrentIndex(0)
        self.ui.employeeDetailsName.setText(gData["name"])
        self.ui.employeeDetailsSnils.setText(gData["snils"])
        self.ui.employeeDetailsLogin.setText(gData["login"])
        self.ui.employeeDetailsPhone.setText(gData["phone"])
        self.ui.employeeDetailsAddr.setText(gData["addr"])
        self.ui.employeeDetailsRole.setText(gData["role"])

    def employee_operations_update(self):
        t = self.ui.employeeOperationsTable
        t.clearContents()
        t.setRowCount(0)
        opData = self._currentEmployee["object"]["operations"]
        size = len(opData)
        t.setRowCount(size)
        for i in xrange(size):
            e = opData[i]
            t.setVerticalHeaderItem(i, QtGui.QTableWidgetItem("%d" % e["id"]))
            t.setItem(i, 0, QtGui.QTableWidgetItem(e["type"]))
            t.setItem(i, 1, QtGui.QTableWidgetItem(e["date"]))
        t.resizeColumnsToContents()

    def employee_equipment_update(self):
        t = self.ui.equipmentListBox
        t.clear()
        eqData = self._currentEmployee["object"]["owner_of"]

        if self.ui.equipmentExistCheckbox.isChecked():
            eq_names = [u"%s : %s" % (x["equipment"]["id"], x["equipment"]["name"]) for x in eqData if x["actual"]]
        else:
            eq_names = [u"%s : %s" % (x["equipment"]["id"], x["equipment"]["name"]) for x in eqData]
        t.addItems(eq_names)
        self.ui.taskEquipmentAttachBox.clear()
        self.ui.taskEquipmentAttachBox.addItems(eq_names)

    def equipment_exist_changed(self, state):
        self.ui.statusBar.showMessage(u"Переключение режима отображения списка оборудования...")
        self.employee_equipment_update()
        self.ui.statusBar.showMessage(u"Режим успешно переключен", 1000)

    def equipment_details_update(self, index):
        self.ui.equipmentAddr.clear()
        self.ui.equipmentName.clear()
        self.ui.equipmentSN.clear()
        self.ui.equipmentModel.clear()
        self.ui.equipmentDateBegin.clear()
        self.ui.equipmentDateEnd.clear()
        self.ui.equipmentActual.clear()

        if index >= 0:
            if self.ui.equipmentExistCheckbox.isChecked():
                eqData = [x for x in self._currentEmployee["object"]["owner_of"] if x["actual"]][index]
            else:
                eqData = self._currentEmployee["object"]["owner_of"][index]
            self.ui.equipmentAddr.setText(eqData["equipment"]["addr"])
            self.ui.equipmentName.setText(eqData["equipment"]["name"])
            self.ui.equipmentSN.setText(eqData["equipment"]["serial_number"])
            self.ui.equipmentModel.setText(eqData["equipment"]["model"])
            self.ui.equipmentDateBegin.setText(eqData["date_begin"])
            self.ui.equipmentDateEnd.setText(eqData["date_end"])
            self.ui.equipmentActual.setText(u"Правда" if eqData["actual"] else u"Неправда")

    def employee_tasks_update(self):
        t = self.ui.tasksListBox
        t.clear()
        tData = self._currentEmployee["object"]["tasks"]

        t_names = [u"%d : %s" % (x["id"], x["datetime"]) for x in tData]
        t.addItems(t_names)

    def tasks_details_update(self, index):
        self.ui.taskDate.clear()
        self.ui.taskOwner.clear()
        self.ui.taskDescription.clear()
        self.ui.taskEquipmentBox.clear()

        if index >= 0:
            tData = self._currentEmployee["object"]["tasks"][index]
            self.ui.taskDate.setText(tData["datetime"])
            if tData["owner"]:
                self.ui.taskOwner.setText(tData["owner"]["name"])
            self.ui.taskDescription.setPlainText(tData["name"])
            self.list_of_task_equipment_update(tData["id"])

        t = datetime.now().isoformat()
        self.ui.newTaskTime.setText(datetime.now().isoformat())
        self.ui.newTaskDescription.setPlainText("test:%s" % t)

    def list_of_task_equipment_update(self, task_id):
        self.ui.taskEquipmentBox.clear()
        self.ui.statusBar.showMessage(u"Запрашивается список оборудовани для задания%d..." % task_id)
        succeed, self._current_list_of_task_equipment = self._c.get_equipment_for_task(task_id)
        if succeed:
            c = self._current_list_of_task_equipment
            self.ui.taskEquipmentBox.addItems(["%d : %s" % (x["id"], x["name"]) for x in c])
            self.ui.statusBar.showMessage(u"Список оборудования успешно принят")
        else:
            self.ui.statusBar.showMessage(u"Ошибка получения списка оборудования")

    def tasks_equipment_details_update(self, index):
        self.ui.taskEquipmentID.clear()
        self.ui.taskEquipmentAddr.clear()
        self.ui.taskEquipmentName.clear()
        self.ui.taskEquipmentSerial.clear()
        self.ui.taskEquipmentDetachButton.setDisabled(True)

        if index >= 0:
            self.ui.taskEquipmentDetachButton.setEnabled(True)
            tData = self._current_list_of_task_equipment[index]
            self.ui.taskEquipmentID.setText(u"%s" % tData["id"])
            self.ui.taskEquipmentAddr.setText(tData["addr"])
            self.ui.taskEquipmentName.setText(tData["name"])
            self.ui.taskEquipmentSerial.setText(tData["serial_number"])

    def attach_equipment_to_task(self):
        eqs = self.ui.taskEquipmentAttachBox
        tsk = self.ui.tasksListBox

        t_index = tsk.currentIndex()
        if t_index < 0:
            return
        ts_id = self._currentEmployee["object"]["tasks"][t_index]["id"]

        eq_index = eqs.currentIndex()
        if eq_index < 0:
            return
        eq_id = self._currentEmployee["object"]["owner_of"][eq_index]["equipment"]["id"]

        self.ui.statusBar.showMessage(u"Прикрепляется оборудование %d к заданию %d..." % (eq_id, ts_id))
        succeed, data = self._c.add_equipment_to_task(ts_id, eq_id)
        if succeed:
            self.ui.statusBar.showMessage(u"Успешно прикреплено оборудование %d к заданию %d" % (eq_id, ts_id), 1000)
        else:
            self.ui.statusBar.showMessage(
                u"Неудача при прикреплении оборудования %d к заданию %d" % (eq_id, ts_id), 1000
            )

        self.tasks_details_update(t_index)

    def detach_equipment_from_task(self):
        eqs = self.ui.taskEquipmentBox
        tsk = self.ui.tasksListBox

        t_index = tsk.currentIndex()
        if t_index < 0:
            return
        ts_id = self._currentEmployee["object"]["tasks"][t_index]["id"]

        eq_id = int(self.ui.taskEquipmentID.text())

        self.ui.statusBar.showMessage(u"Открепляется оборудование %d от задания %d..." % (eq_id, ts_id))
        succeed, data = self._c.remove_equipment_from_task(ts_id, eq_id)
        if succeed:
            self.ui.statusBar.showMessage(u"Успешно откреплено оборудование %d от задания %d" % (eq_id, ts_id), 1000)
        else:
            self.ui.statusBar.showMessage(
                u"Неудача при откреплении оборудования %d от задания %d" % (eq_id, ts_id), 1000
            )

        self.tasks_details_update(t_index)

    def tasks_equipment_attach_update(self):
        self.ui.taskEquipmentAttachButton.setDisabled(True)
        if self.ui.taskEquipmentAttachBox.currentIndex() >= 0 and self.ui.tasksListBox.currentIndex() >= 0:
            self.ui.taskEquipmentAttachButton.setEnabled(True)

    def publish_new_task(self):
        client_id = self._currentEmployee["object"]["general"]["id"]
        name = self.ui.newTaskDescription.toPlainText()
        time = self.ui.newTaskTime.text()
        self._c.add_task(client_id, name, time)
        self.get_employee_details(client_id)

    def export_to_excel(self):
        w = ExcelSaver()
        self.ui.statusBar.showMessage(u"Загружается список всех сотрудников...")
        filename = "report.xls"
        succeed, employees = self._c.get_employee_list(1000)
        if succeed:
            w.makeEmployeeList(employees)
            w.save(filename)
            self.ui.statusBar.showMessage(u"Информация была успешно сохранена в файле %s" % filename, 2000)
        else:
            self.ui.statusBar.showMessage(u"Не удалось сохранить информацию", 2000)
Esempio n. 54
0
File: main.py Progetto: olexiim/tsp
class MainWindow(QtGui.QMainWindow):
    """Main TSP Problem SOlver class.
    
    Shows the main window and runs methods for the problems.
    
    Attributes:
        _method_path: path to methods module
        _method_modules: list of loaded methods for a current problem
        _method_types: list of loaded method types
        _neighborhoods: list of loaded heighborhood modules
        _current_state: current state
        _original_state: starting state
        _current_problem: current problem shortcut
        _current_problem_title: current problem title
        _current_problem_short_title: current problem short title
        _board_scene: object of QGraphicsScene, used to display a board
        _board_scene_removable: a list of objects that a dynamic on a board
        _board_data: data used to display board
        _statistics: list of all statistic records
        _run_queue: queue of problem tasks
        _has_solution: flag to know if there solution was found
        _is_displaying_runtime: 
        _is_displaying_runtime_state:
        main_options: GUI options of the Problem Solver
        _chart_max_value: maximum height (cost value) of chart data
        _chart_min_value: minimum height (cost value) of chart data
        _chart_prev_value: previous value on a dynamic chart
        _chart_prev_best_value: currently best cost value
        tsp_cities_num: number of cities in TSP problem
        tsp_filename: TSP file name
        tsp_board: TspBoard object
        run_thread: object of a thread that runs a searching method
        run_object: object of class AsyncRun
    """
    
    _method_path = 'methods'
    _method_modules = {}
    _method_types = []
    _neighborhoods = {}
    _current_state = None
    _original_state = None
    _current_problem = ''
    _current_problem_title = ''
    _current_problem_short_title = ''
    
    _board_scene = None
    _board_scene_removable = []
    _board_data = None
    
    _statistics = []
    _run_queue = []
    _has_solution = False
    _is_displaying_runtime = False
    _is_displaying_runtime_state = False
    
    main_options = {'runtime_chart':True, 'runtime_solution':False, 
                    'avg_solution':1, 'runtime_best':False}
    
    _chart_max_value = 0
    _chart_min_value = float('inf')
    _chart_prev_value = None
    _chart_prev_best_value = float('inf')
    
    # problem parameteres
    # TSP
    tsp_cities_num = 4
    tsp_filename = ""
    tsp_board = TspBoard()
    
    run_thread = None
    run_object = None
    
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.disable_methods()
        self.clear_board()
        
        # init run button menu
        self.run_menu = QtGui.QMenu()
        self.run_menu.addAction("Run once", self.run_once)
        self.run_menu.addAction("Run checked methods", self.run_checked_methods)
        self.run_menu.addAction("Run all methods", self.run_all_variants)
        self.ui.run.setMenu(self.run_menu)
        
        # status bar
        self.timer_widget = QtGui.QLabel()
        self.run_timer = QtCore.QTimer(self)
        self.run_timer.timeout.connect(self.update_timer)
        
        # init stat table
        header_labels = ["##","Problem","Method","Neighborhood",
                "Solution cost","Time, sec", "Overall states"]
        self.ui.stat_table.setHorizontalHeaderLabels(header_labels)
        self.ui.stat_table.resizeColumnsToContents() # autoresize based on header text width
        self.ui.stat_table.setColumnWidth(1, 110) # extend Problem header width
        self.ui.stat_table.setColumnWidth(2, 120) # extend Problem header width
        self.ui.stat_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.ui.stat_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        
        QtCore.QObject.connect(self.ui.run,QtCore.SIGNAL("clicked()"), self.run_once)
        
        self.ui.actionGenerate_new.triggered.connect(self.new_random)
        self.ui.actionLoad_from_file.triggered.connect(self.new_load)
        self.ui.actionSave.triggered.connect(self.save_problem)
        self.ui.actionRestart.triggered.connect(self.restart)
        self.ui.actionRun_once.triggered.connect(self.run_once)
        self.ui.actionRun_checked_methods.triggered.connect(self.run_checked_methods)
        self.ui.actionRun_all_methods.triggered.connect(self.run_all_variants)
        self.ui.actionStop.triggered.connect(self.stop)
        self.ui.actionClear.triggered.connect(self.clear_statistics)
        self.ui.actionDelete_selected.triggered.connect(self.delete_selected_statistics)
        self.ui.actionImportTo_CSV.triggered.connect(self.import_to_csv)
        self.ui.actionExit.triggered.connect(self.close)
        self.ui.actionOptions.triggered.connect(self.popup_main_options_dlg)
        
        self.ui.methods_tree.itemDoubleClicked.connect(self.methods_tree_item_clicked)
        self.ui.stat_table.currentItemChanged.connect(self.stat_table_item_changed)
        self.ui.main_splitter.splitterMoved.connect(self.process_resize)
        self.ui.splitter_2.splitterMoved.connect(self.process_resize)
        
        self.ui.stat_table.keyPressEvent = self.process_statistics_keys_event
        
        self.ui.tab_widget.setCurrentIndex(0)

    def process_resize(self, event):
        """Processes a window resize event"""
        sr = self.ui.runtime_chart.sceneRect()
        g = self.ui.runtime_chart_frame.geometry()
        if sr.width()>g.width():
            self.ui.runtime_chart.setGeometry(g.width()-sr.width(), 0, sr.width(), g.height())
        else:
            self.ui.runtime_chart.setGeometry(0, 0, sr.width(), g.height())
        self.ui.runtime_chart.fitInView(sr, QtCore.Qt.IgnoreAspectRatio)
        self.ui.board.fitInView(self.ui.board.sceneRect(), QtCore.Qt.KeepAspectRatio)
    
    def resizeEvent(self, event):
        """Slot that processes a window resize event"""
        QtGui.QWidget.resizeEvent(self, event)
        self.process_resize(event)
        
    def popup_main_options_dlg(self):
        """Pop-ups a main options dialog"""
        dialog = MainOptionsDlg(self)
        dialog.ui.runtime_chart.setCheckState(self.main_options['runtime_chart'] and QtCore.Qt.Checked or QtCore.Qt.Unchecked)
        dialog.ui.runtime_solution.setCheckState(self.main_options['runtime_solution'] and QtCore.Qt.Checked or QtCore.Qt.Unchecked)
        dialog.ui.runtime_best.setCheckState(self.main_options['runtime_best'] and QtCore.Qt.Checked or QtCore.Qt.Unchecked)
        dialog.ui.avg_solution.setValue(self.main_options['avg_solution'])
        dialog.ui.avg_solution.setEnabled(self.main_options['runtime_chart'])
        dialog.ui.avg_solution_label.setEnabled(self.main_options['runtime_chart'])
        if dialog.exec_():
            self.main_options['runtime_chart'] = dialog.ui.runtime_chart.checkState()==QtCore.Qt.Checked
            self.main_options['runtime_solution'] = dialog.ui.runtime_solution.checkState()==QtCore.Qt.Checked
            self.main_options['runtime_best'] = dialog.ui.runtime_best.checkState()==QtCore.Qt.Checked
            self.main_options['avg_solution'] = dialog.ui.avg_solution.value()
            self.ui.tab_widget.setTabEnabled(1, self.main_options['runtime_chart'])
            return True
        return False
    
    def clear_method_lists(self):
        """Delete all methods from the interface lists"""
        self.ui.methods_tree.clear()
        self.ui.neighborhood_list.clear()
        
    def disable_methods(self):
        """Disables methods list"""
        self.ui.run_groupbox.setEnabled(False)
    
    def update_method_lists(self, reload_modules=True):
        """Loads methods, heuristics, and neighborhoods
        
        Args:
            reload_modules
        """
        
        def is_subclass(class_obj, parent_class_name, strictly=True):
            if strictly and class_obj.__name__==parent_class_name:
                return False
            for cl in inspect.getmro(class_obj):
                if cl.__name__==parent_class_name:
                    return True
            return False
            
        self.ui.run_groupbox.setEnabled(True)
            
        if reload_modules:
            self.clear_method_lists()
            
            self.ui.methods_tree.addTopLevelItem(QtGui.QTreeWidgetItem(['Methods']))
            root = self.ui.methods_tree.topLevelItem(0)
            root.setFlags(root.flags().__or__(QtCore.Qt.ItemIsTristate))
            root.setCheckState(0, QtCore.Qt.Unchecked)
            root.setExpanded(True)
            self._method_types = []
            
            method_path = self._method_path + os.sep + self._current_problem
            method_files = [ f for f in os.listdir(method_path) if isfile(join(method_path,f)) and f.endswith('.py') ]
            sys.path.append(join(sys.path[0], method_path))
            
            self._method_modules = {}
            self._neighborhoods = {}
            for method_file in method_files:
                module_name = 'methods.'+self._current_problem+'.'+method_file.replace('.py','')
                import_module(module_name)
                for name, obj in inspect.getmembers(sys.modules[module_name]):
                    # method
                    if inspect.isclass(obj) and is_subclass(obj,"BasicMethod"):
                        if not obj._type in self._method_types:
                            self._method_types.append(obj._type)
                            root.addChild(QtGui.QTreeWidgetItem([obj._type]))
                            child = root.child(root.childCount()-1)
                            child.setCheckState(0, QtCore.Qt.Unchecked)
                            child.setExpanded(True)
                            font = child.font(0)
                            font.setBold(True)
                            child.setFont(0, font)
                            child.setFlags(root.flags().__or__(QtCore.Qt.ItemIsTristate))
                        
                        if not obj._disabled:
                            self._method_modules[obj.__name__] = {'file':method_file, 'type':obj._type, 'class':obj, 'title':obj._name, 'short_title':obj._short_name, 'module':module_name}
                        parent = self.ui.methods_tree.findItems(obj._type, QtCore.Qt.MatchFlags(QtCore.Qt.MatchFixedString + QtCore.Qt.MatchRecursive))
                        if parent:
                            parent = parent[0]
                            parent.addChild(QtGui.QTreeWidgetItem([obj._name]))
                            child = parent.child(parent.childCount()-1)
                            child.setCheckState(0, QtCore.Qt.Unchecked)
                            child.setData(1, QtCore.Qt.UserRole, obj.__name__)
                            if obj._disabled:
                                child.setDisabled(True)

                    # neighborhood
                    if inspect.isclass(obj) and is_subclass(obj,"BasicNeighborhood") and not obj._disabled:
                        self._neighborhoods[obj.__name__] = {'file':method_file, 'module':module_name, 'class':obj, 'title':obj._name, 'short_title':obj._short_name}
                        self.ui.neighborhood_list.addItem(obj._name)
                        item = self.ui.neighborhood_list.item(self.ui.neighborhood_list.count()-1)
                        item.setData(QtCore.Qt.UserRole, obj.__name__)
                        if obj._default:
                            item.setCheckState(QtCore.Qt.Checked)
                        else:
                            item.setCheckState(QtCore.Qt.Unchecked)
    
    def popup_tsp_random_options_dlg(self):
        """Pop-ups a TSP options dialog"""
        dialog = TSPRandomOptionsDlg(self)
        dialog.ui.cities_num.setValue(self.tsp_cities_num)
        dialog.ui.cities_num.selectAll()
        if dialog.exec_():
            self.tsp_cities_num = dialog.ui.cities_num.value()
            return True
        return False
        
    def enable_window_items(self, enable=True):
        """Enables or disables interface elements before/after method's run"""
        enable_objects = [self.ui.methods_tree, self.ui.neighborhood_list, self.ui.time_limit,
                          self.ui.actionRun_once, self.ui.actionRun_checked_methods, 
                          self.ui.actionRun_all_methods, self.ui.menuProblem]
        if enable:
#            self.ui.methods_tree.setEnabled(True)
#            self.ui.neighborhood_list.setEnabled(True)
#            self.ui.time_limit.setEnabled(True)
            self.ui.run.setText("Run")
            self.run_menu.setEnabled(True)
            self.ui.actionStop.setEnabled(False)
            for obj in enable_objects:
                obj.setEnabled(True)
            
        else:
#            self.ui.methods_tree.setEnabled(False)
#            self.ui.neighborhood_list.setEnabled(False)
#            self.ui.time_limit.setEnabled(False)
            self.ui.run.setText("Stop")
            self.run_menu.setEnabled(False)
            self.ui.actionStop.setEnabled(True)
            for obj in enable_objects:
                obj.setEnabled(False)
                
    def before_run(self, problem_title="", method_title=""):
        """Function that runs before a solving method
        
        Args:
            problem_title: 
            method_title:
        """
        msg = 'Run'
        if problem_title:
            msg += ' ' + problem_title
        if method_title:
            msg += ' with ' + method_title + ' method'

        self.ui.statusbar.showMessage(msg)
        self.elapsed_timer = QtCore.QElapsedTimer()
        self.elapsed_timer.start()
        self.run_timer.start(1000)
        self.ui.statusbar.addPermanentWidget(self.timer_widget)
        self.timer_widget.show()
        self.timer_widget.setText('00:00')
#        self.erase_runtime_chart()
        if self.main_options['runtime_chart']:
            self.ui.tab_widget.setCurrentIndex(1)
        else:
            self.ui.tab_widget.setCurrentIndex(0)
        
#        self.ui.board.setForegroundBrush(QtGui.QBrush(QtCore.Qt.lightGray,QtCore.Qt.Dense6Pattern))
        self.ui.board.setForegroundBrush(QtGui.QBrush(QtGui.QColor(235,233,237,127)))
        self.ui.board.repaint()
        self.enable_window_items(enable=False)
    
    def after_run(self, result_state=None, msg="", stat=StatRecord()):
        """Function that runs after a solving method
        
        Args:
            result_state: found state
            msg: string that will be displayed in a status bar
            stat: statistics, type StatRecord
        """
        if result_state:
            print "After run", result_state.to_string(), msg
        else:
            print "After run with no params"
        self.run_thread.wait()
        del self.run_thread
        self.run_thread = None
        del self.run_object
        self.run_object = None
    
        self.run_timer.stop()
        del self.elapsed_timer
        self.ui.statusbar.removeWidget(self.timer_widget)
        self.ui.statusbar.showMessage(msg, 1000*60)
        
        if result_state:
            self._has_solution = True
            self._current_state = result_state.copy()
            self.display_board(self._current_state)
            self.add_statistics(stat, result_state.copy())
        
        if self._run_queue:
            time.sleep(1)
        if self.process_run_queue():
            return
        
        self.ui.board.setForegroundBrush(QtGui.QBrush(QtCore.Qt.lightGray,QtCore.Qt.NoBrush))
        self.ui.board.repaint()
        self.ui.tab_widget.setCurrentIndex(0)
        self.enable_window_items()
        
    def _process_new_tsp_problem(self, problem_title, problem_short_title):
        """Runs after new problem is randomly created or loaded
        
        Args:
            problem_title: 
            problem_short_title:
        """
        self._original_state = TspState(self.tsp_board.cities_num())
        self._current_state = self._original_state
        self._current_problem = "tsp"
        self._current_problem_title = problem_title
        self._current_problem_short_title = problem_short_title
        self._has_solution = False
        self._board_scene = None
        self.display_board(self._current_state)
        self.ui.actionRestart.setEnabled(True)
        self.ui.actionSave.setEnabled(True)
        self.erase_runtime_chart()
    
    def new_random(self):
        """Process a menu action "Problem/Generate new..."""
        prev_problem = self._current_problem
#        selected_problem = self.ui.problem_list.itemData(self.ui.problem_list.currentIndex()).toString().__str__()
        selected_problem = "tsp"
        if selected_problem=="tsp":
            if self.popup_tsp_random_options_dlg():
                self.tsp_board.random(self.tsp_cities_num)
                self._process_new_tsp_problem("Random TSP with %d cities" % (self.tsp_cities_num,), "TSP %d cities" % (self.tsp_cities_num,))
        if prev_problem!=self._current_problem:
            self.update_method_lists()
            self.clear_statistics()
            
    def new_load(self):
        """Process a menu action "Problem/Load from file..."""
        prev_problem = self._current_problem
        selected_problem = "tsp"
        
        open_dlg = QtGui.QFileDialog(self, "Load problem", ".")
        open_dlg.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
        open_dlg.setFileMode(QtGui.QFileDialog.ExistingFile)
        if selected_problem=="tsp":
            open_dlg.setDefaultSuffix("tsp")
            open_dlg.setNameFilters(["TSP files (*.tsp)","Any files (*)"])
        if open_dlg.exec_():
            file_name = open_dlg.selectedFiles()[0].__str__()
            if not file_name:
                return
            if selected_problem=="tsp":
                self.tsp_board.load_from_file(file_name)
                self.tsp_cities_num = self.tsp_board.cities_num()
                self._process_new_tsp_problem("TSP with %d cities (%s)" % (self.tsp_cities_num, split(file_name)[1]), "TSP %d cities (%s)" % (self.tsp_cities_num, split(file_name)[1]))
        if prev_problem!=self._current_problem:
            self.update_method_lists()
            self.clear_statistics()
    
    def save_problem(self):
        """Process a menu action "Problem/Save..."""
        save_dlg = QtGui.QFileDialog(self, "Save problem", ".")
        save_dlg.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        if self._current_problem=="tsp":
            save_dlg.setDefaultSuffix("tsp")
            save_dlg.setNameFilters(["TSP files (*.tsp)","Any files (*)"])
        if save_dlg.exec_():
            file_name = save_dlg.selectedFiles()[0].__str__()
            if not file_name:
                return
            if self._current_problem=="tsp":
                self.tsp_board.save_to_file(file_name)
    
    def restart(self):
        """Process a menu action "Run/Restart..."""
        self._current_state = self._original_state.copy()
        self._current_state.randomize()
        self._has_solution = False
        self._board_scene = None
        self.display_board(self._current_state)
        self.erase_runtime_chart()
    
    def display_board(self, state=None, board=None, has_solution=False, use_board_scene=True):
        """Displays the Problem Solver board for a state
        
        Args:
            state: state to disaply on board; if not defined, then takes 
                current state
            board: 
            has_solution: 
            use_board_scene:
        """
        if not state:
            state = self._current_state
        if not state:
            self.clear_board()
        if self._current_problem=="tsp":
            if not board:
                board = self.tsp_board
            self.display_board_tsp(state, board, has_solution, use_board_scene)
        else:
            self.clear_board()
    
    def display_board_tsp(self, state, board=None, has_solution=False, use_board_scene=True):
        """Displays TSP board for a state
        
        Args:
            state: state to disaply on board; if not defined, then takes 
                current state
            board: 
            has_solution: 
            use_board_scene:
        """
        new_board = False
        if not self._board_scene and use_board_scene:
            self._board_scene = QtGui.QGraphicsScene()
            self._board_scene_removable = []
            scene = self._board_scene
            new_board = True
        elif not use_board_scene:
            scene = QtGui.QGraphicsScene()
            new_board = True
        
#        scene = QtGui.QGraphicsScene()
        cities = []
        if new_board:
            board_width = board_height = min(board.max_x()-board.min_x(), board.max_y()-board.min_y())
            city_width = city_height = max(board_width*0.01, 4)

            scene.setSceneRect(0,0,board_width,board_height)
#            scene.addRect(0,0,board_width,board_height, QtGui.QPen(QtCore.Qt.white), QtGui.QBrush(QtCore.Qt.white))
            x_coef = float(board_width*0.9) / (board.max_x() - board.min_x())
            y_coef = float(board_height*0.9) / (board.max_y() - board.min_y())
            x_delta, y_delta = board_width*0.05, board_height*0.05
            if x_coef<y_coef:
                y_coef = x_coef
            elif y_coef<x_coef:
                x_coef = y_coef
                
            for city in board.cities():
                cities.append(((city[0]-board.min_x())*x_coef+x_delta, 
                               (city[1]-board.min_y())*y_coef+y_delta))
            for i in range(len(cities)):
                scene.addRect(cities[i][0]-city_width/2, cities[i][1]-city_height/2, city_width, city_height, QtGui.QPen(QtCore.Qt.black), QtGui.QBrush(QtCore.Qt.black))
            
            if use_board_scene:
                scene = self._board_scene
                self._board_data = cities
        elif not new_board and use_board_scene:
            scene = self._board_scene
            cities = self._board_data
            if self._board_scene_removable:
                for item in self._board_scene_removable:
                    scene.removeItem(item)
            
        if self._has_solution or has_solution:
            if use_board_scene:
                self._board_scene_removable = []
            prev_city = state._cities[state.cities_num()-1]
            for next_city in state._cities:
                new_item = scene.addLine(cities[prev_city][0], cities[prev_city][1], cities[next_city][0], cities[next_city][1], QtGui.QPen(QtCore.Qt.black))
                if use_board_scene:
                    self._board_scene_removable.append(new_item)
                prev_city = next_city
        self.ui.board.setScene(scene)
        self.ui.board.fitInView(scene.sceneRect(), QtCore.Qt.KeepAspectRatio)
        return True
        
    def clear_board(self):
        """Clears a board"""
        scene = QtGui.QGraphicsScene()
        self.ui.board.setScene(scene)
        self._board_scene = None
        
    def stop(self):
        """Stops method running"""
        if self.run_thread:
#            print "Begin termination..."
            self._run_queue = []
#            print "Run after_run"
#            self.after_run()
            self.run_object.emit(QtCore.SIGNAL("finished"))
#            print "After run completed"
    
    def process_run_queue(self):
        """Process a queue of the problem tasks"""
        if not self._run_queue:
            return False
            
        method, neighborhood, self._current_state = self._run_queue.pop(0)
        print 'Next task:', self._current_problem, method
        self.before_run(problem_title=self._current_problem_title, method_title=self._method_modules[method]['title'])
        self.async_run(method, neighborhood)
        return True
    
    def run_once(self):
        """Runs currently selected method for the problem"""
        if self.run_thread:
            return self.stop()
            
        items = self.ui.methods_tree.selectedItems()
        if not items:
            self.show_message("No method selected")
            return
        method = items[0].data(1, QtCore.Qt.UserRole).toString().__str__()

        neighborhood = self.get_checked_neighborhoods()
        if not neighborhood:
            self.show_message("Please select a method")
            return
        
        if self._method_modules.has_key(method):
            self._run_queue.append((method, neighborhood, self._current_state.copy()))
            self.process_run_queue()
    
    def run_checked_methods(self):
        """Runs checked methods for the problem"""
        if self.run_thread:
            return self.stop()
            
        methods = self.get_checked_methods()
        neighborhood = self.get_checked_neighborhoods()
        if not neighborhood:
            self.show_message("No neighborhood selected")
            return
        
        for method in methods:
            if self._method_modules.has_key(method):
                self._run_queue.append((method, neighborhood, self._current_state.copy()))
        self.process_run_queue()
    
    def run_all_variants(self):
        """Runs all possible variants of methods"""
        if self.run_thread:
            return self.stop()
        
        neighborhood = self.get_checked_neighborhoods()
        if not neighborhood:
            self.show_message("No neighborhood selected")
            return
        
        methods = self.get_checked_methods(only_checked=False)
        for method in methods:
            if self._method_modules.has_key(method):
                self._run_queue.append((method, neighborhood, self._current_state.copy()))
        self.process_run_queue()
            
    def async_run(self, method, neighborhoods):
        """Makes an asynchronous run of the method

        Args:
            method: name of the method to run
            neighborhoods: list of the neighborhood's names
        """
        neighborhood_classes = []
        for neighborhood in neighborhoods:
            neighborhood_classes.append(self._neighborhoods[neighborhood]['class']())
        obj = self._method_modules[method]['class'](neighborhood=neighborhood_classes, time_limit=self.ui.time_limit.value(), args=self.get_problem_args())
        run_options = {'runtime_cost': self.main_options['runtime_chart'],
                       'runtime_state': self.main_options['runtime_solution'],
                       'cost_avg_num': self.main_options['avg_solution'],
                       'runtime_best_state': self.main_options['runtime_best']}
        self.run_object = AsyncRun(obj, self._current_state, run_options)
        self.run_thread = QtCore.QThread()
        QtCore.QObject.connect(self.run_thread, QtCore.SIGNAL("started()"), self.run_object.run, QtCore.Qt.DirectConnection);
        QtCore.QObject.connect(self.run_thread, QtCore.SIGNAL("finished()"), self.run_object.deleteLater, QtCore.Qt.DirectConnection);
        QtCore.QObject.connect(self.run_object, QtCore.SIGNAL("finished"), self.run_object.stopWork, QtCore.Qt.DirectConnection);
        QtCore.QObject.connect(self.run_object, QtCore.SIGNAL("finished"), self.run_object.deleteLater, QtCore.Qt.DirectConnection);
        QtCore.QObject.connect(self.run_object, QtCore.SIGNAL("finished"), self.run_thread.quit, QtCore.Qt.DirectConnection);
        QtCore.QObject.connect(self.run_object, QtCore.SIGNAL("success"), self.after_run)

        QtCore.QObject.connect(self.run_object, QtCore.SIGNAL("display_value"), self.display_runtime_chart)
        QtCore.QObject.connect(self.run_object, QtCore.SIGNAL("display_state"), self.display_runtime_state)
        self.run_object.moveToThread(self.run_thread)
        self.run_thread.start()
        
    def methods_tree_item_clicked(self):
        """Slot for clicking on method signal"""
        if not self.run_thread:
            self.run_once()
            
    def get_checked_methods(self, only_checked=True):
        """Returns all checked methods in the tree
        
        Args:
            only_checked:
        
        Returns:
            A list of names of checked methods
        """
        def process_node(node, level, check_list):
            if node.childCount()==0 and level>=3 and (node.checkState(0)==QtCore.Qt.Checked or not only_checked):
                check_list.append(node.data(1, QtCore.Qt.UserRole).toString().__str__())
            for c in range(node.childCount()):
                process_node(node.child(c), level+1, check_list)
        
        root = self.ui.methods_tree.topLevelItem(0)
        check_list = []
        process_node(root, 1, check_list)
        return check_list
        
    def get_checked_neighborhoods(self, only_checked=True):
        """Returns all checked neighborhoods in the neighborhood list
        
        Args:
            only_checked:
        
        Returns:
            A list of names of checked neighborhoods
        """
        check_list = []
        for i in range(self.ui.neighborhood_list.count()):
            item = self.ui.neighborhood_list.item(i)
            if item.checkState()==QtCore.Qt.Checked or not only_checked:
                check_list.append(item.data(QtCore.Qt.UserRole).toString().__str__())
        return check_list
        
    def get_problem_args(self):
        if self._current_problem=="tsp":
            return [self.tsp_board.distance_matrix()]
        return None
        
    """
    Statistics stuff
    """
    
    def enable_statistics_actions(self, enable=True):
        """Enables or disables statistics table during method run
        
        Args:
            enable: True/False
        """
        self.ui.actionSave_history.setEnabled(enable)
        self.ui.menuImport.setEnabled(enable)
        self.ui.actionClear.setEnabled(enable)
        self.ui.actionDelete_selected.setEnabled(enable)
    
    def add_statistics(self, stat=StatRecord(), state=None):
        """Adds a statistic record to the statistics table.
        
        Args:
            stat: statistic object, type: StatRecord
            state: state
        """
        if not stat:
            return
        print "Adding statistics..."
        self._statistics.append({'statistics':stat, 'state':state, 'board':self.tsp_board.copy(), 'problem':self._current_problem})
        row = self.ui.stat_table.rowCount()
        self.ui.stat_table.insertRow(row)
        self.ui.stat_table.setItem(row, 0, QtGui.QTableWidgetItem(str(row+1)))
        self.ui.stat_table.setItem(row, 1, QtGui.QTableWidgetItem(self._current_problem_short_title))
        self.ui.stat_table.setItem(row, 2, QtGui.QTableWidgetItem(stat.method))
        self.ui.stat_table.setItem(row, 3, QtGui.QTableWidgetItem(stat.neighborhood))
        self.ui.stat_table.setItem(row, 4, QtGui.QTableWidgetItem('{:,.2f}'.format(stat.solution_cost)))
        self.ui.stat_table.item(row,4).setTextAlignment(QtCore.Qt.AlignRight+QtCore.Qt.AlignVCenter)
        self.ui.stat_table.setItem(row, 5, QtGui.QTableWidgetItem("%.3f"%stat.overall_run_time))
        self.ui.stat_table.item(row,5).setTextAlignment(QtCore.Qt.AlignRight+QtCore.Qt.AlignVCenter)
        self.ui.stat_table.setItem(row, 5, QtGui.QTableWidgetItem("%.3f"%stat.overall_run_time))
        self.ui.stat_table.setItem(row, 6, QtGui.QTableWidgetItem('{:,d}'.format(stat.overall_nodes_generated)))
        self.ui.stat_table.item(row,6).setTextAlignment(QtCore.Qt.AlignRight+QtCore.Qt.AlignVCenter)
        self.ui.stat_table.item(row,1).setData(QtCore.Qt.UserRole, len(self._statistics)-1)
        self.ui.stat_table.resizeRowsToContents()
        self.ui.stat_table.scrollToItem(self.ui.stat_table.item(row,0))
        
        self.enable_statistics_actions()
        
    def stat_table_item_changed(self):
        """Slot that handles changes of the statistic record in the list"""
        if self.ui.stat_table.isEnabled():
            if self.ui.stat_table.rowCount():
                state_num = self.ui.stat_table.item(self.ui.stat_table.currentRow(),1).data(QtCore.Qt.UserRole).toInt()[0]
                self.display_board(self._statistics[state_num]['state'], self._statistics[state_num]['board'], has_solution=True, use_board_scene=False)
    
    def clear_statistics(self):
        """Clears statistics"""
        self.ui.stat_table.setDisabled(True)
        for row in range(self.ui.stat_table.rowCount()):
            self.ui.stat_table.removeRow(0)
        self.ui.stat_table.setEnabled(True)
        self.enable_statistics_actions(False)
        
    def delete_selected_statistics(self):
        """Delete selected statistic records"""
        self.ui.stat_table.setDisabled(True)
        ranges = self.ui.stat_table.selectedRanges()
        rows = []
        for range_ in ranges:
            for r in range(range_.topRow(), range_.bottomRow()+1):
                rows.append(r)
        rows.sort(reverse = True)
        for row in rows:
            self.ui.stat_table.removeRow(row)
        for row in range(self.ui.stat_table.rowCount()):
            self.ui.stat_table.setItem(row, 0, QtGui.QTableWidgetItem(str(row+1)))
        self.ui.stat_table.setEnabled(True)
        if self.ui.stat_table.rowCount()==0:
            self.enable_statistics_actions(False)
            
    def process_statistics_keys_event(self, event):
        """Process key clicks for statistics table"""
        QtGui.QTableWidget.keyPressEvent(self.ui.stat_table, event)
        if event.key()==QtCore.Qt.Key_Delete and self.ui.stat_table.currentRow()>=0:
            self.ui.stat_table.setDisabled(True)
            row = self.ui.stat_table.currentRow()
            self.ui.stat_table.removeRow(row)
            for r in range(row, self.ui.stat_table.rowCount()):
                self.ui.stat_table.setItem(r, 0, QtGui.QTableWidgetItem(str(r+1)))
            self.ui.stat_table.setEnabled(True)
            if self.ui.stat_table.rowCount()==0:
                self.enable_statistics_actions(False)
            
    def import_to_csv(self):
        """Imports all statistic records to CSV-format file"""
        save_dlg = QtGui.QFileDialog(self, "Import history", ".")
        save_dlg.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        save_dlg.setDefaultSuffix("csv")
        save_dlg.setNameFilters(["CSV files (*.csv)","Any files (*)"])
        if save_dlg.exec_():
            file_name = save_dlg.selectedFiles()[0].__str__()
            if not file_name:
                return
#        filename = 'import.csv'
            col_count = self.ui.stat_table.columnCount()
            with open(file_name, 'w') as f:
                header = [self.ui.stat_table.horizontalHeaderItem(col).text().__str__() for col in range(col_count)] + ["State"]
                f.write(";".join(header))
                for row in range(self.ui.stat_table.rowCount()):
                    stat_num = self.ui.stat_table.item(row,1).data(QtCore.Qt.UserRole).toInt()[0]
                    item = [self.ui.stat_table.item(row,col).text().__str__() for col in range(col_count)] + [self._statistics[stat_num]['state'].to_string()]
                    f.write("\n" + ";".join(item))
            self.ui.statusbar.showMessage("Statistics data have been imported to file "+file_name, 1000*60)
    
    def build_chart(self):
        pass
    
    def update_timer(self):
        """Handles tick signal from running timer"""
        elapsed = self.elapsed_timer.elapsed() / 1000
        num_secs = elapsed % 60
        num_mins = elapsed / 60
        num_hrs = num_mins / 60
        if num_hrs>0:
            num_mins = num_mins % 60
        if num_hrs:
            self.timer_widget.setText('%02d:%02d:%02d'%(num_hrs,num_mins,num_secs))
        else:
            self.timer_widget.setText('%02d:%02d'%(num_mins,num_secs))
            
    def show_message(self, msg):
        """Show alert message box
        
        Args:
            msg:
        """
        msg_box = QtGui.QMessageBox(QtGui.QMessageBox.Warning, "Warning", msg, QtGui.QMessageBox.Ok, self)
        msg_box.exec_()
        
    def display_runtime_chart(self, value, best_value=float('inf')):
        """Display runtime chart
        
        Args:
            value: add new value point
            best_value: new best value point
        """
        if self.main_options['runtime_chart'] and not self._is_displaying_runtime:
            if self._chart_max_value<value:
                self._chart_max_value = value
            if self._chart_min_value>value:
                self._chart_min_value = value
            self._is_displaying_runtime = True
            self.ui.runtime_cost.setText("%.2f" % (value,))
            if best_value!=float('inf'):
                self.ui.best_cost.setText("%.2f" % (best_value,))
            
            scene = self.ui.runtime_chart.scene()
            if not scene:
                scene = QtGui.QGraphicsScene()
                width, height = 2, self._chart_max_value
            else:
                width, height = scene.sceneRect().width()+2, self._chart_max_value
            scene.setSceneRect(0,-height,width,height)
            sr = scene.sceneRect()
            h = value
            front_color, back_color = QtGui.QColor(0,127,0), QtGui.QColor(0,255,0)
            scene.addRect(sr.width()-2, -h, 2, h, QtGui.QPen(back_color), QtGui.QBrush(back_color))
            scene.addLine(sr.width()-1, -h, sr.width(), -h, QtGui.QPen(front_color))
            
#            if self._chart_prev_value!=None:
#                prev_h = int((sr.height()-self._chart_max_value*0.1)*self._chart_prev_value/self._chart_max_value)
#                scene.addLine(sr.width()-3, -prev_h, sr.width()-3, -h, QtGui.QPen(front_color))
                
            if best_value!=float('inf'):
                scene.addLine(sr.width()-2, -best_value, sr.width(), -best_value, QtGui.QPen(QtCore.Qt.red))
                if self._chart_prev_best_value!=float('inf'):
                    scene.addLine(sr.width()-3, -self._chart_prev_best_value, sr.width()-3, -best_value, QtGui.QPen(QtCore.Qt.red))
                
            self.ui.runtime_chart.setScene(scene)
            g = self.ui.runtime_chart_frame.geometry()
            if sr.width()>g.width():
                self.ui.runtime_chart.setGeometry(g.width()-sr.width(), 0, sr.width(), g.height())
            else:
                self.ui.runtime_chart.setGeometry(0, 0, sr.width(), g.height())
            self.ui.runtime_chart.fitInView(sr, QtCore.Qt.IgnoreAspectRatio)
            self._chart_prev_value = value
            self._chart_prev_best_value = best_value
            
            self._is_displaying_runtime = False
            
    def display_runtime_state(self, state, value):
        """Display actual runtime state as label
        
        Args:
            state: new state
            value: new state value
        """
        if not self._is_displaying_runtime_state:
            self._is_displaying_runtime_state = True
            self.display_board(state, has_solution=True)
            self._is_displaying_runtime_state = False
            
    def erase_runtime_chart(self):
        """Erase runtime chart"""
        self.ui.runtime_cost.setText("0.00")
        self.ui.best_cost.setText("0.00")
        scene = QtGui.QGraphicsScene()
        self.ui.runtime_chart.setScene(scene)
        self._chart_max_value = 0
        self._chart_min_value = float('inf')
        self._chart_prev_value = None
        self._chart_prev_best_value = float('inf')
Esempio n. 55
0
 def __init__(self, parent=None):
     super(MyMainWindow, self).__init__(parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
Esempio n. 56
0
class MainWindow(QtGui.QMainWindow):
    """
    Clase de la ventana principal.
    El widget central (centralWidget) de la ventana ira cambiando
    respecto a que es lo que el usuario desea hacer.
    """

    venta_directa_en_curso = False
    num_mesas = controller_empresa.getEmpresa(1)[0].num_mesas

    def __init__(self, tipo=None, rut=None):
        'Constructor de la clase'
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.rut = rut
        self.tipo = tipo
        self.set_signals()
        self.showMaximized()
        self.config_user()

        self.setVisible(False) # Se oculta la ventana principal mientras se cargan los componentes.

        # Se crea un QProgressDialog para notificar al usuario sobre las cargas del programa.
        progress = QtGui.QProgressDialog("Cargando modulos...", "", 0, self.num_mesas+7)
        progress.setWindowTitle("Cargando...")
        progress.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        label = QtGui.QLabel()
        pixmap = QtGui.QPixmap('images/cafe_nostro_load_modulos.png')
        label.setPixmap(pixmap)
        progress.setLabel(label)
        progress.setCancelButton(None)
        progress.show()

        progress.setValue(0)
        self.ui.stackedWidget.addWidget(AdminUsers()) #2
        progress.setValue(1)
        self.ui.stackedWidget.addWidget(AdminProductos()) #3
        progress.setValue(2)
        self.ui.stackedWidget.addWidget(FormularioVenta(self.ui,self.rut,"0")) #4
        progress.setValue(3)
        self.ui.stackedWidget.addWidget(AdminVentas(self.ui)) #5
        progress.setValue(4)
        self.ui.stackedWidget.addWidget(MesasVenta(self,self.num_mesas,self.rut)) #6
        progress.setValue(5)
        self.ui.stackedWidget.addWidget(Estadistica()) # 7
        progress.setValue(6)
        self.ui.stackedWidget.addWidget(FormularioVenta(self.ui,self.rut,"-1")) # 8
        progress.setValue(7)

        pixmap = QtGui.QPixmap('images/cafe_nostro_load_mesas.png')
        label.setPixmap(pixmap)

        for i in range(1,self.num_mesas+1): #9 = primera mesa
            self.ui.stackedWidget.addWidget(FormularioVenta(self.ui,self.rut,str(i)))
            progress.setValue(i+5)

        
        progress.setValue(self.num_mesas+7)
        self.setVisible(True)

    def config_user(self):
        """
        Configura aspectos del programa dependiendo el nombre y el tipo de
        usuario que se haya logueado al inicio.
        Si el usuario no es administrador bloquea todas las funcionalidades
        administrativas que el programa ofrece.
        """
        self.nombre = (
            unicode(
                controller.getUsuarioRut(self.rut)[0].nombre.decode('cp1252'))+
            " "+
            unicode(
                controller.getUsuarioRut(self.rut)[0].apellido.decode('cp1252')))
        if(controller.getUsuarioRut(self.rut)[0].nombre == "root"):
            self.nombre = "ROOT"
        self.ui.label_usuario.setText(
            u"<font color='white' size='5'><b>"+self.nombre+"</b></font>")
        if(self.tipo != None):
            if(self.tipo == 1):
                self.ui.actionUsuarios.setEnabled(False)
                self.ui.actionProductos.setEnabled(False)
                self.ui.actionVentas.setEnabled(False)
                self.ui.actionEstadisticas.setEnabled(False)
                self.ui.actionDatos_empresa.setEnabled(False)

    def set_signals(self):
        'Setea los triggers que se usaran para cambiar la interfaz'
        self.ui.actionVentas.triggered.connect(self.admin_ventas)
        self.ui.actionUsuarios.triggered.connect(self.admin_users)
        self.ui.actionProductos.triggered.connect(self.admin_productos)
        self.ui.actionEstadisticas.triggered.connect(self.admin_estadisticas)
        self.ui.actionDatos_empresa.triggered.connect(self.admin_empresa)
        self.ui.actionSalir.triggered.connect(self.close)

        self.ui.pushButton_compra_directa.clicked.connect(self.formulario_venta_directa)
        self.ui.pushButton_mesas.clicked.connect(self.mesas_venta)
        self.ui.stackedWidget.currentChanged.connect(self.stackedWidget_changed)

    def stackedWidget_changed(self,index):
        """
        Método que es llamado cuando se cambia el indice del QStackedWidget.
        Recorre los pedidos de todas las mesas definidas para otorgar un
        estado 'ocupado' en caso de que aun no se haya cerrado dicho pedido
        y un estado 'no ocupado' en caso contrario.
        """
        for i in range(9,self.num_mesas+10):
            try:
                id_pedido = self.ui.stackedWidget.widget(i).id_pedido
                pedido = controller_venta.getPedido(id_pedido)
                if(pedido[0].en_curso == 0):
                    self.ui.stackedWidget.widget(i).set_ocupado(False)
                else:
                    self.ui.stackedWidget.widget(i).set_ocupado(True)
            except:
                pass
    def admin_empresa(self):
        'Abre la interfaz de configuracion de los datos de la empresa'
        config_empresa = FormularioEmpresa(self.ui.stackedWidget.widget(6))
        config_empresa.exec_()

    def admin_estadisticas(self):
        'Cambia a la interfaz de estadisticas'
        self.ui.stackedWidget.setCurrentIndex(7)
        self.ui.stackedWidget.widget(7).actualizar_productos()

    def mesas_venta(self):
        'Cambia a la interfaz de venta por mesas'
        self.ui.stackedWidget.setCurrentIndex(6)

    def admin_users(self):
        'Cambia a la interfaz de administración de usuarios'
        self.ui.stackedWidget.setCurrentIndex(2)

    def admin_productos(self):
        'Cambia a la interfaz de administración de productos'
        self.ui.stackedWidget.setCurrentIndex(3)

    def formulario_venta_directa(self):
        'Cambia a la interfaz de formulario de venta directa'
        self.ui.stackedWidget.setCurrentIndex(4)

    def admin_ventas(self):
        'Cambia a la interfaz de editar ventas de productos'
        self.ui.stackedWidget.setCurrentIndex(5)