def create_options_toolbar(self):

        self.collapsable_options_toolbar = Ui_horizontalCollapsableWidget()
        buttons_layout = QtGui.QHBoxLayout()
        buttons_layout.setSpacing(0)
        buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.collapsable_options_toolbar.set_direction('right')
        self.collapsable_options_toolbar.setLayout(buttons_layout)
        self.collapsable_options_toolbar.setCollapsed(True)

        self.auto_save_check_box = QtGui.QCheckBox('Autosave')
        self.auto_save_check_box.setChecked(False)

        self.filter_process_check_box = QtGui.QCheckBox('Filter')
        self.filter_process_check_box.setChecked(False)

        self.process_combo_box = Ui_coloredComboBox()
        self.process_combo_box.setEnabled(False)

        QtCore.QObject.connect(self.filter_process_check_box,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.process_combo_box.setEnabled)

        buttons_layout.addWidget(self.filter_process_check_box)
        buttons_layout.addWidget(self.process_combo_box)
        buttons_layout.addWidget(self.auto_save_check_box)

        self.main_layout.addWidget(self.collapsable_options_toolbar, 0, 1, 1,
                                   1)
Esempio n. 2
0
    def create_right_collapsable_toolbar(self):
        self.right_collapsable_toolbar = Ui_horizontalCollapsableWidget()
        self.right_collapsable_toolbar.setCollapsed(False)

        self.right_buttons_layout = QtGui.QHBoxLayout()
        self.right_buttons_layout.setSpacing(0)
        self.right_buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.right_collapsable_toolbar.setLayout(self.right_buttons_layout)

        self.refresh_serverside_scripts_button = QtGui.QToolButton()
        self.refresh_serverside_scripts_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.refresh_serverside_scripts_button.setAutoRaise(True)
        self.refresh_serverside_scripts_button.setMinimumSize(
            QtCore.QSize(24, 24))
        self.refresh_serverside_scripts_button.setMaximumSize(
            QtCore.QSize(24, 24))
        self.refresh_serverside_scripts_button.setIcon(
            gf.get_icon('refresh', icons_set='mdi'))
        self.refresh_serverside_scripts_button.setToolTip(
            'Refresh all Scripts Tree from Server')

        self.right_buttons_layout.addWidget(
            self.refresh_serverside_scripts_button)
    def create_toolbar(self):

        self.collapsable_toolbar = Ui_horizontalCollapsableWidget()
        buttons_layout = QtGui.QHBoxLayout()
        buttons_layout.setSpacing(0)
        buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.collapsable_toolbar.set_direction('right')
        self.collapsable_toolbar.setLayout(buttons_layout)
        self.collapsable_toolbar.setCollapsed(False)

        self.save_button = QtGui.QToolButton()
        self.save_button.setAutoRaise(True)
        self.save_button.setIcon(
            gf.get_icon('content-save', icons_set='mdi', scale_factor=1))
        self.save_button.setToolTip('Save Current Changes')

        self.refresh_button = QtGui.QToolButton()
        self.refresh_button.setAutoRaise(True)
        self.refresh_button.setIcon(
            gf.get_icon('refresh', icons_set='mdi', scale_factor=1.3))
        self.refresh_button.setToolTip('Refresh Current Tasks')

        buttons_layout.addWidget(self.save_button)
        buttons_layout.addWidget(self.refresh_button)

        self.main_layout.addWidget(self.collapsable_toolbar, 0, 0, 1, 1)
    def create_collapsable_toolbar(self):
        self.collapsable_toolbar = Ui_horizontalCollapsableWidget()
        self.collapsable_toolbar.setText('Quick Config')

        self.buttons_layout = QtGui.QHBoxLayout()
        self.buttons_layout.setSpacing(0)
        self.buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.collapsable_toolbar.setLayout(self.buttons_layout)
        self.collapsable_toolbar.setCollapsed(True)

        self.expandingLayout.addWidget(self.collapsable_toolbar)
Esempio n. 5
0
    def create_left_collapsable_toolbar(self):
        self.left_collapsable_toolbar = Ui_horizontalCollapsableWidget()
        self.left_collapsable_toolbar.setCollapsed(False)

        self.left_buttons_layout = QtGui.QHBoxLayout()
        self.left_buttons_layout.setSpacing(0)
        self.left_buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.left_collapsable_toolbar.setLayout(self.left_buttons_layout)

        self.add_new_script_button = QtGui.QToolButton()
        self.add_new_script_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.add_new_script_button.setAutoRaise(True)
        self.add_new_script_button.setMinimumSize(QtCore.QSize(24, 24))
        self.add_new_script_button.setMaximumSize(QtCore.QSize(24, 24))
        self.add_new_script_button.setIcon(
            gf.get_icon('plus-box', icons_set='mdi'))
        self.add_new_script_button.setToolTip('Create New Script')

        self.cleanup_output_button = QtGui.QToolButton()
        self.cleanup_output_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.cleanup_output_button.setAutoRaise(True)
        self.cleanup_output_button.setMinimumSize(QtCore.QSize(24, 24))
        self.cleanup_output_button.setMaximumSize(QtCore.QSize(24, 24))
        self.cleanup_output_button.setIcon(
            gf.get_icon('eraser', icons_set='mdi'))
        self.cleanup_output_button.setToolTip('Clean-up Output Window')

        self.save_current_script_button = QtGui.QToolButton()
        self.save_current_script_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.save_current_script_button.setAutoRaise(True)
        self.save_current_script_button.setMinimumSize(QtCore.QSize(24, 24))
        self.save_current_script_button.setMaximumSize(QtCore.QSize(24, 24))
        self.save_current_script_button.setIcon(
            gf.get_icon('content-save', icons_set='mdi'))
        self.save_current_script_button.setToolTip(
            'Save current Script to Sever')

        self.left_buttons_layout.addWidget(self.add_new_script_button)
        self.left_buttons_layout.addWidget(self.save_current_script_button)
        self.left_buttons_layout.addWidget(self.cleanup_output_button)
Esempio n. 6
0
    def create_options_toolbar(self):

        self.collapsable_options_toolbar = Ui_horizontalCollapsableWidget()
        buttons_layout = QtGui.QHBoxLayout()
        buttons_layout.setSpacing(9)
        buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.collapsable_options_toolbar.set_direction('right')
        self.collapsable_options_toolbar.setLayout(buttons_layout)
        self.collapsable_options_toolbar.setCollapsed(True)

        self.auto_save_check_box = QtGui.QCheckBox('Autosave')
        self.auto_save_check_box.setChecked(False)

        self.definition_label = QtGui.QLabel('Definition: ')

        self.definition_combo_box = QtGui.QComboBox()

        buttons_layout.addWidget(self.definition_label)
        buttons_layout.addWidget(self.definition_combo_box)
        buttons_layout.addWidget(self.auto_save_check_box)

        self.main_layout.addWidget(self.collapsable_options_toolbar, 0, 1, 1,
                                   1)
class Ui_dropPlateWidget(QtGui.QWidget, ui_drop_plate.Ui_dropPlate):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent=parent)

        self.tree_items = []

        self.setupUi(self)

        self.setAcceptDrops(True)

        self.create_ui()

        self.create_config_widget()
        self.controls_actions()

    def threads_fill_items(self, kwargs, exec_after_added=None):

        worker = env_inst.local_pool.add_task(self.get_files_objects, kwargs)

        worker.result.connect(self.append_items_to_tree)
        if exec_after_added:
            worker.finished.connect(exec_after_added)
        worker.error.connect(gf.error_handle)
        worker.start()

    def create_ui(self):

        self.clearPushButton.setIcon(gf.get_icon('trash'))
        self.configPushButton.setIcon(gf.get_icon('settings', icons_set='mdi'))
        self.create_progress_bar_widget()

        self.create_collapsable_toolbar()

        self.setAcceptDrops(True)

        if env_mode.get_mode() == 'standalone':
            sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                           QtGui.QSizePolicy.Preferred)
            self.setSizePolicy(sizePolicy)
            self.setMinimumWidth(300)

        self.move_controls_to_collapsable_toolbar()

        self.customize_ui()

    def customize_ui(self):
        self.dropTreeWidget.setSelectionMode(
            QtGui.QAbstractItemView.ExtendedSelection)
        self.dropTreeWidget.setDragDropMode(QtGui.QAbstractItemView.DragOnly)
        self.dropTreeWidget.setStyleSheet(gf.get_qtreeview_style())

    def create_progress_bar_widget(self):
        self.progressBar = QtGui.QProgressBar()
        self.progressBar.setMaximum(100)
        self.progressBarLayout.addWidget(self.progressBar)
        self.progressBar.setTextVisible(True)
        self.progressBar.setVisible(False)

    def create_config_widget(self):
        self.config_widget = Ui_matchingTemplateConfigWidget(self)

    def create_collapsable_toolbar(self):
        self.collapsable_toolbar = Ui_horizontalCollapsableWidget()
        self.collapsable_toolbar.setText('Quick Config')

        self.buttons_layout = QtGui.QHBoxLayout()
        self.buttons_layout.setSpacing(0)
        self.buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.collapsable_toolbar.setLayout(self.buttons_layout)
        self.collapsable_toolbar.setCollapsed(True)

        self.expandingLayout.addWidget(self.collapsable_toolbar)

    def add_widget_to_collapsable_toolbar(self, widget):
        self.buttons_layout.addWidget(widget)

    def move_controls_to_collapsable_toolbar(self):
        self.add_widget_to_collapsable_toolbar(self.groupCheckinCheckBox)
        self.add_widget_to_collapsable_toolbar(self.keepFileNameCheckBox)
        self.add_widget_to_collapsable_toolbar(self.includeSubfoldersCheckBox)
        self.collapsable_toolbar.setCollapsed(False)

    def controls_actions(self):

        self.clearPushButton.clicked.connect(self.clear_tree_widget)
        self.configPushButton.clicked.connect(self.config_widget.exec_)
        # self.groupCheckinCheckBox.stateChanged.connect(self.enable_group_checkin)

        self.create_files_tree_context_menu()

    def clear_tree_widget(self):

        self.dropTreeWidget.clear()
        self.tree_items = []

    def create_files_tree_context_menu(self):
        self.dropTreeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.dropTreeWidget.customContextMenuRequested.connect(self.open_menu)

    def open_menu(self):
        item = self.dropTreeWidget.selectedIndexes()
        if item:
            menu = self.file_context_menu()
            if menu:
                menu.exec_(Qt4Gui.QCursor.pos())
        else:
            menu = self.drop_plate_context_menu()
            if menu:
                menu.exec_(Qt4Gui.QCursor.pos())

    @gf.catch_error
    def open_file_from_tree(self):
        item = self.get_selected_items()
        for it in item:
            it.open_file()

    @gf.catch_error
    def open_folder_from_tree(self):
        item = self.get_selected_items()
        for it in item:
            it.open_folder()

    @gf.catch_error
    def copy_path_from_tree(self):
        item = self.get_selected_items()
        clipboard = QtGui.QApplication.instance().clipboard()
        files_list = set()
        for it in item:
            files_list.add(it.get_file_path())
        clipboard.setText('\n'.join(files_list))

    @gf.catch_error
    def copy_abs_path_from_tree(self):
        item = self.get_selected_items()
        clipboard = QtGui.QApplication.instance().clipboard()
        files_list = []
        for it in item:
            files_list.extend(it.get_all_files_list())
        clipboard.setText('\n'.join(files_list))

    def file_context_menu(self):
        open_file = QtGui.QAction('Open File', self.dropTreeWidget)
        open_file.setIcon(gf.get_icon('folder'))
        open_file.triggered.connect(self.open_file_from_tree)

        open_file_folder = QtGui.QAction('Show Folder', self.dropTreeWidget)
        open_file_folder.setIcon(gf.get_icon('folder-open'))
        open_file_folder.triggered.connect(self.open_folder_from_tree)

        copy_path = QtGui.QAction("Copy File Path", self.dropTreeWidget)
        copy_path.setIcon(gf.get_icon('copy'))
        copy_path.triggered.connect(self.copy_path_from_tree)

        copy_abs_path = QtGui.QAction("Copy Absolute File Path",
                                      self.dropTreeWidget)
        copy_abs_path.setIcon(gf.get_icon('copy'))
        copy_abs_path.triggered.connect(self.copy_abs_path_from_tree)

        add_file = QtGui.QAction('Add More Files', self.dropTreeWidget)
        add_file.setIcon(gf.get_icon('folder-open'))
        add_file.triggered.connect(self.add_files_from_menu)

        menu = QtGui.QMenu()

        menu.addAction(open_file)
        menu.addAction(open_file_folder)
        menu.addAction(copy_path)
        menu.addAction(copy_abs_path)
        menu.addAction(add_file)

        return menu

    def drop_plate_context_menu(self):
        add_file = QtGui.QAction('Add Files', self.dropTreeWidget)
        add_file.setIcon(gf.get_icon('folder-open'))
        add_file.triggered.connect(self.add_files_from_menu)

        paste_from_clipboard = QtGui.QAction('Paste From Clipboard',
                                             self.dropTreeWidget)
        paste_from_clipboard.setIcon(gf.get_icon('folder-open'))
        paste_from_clipboard.triggered.connect(self.add_files_from_clipboard)

        menu = QtGui.QMenu()

        menu.addAction(add_file)
        menu.addAction(paste_from_clipboard)

        return menu

    def add_files_from_menu(self, exec_after_added=None):

        options = QtGui.QFileDialog.Options()
        options |= QtGui.QFileDialog.DontUseNativeDialog
        files_names, filter = QtGui.QFileDialog.getOpenFileNames(
            self, 'Adding files to Drop Pate', '', 'All Files (*.*);;', '',
            options)

        if files_names:
            self.threads_fill_items(files_names, exec_after_added)
            # files_objects = self.get_files_objects(files_names)
            # self.append_items_to_tree(files_objects)
            # if exec_after_added:
            #     exec_after_added(files_objects)

    def add_files_from_clipboard(self, exec_after_added=None):
        clipboard = QtGui.QApplication.clipboard()
        files_names = clipboard.text()

        if files_names:
            files_names = set(files_names.split('\n'))
            self.threads_fill_items(files_names, exec_after_added)

    def get_selected_items(self):
        selected_items = []

        if self.tree_items:

            for item in self.dropTreeWidget.selectedItems():
                # index = item.data(0, QtCore.Qt.UserRole)
                file_object = item.data(1, QtCore.Qt.UserRole)
                # print file_object
                # for i, itm in enumerate(self.tree_items):
                #     print itm, i
                #     if i == index:
                #         selected_items.append(itm)
                #         break
                selected_items.append(file_object)

        return selected_items

    def get_files_objects(self, items):
        if self.includeSubfoldersCheckBox.isChecked():

            dirs_and_files = gf.split_files_and_dirs(items)

            for dirs in dirs_and_files[0]:
                for path, subdirs, files in os.walk(dirs):
                    for name in files:
                        items.append(os.path.join(path, name))
                    for s_dir in subdirs:
                        items.append(os.path.join(path, s_dir))

        match_template = gf.MatchTemplate(
            self.config_widget.get_templates_list(),
            padding=self.config_widget.get_min_padding())

        return match_template.get_files_objects(items)

    def remove_selected_items(self):
        if self.tree_items:
            for item in self.dropTreeWidget.selectedItems():
                index = item.data(0, QtCore.Qt.UserRole)
                for i, itm in enumerate(self.tree_items):
                    if i == index:
                        self.tree_items.pop(index)

                item_index = self.dropTreeWidget.indexFromItem(item)
                self.dropTreeWidget.takeTopLevelItem(item_index.row())

    def append_items_to_tree(self, files_objects_dict):
        self.dropTreeWidget.clearSelection()

        icon_provider = QtGui.QFileIconProvider()

        self.progressBar.setVisible(True)

        for item_type, item in files_objects_dict.items():

            for i, file_obj in enumerate(item):
                tree_item = QtGui.QTreeWidgetItem()
                tree_item.setText(0, file_obj.get_pretty_file_name())
                sequence_info_string = []
                frameranges = file_obj.get_sequence_frameranges_string('[]')
                tiles_count = file_obj.get_tiles_count()
                layer = file_obj.get_layer()
                if frameranges:
                    sequence_info_string.append(frameranges)
                if tiles_count:
                    sequence_info_string.append(
                        '{0} Tile(s)'.format(tiles_count))
                if layer:
                    sequence_info_string.append(layer)
                tree_item.setText(1, ' / '.join(sequence_info_string))
                tree_item.setText(2, file_obj.get_base_file_type_pretty_name())
                tree_item.setText(3, file_obj.get_base_file_type())
                tree_item.setText(4, file_obj.get_file_path())

                file_icon = icon_provider.icon(
                    file_obj.get_all_files_list(True))
                tree_item.setIcon(0, file_icon)

                self.dropTreeWidget.addTopLevelItem(tree_item)

                # TODO fix this (we need to select all)
                # if self.dropTreeWidget.topLevelItemCount() < 50:  # for performance reasons
                self.dropTreeWidget.setItemSelected(tree_item, True)
                # else:
                #     self.dropTreeWidget.clearSelection()

                tree_item.setData(0, QtCore.Qt.UserRole, len(self.tree_items))
                tree_item.setData(1, QtCore.Qt.UserRole, file_obj)
                self.tree_items.append(file_obj)

                # if i+1 % 50 == 0:
                #     QtGui.QApplication.processEvents()

                self.progressBar.setValue(int(i + 1 * 100 / len(item)))

        self.progressBar.setValue(100)
        self.dropTreeWidget.resizeColumnToContents(0)
        self.dropTreeWidget.resizeColumnToContents(1)
        self.dropTreeWidget.resizeColumnToContents(2)
        self.dropTreeWidget.resizeColumnToContents(3)
        self.dropTreeWidget.resizeColumnToContents(4)

        # self.dropTreeWidget.sortByColumn(0, QtCore.Qt.AscendingOrder)
        self.progressBar.setVisible(False)

    def get_keep_filename(self):

        return self.keepFileNameCheckBox.isChecked()

    def set_settings_from_dict(self, settings_dict=None):

        ref_settings_dict = {
            'includeSubfoldersCheckBox': False,
            'keepFileNameCheckBox': False,
            'groupCheckinCheckBox': False,
        }

        settings = gf.check_config(ref_settings_dict, settings_dict)

        self.includeSubfoldersCheckBox.setChecked(
            settings['includeSubfoldersCheckBox'])
        self.keepFileNameCheckBox.setChecked(settings['keepFileNameCheckBox'])
        self.groupCheckinCheckBox.setChecked(settings['groupCheckinCheckBox'])

    def get_settings_dict(self):

        settings_dict = {
            'includeSubfoldersCheckBox':
            int(self.includeSubfoldersCheckBox.isChecked()),
            'keepFileNameCheckBox':
            int(self.keepFileNameCheckBox.isChecked()),
            'groupCheckinCheckBox':
            int(self.groupCheckinCheckBox.isChecked()),
        }

        return settings_dict

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls:
            event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):

        # print event.mimeData()
        # print event.mimeData().text()
        # print event.mimeData().urls()

        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            links = []
            for url in event.mimeData().urls():
                links.append(url.toLocalFile())
            self.threads_fill_items(links)
        else:
            event.ignore()
class Ui_tasksDockWidget(QtGui.QWidget):
    def __init__(self, project=None, parent=None):
        super(self.__class__, self).__init__(parent=parent)

        self.project = project
        self.sobject = None
        self.task_widgets_list = []
        self.tasks_sobjects = None

        self.create_ui()
        self.controls_actions()

    def controls_actions(self):
        self.save_button.clicked.connect(self.save_tasks)
        self.refresh_button.clicked.connect(self.refresh_tasks)

    def create_ui(self):

        self.create_main_layout()

        self.create_toolbar()
        self.create_options_toolbar()

        self.create_stretch()

        self.create_scroll_area()

        self.create_no_notes_label()

    def create_main_layout(self):
        self.main_layout = QtGui.QGridLayout(self)
        self.main_layout.setSpacing(0)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.main_layout)

    def create_toolbar(self):

        self.collapsable_toolbar = Ui_horizontalCollapsableWidget()
        buttons_layout = QtGui.QHBoxLayout()
        buttons_layout.setSpacing(0)
        buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.collapsable_toolbar.set_direction('right')
        self.collapsable_toolbar.setLayout(buttons_layout)
        self.collapsable_toolbar.setCollapsed(False)

        self.save_button = QtGui.QToolButton()
        self.save_button.setAutoRaise(True)
        self.save_button.setIcon(
            gf.get_icon('content-save', icons_set='mdi', scale_factor=1))
        self.save_button.setToolTip('Save Current Changes')

        self.refresh_button = QtGui.QToolButton()
        self.refresh_button.setAutoRaise(True)
        self.refresh_button.setIcon(
            gf.get_icon('refresh', icons_set='mdi', scale_factor=1.3))
        self.refresh_button.setToolTip('Refresh Current Tasks')

        buttons_layout.addWidget(self.save_button)
        buttons_layout.addWidget(self.refresh_button)

        self.main_layout.addWidget(self.collapsable_toolbar, 0, 0, 1, 1)

    def create_options_toolbar(self):

        self.collapsable_options_toolbar = Ui_horizontalCollapsableWidget()
        buttons_layout = QtGui.QHBoxLayout()
        buttons_layout.setSpacing(0)
        buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.collapsable_options_toolbar.set_direction('right')
        self.collapsable_options_toolbar.setLayout(buttons_layout)
        self.collapsable_options_toolbar.setCollapsed(True)

        self.auto_save_check_box = QtGui.QCheckBox('Autosave')
        self.auto_save_check_box.setChecked(False)

        self.filter_process_check_box = QtGui.QCheckBox('Filter')
        self.filter_process_check_box.setChecked(False)

        self.process_combo_box = Ui_coloredComboBox()
        self.process_combo_box.setEnabled(False)

        QtCore.QObject.connect(self.filter_process_check_box,
                               QtCore.SIGNAL("toggled(bool)"),
                               self.process_combo_box.setEnabled)

        buttons_layout.addWidget(self.filter_process_check_box)
        buttons_layout.addWidget(self.process_combo_box)
        buttons_layout.addWidget(self.auto_save_check_box)

        self.main_layout.addWidget(self.collapsable_options_toolbar, 0, 1, 1,
                                   1)

    def create_stretch(self):
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Minimum)
        self.main_layout.addItem(spacerItem, 0, 2, 1, 1)
        self.main_layout.setColumnStretch(2, 1)

    def create_scroll_area(self):
        from thlib.side.flowlayout import FlowLayout

        self.scroll_area_contents = QtGui.QWidget()
        self.scroll_area_contents.setContentsMargins(9, 9, 0, 0)

        self.scroll_area = QtGui.QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setWidget(self.scroll_area_contents)

        self.scroll_area_layout = FlowLayout(self.scroll_area_contents)

        self.scroll_area_layout.setAlignment(QtCore.Qt.AlignTop)
        self.scroll_area_layout.setContentsMargins(9, 9, 0, 0)
        self.scroll_area_layout.setSpacing(9)

        self.main_layout.addWidget(self.scroll_area, 1, 0, 1, 3)

    def create_no_notes_label(self):
        self.no_notes_label = QtGui.QLabel()
        self.no_notes_label.setMinimumSize(0, 0)
        self.no_notes_label.setText('Select Item to See Tasks...')
        self.no_notes_label.setAlignment(QtCore.Qt.AlignHCenter
                                         | QtCore.Qt.AlignVCenter)

        self.scroll_area_layout.addWidget(self.no_notes_label)

    def toggle_no_notes_label(self):
        if self.no_notes_label.isVisible():
            self.no_notes_label.setHidden(True)
        else:
            self.no_notes_label.setHidden(False)

    def save_tasks(self):
        # groupped_tasks_sobjects = tc.group_sobject_by(self.tasks_sobjects, 'process')

        # for process, task_sobjects in groupped_tasks_sobjects.items():
        for task_widget in self.task_widgets_list:
            print task_widget.is_task_changed()
            # if task_widget.get_process() == process:
            #     task_widget.set_tasks_sobjects(task_sobjects)

    def refresh_tasks(self):
        if self.sobject:
            self.task_widgets_list = []

            self.create_filler_tasks()

            self.query_tasks()

    def query_tasks(self):
        def get_tasks_sobjects_agent():
            return self.sobject.get_tasks_sobjects()

        env_inst.set_thread_pool(None, 'server_query/server_thread_pool')

        get_tasks_sobjects_worker = gf.get_thread_worker(
            get_tasks_sobjects_agent,
            env_inst.get_thread_pool('server_query/server_thread_pool'),
            result_func=self.fill_tasks,
            error_func=gf.error_handle,
        )
        get_tasks_sobjects_worker.try_start()

    def create_filler_tasks(self):
        self.clear_scroll_area()
        self.process_combo_box.clear()

        stype = self.sobject.get_stype()
        # getting all possible processes here
        processes = []
        pipeline_code = self.sobject.get_pipeline_code()
        current_pipeline = None
        if pipeline_code and stype.pipeline:
            current_pipeline = stype.pipeline.get(pipeline_code)
            if current_pipeline:
                processes = current_pipeline.pipeline.keys()

        # if self.ignore_dict:
        #     if self.ignore_dict.get('show_builtins'):
        #         show_all = True
        #         for builtin in ['icon', 'attachment', 'publish']:
        #             if builtin not in self.ignore_dict['builtins']:
        #                 processes.append(builtin)
        #                 show_all = False
        #         if show_all:
        #             processes.extend(['icon', 'attachment', 'publish'])

        for process in processes:
            process_info = current_pipeline.get_pipeline_info(process)

            ignored = False

            # Ignoring PROGRESS, ACTION, CONDITION processes
            # TODO Special case for progress, we should fetch completeness of progress node as in tactic.
            if process_info.get('type') in [
                    'action', 'condition', 'dependency', 'progress'
            ]:
                ignored = True

            if not ignored:
                # Filling process combo box
                if process_info:
                    process_color = process_info.get('color')
                    if not process_color:
                        process_object = current_pipeline.get_pipeline_process(
                            process)
                        if process_object:
                            process_color = process_object.get('color')

                    process_label = process_info.get('label')
                    if process_label:
                        if process_color:
                            self.process_combo_box.add_item(
                                process_label,
                                hex_color=process_color,
                                item_data=process)
                        else:
                            self.process_combo_box.add_item(
                                process_label,
                                hex_color='#484848',
                                item_data=process)
                    else:
                        self.process_combo_box.add_item(process,
                                                        hex_color='#484848',
                                                        item_data=process)
                else:
                    self.process_combo_box.add_item(process,
                                                    hex_color='#484848',
                                                    item_data=process)

                # creating and adding Simple task widgets
                task_widget = Ui_simpleTaskWidget(process, self.sobject)
                self.task_widgets_list.append(task_widget)
                self.scroll_area_layout.addWidget(task_widget)

    def clear_scroll_area(self):
        self.scroll_area_layout.clear_items()

    def fill_tasks(self, query_result):

        self.tasks_sobjects, info = query_result

        self.create_filler_tasks()

        groupped_tasks_sobjects = tc.group_sobject_by(self.tasks_sobjects,
                                                      'process')

        for process, task_sobjects in groupped_tasks_sobjects.items():
            for task_widget in self.task_widgets_list:
                if task_widget.get_process() == process:
                    task_widget.set_tasks_sobjects(task_sobjects)

        self.set_dock_title(u'Tasks For: {0}'.format(self.sobject.get_title()))

    def bring_dock_widget_up(self):

        related_tasks_dock = env_inst.get_check_tree(
            self.project.get_code(), 'checkin_out_instanced_widgets',
            'tasks_dock')

        dock_widget = related_tasks_dock.parent()
        if dock_widget:
            if isinstance(dock_widget, QtGui.QDockWidget):
                dock_widget.setHidden(False)
                dock_widget.raise_()

    def set_dock_title(self, title_string):

        related_tasks_dock = env_inst.get_check_tree(
            self.project.get_code(), 'checkin_out_instanced_widgets',
            'tasks_dock')

        dock_widget = related_tasks_dock.parent()
        if dock_widget:
            if isinstance(dock_widget, QtGui.QDockWidget):
                dock_widget.setWindowTitle(title_string)

    def set_sobject(self, sobject, force=False):

        # Do something only if widget is visible to user
        if force:
            self.task_widgets_list = []
            self.sobject = sobject
            self.query_tasks()
        elif not self.visibleRegion().isEmpty():
            self.task_widgets_list = []
            self.sobject = sobject
            self.query_tasks()
Esempio n. 9
0
class Ui_columnsEditorWidget(QtGui.QWidget):
    def __init__(self, project, stype, parent=None):
        super(self.__class__, self).__init__(parent=parent)

        self.project = project
        self.stype = stype
        self.item = None
        self.items = []
        self.columns_widgets = []
        self.multiple_mode = False

        self.current_active_tab = 0

        self.create_ui()

    def create_ui(self):

        self.create_main_layout()

        self.create_toolbar()
        self.create_options_toolbar()
        self.create_stretch()

        self.create_tabbed_widget()

        self.controls_actions()

    def create_main_layout(self):
        self.main_layout = QtGui.QGridLayout()
        self.main_layout.setSpacing(0)
        self.main_layout.setContentsMargins(0, 0, 0, 0)

        self.setLayout(self.main_layout)

    def controls_actions(self):
        self.save_button.clicked.connect(self.save_all_changes)
        self.refresh_button.clicked.connect(self.refresh)
        self.definition_combo_box.currentIndexChanged.connect(self.refresh)

    def create_toolbar(self):

        self.collapsable_toolbar = Ui_horizontalCollapsableWidget()
        buttons_layout = QtGui.QHBoxLayout()
        buttons_layout.setSpacing(0)
        buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.collapsable_toolbar.set_direction('right')
        self.collapsable_toolbar.setLayout(buttons_layout)
        self.collapsable_toolbar.setCollapsed(False)

        self.save_button = QtGui.QToolButton()
        self.save_button.setAutoRaise(True)
        self.save_button.setIcon(
            gf.get_icon('content-save-all', icons_set='mdi', scale_factor=1))
        self.save_button.setToolTip('Save Current Changes')

        self.refresh_button = QtGui.QToolButton()
        self.refresh_button.setAutoRaise(True)
        self.refresh_button.setIcon(
            gf.get_icon('refresh', icons_set='mdi', scale_factor=1.3))
        self.refresh_button.setToolTip('Refresh Current Tasks')

        buttons_layout.addWidget(self.save_button)
        buttons_layout.addWidget(self.refresh_button)

        self.main_layout.addWidget(self.collapsable_toolbar, 0, 0, 1, 1)

    def create_options_toolbar(self):

        self.collapsable_options_toolbar = Ui_horizontalCollapsableWidget()
        buttons_layout = QtGui.QHBoxLayout()
        buttons_layout.setSpacing(9)
        buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.collapsable_options_toolbar.set_direction('right')
        self.collapsable_options_toolbar.setLayout(buttons_layout)
        self.collapsable_options_toolbar.setCollapsed(True)

        self.auto_save_check_box = QtGui.QCheckBox('Autosave')
        self.auto_save_check_box.setChecked(False)

        self.definition_label = QtGui.QLabel('Definition: ')

        self.definition_combo_box = QtGui.QComboBox()

        buttons_layout.addWidget(self.definition_label)
        buttons_layout.addWidget(self.definition_combo_box)
        buttons_layout.addWidget(self.auto_save_check_box)

        self.main_layout.addWidget(self.collapsable_options_toolbar, 0, 1, 1,
                                   1)

    def create_stretch(self):
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Minimum)
        self.main_layout.addItem(spacerItem, 0, 2, 1, 1)
        self.main_layout.setColumnStretch(2, 1)

    def fill_definition_combo_box(self):

        self.definition_combo_box.clear()

        stype = self.item.stype

        if stype.info.get('definition'):
            current_idx = 0
            default_current_definition = 'table'

            for idx, definition in enumerate(stype.info['definition'].keys()):
                if definition == default_current_definition:
                    current_idx = idx
                self.definition_combo_box.addItem(gf.prettify_text(definition))
                self.definition_combo_box.setItemData(idx, definition,
                                                      QtCore.Qt.UserRole)

            self.definition_combo_box.setCurrentIndex(current_idx)

    def save_all_changes(self):

        if self.multiple_mode:
            data_to_update = {}

            for item in self.items:
                update_dict = {}
                for column_widget in self.columns_widgets:
                    changed_data = column_widget.get_changed_data()
                    if changed_data is not None:
                        update_dict[column_widget.get_column()] = changed_data

                if self.item.type == 'snapshot':
                    sobject = item.get_snapshot()
                    sobject.project = self.project  # Snapshot class created without project in it
                else:
                    sobject = item.get_sobject()

                data_to_update[sobject.get_search_key()] = update_dict

            return tc.server_start(
                project=self.project.get_code()).update_multiple(
                    data=data_to_update, triggers=True)
        else:

            if self.item.type == 'snapshot':
                sobject = self.item.get_snapshot()
                sobject.project = self.project  # Snapshot class created without project in it
            else:
                sobject = self.item.get_sobject()

            for column_widget in self.columns_widgets:
                changed_data = column_widget.get_changed_data()
                if changed_data is not None:
                    sobject.set_value(column_widget.get_column(), changed_data)

            sobject.commit()

    def set_dock_title(self, title_string):

        checkin_out_widget = env_inst.get_check_tree(self.project.get_code(),
                                                     'checkin_out',
                                                     self.stype.get_code())

        columns_viewer_widget = checkin_out_widget.get_columns_viewer_widget()

        dock_widget = columns_viewer_widget.parent()
        if dock_widget:
            if isinstance(dock_widget, QtGui.QDockWidget):
                dock_widget.setWindowTitle(title_string)

    def refresh(self):
        if self.multiple_mode:
            self.customize_with_multiple_items()
        else:
            self.customize_with_item()

    def set_items(self, items_list):

        if not self.visibleRegion().isEmpty():
            self.items = items_list

            self.fill_definition_combo_box()

            if self.items:
                self.customize_with_multiple_items()
            else:
                self.customize_without_item()

    def set_item(self, item):
        if not self.visibleRegion().isEmpty():
            self.item = item
            s = gf.time_it()
            # self.fill_definition_combo_box()
            gf.time_it(s)

            if self.item:
                self.customize_with_item()
            else:
                self.customize_without_item()

    def customize_with_multiple_items(self):

        self.multiple_mode = True

        self.current_active_tab = self.columns_tab_widget.currentIndex()

        self.columns_tab_widget.clear()
        self.columns_widgets = []

        self.set_dock_title(u'Multiple Editing Mode for: {0} items'.format(
            len(self.items)))

        table_columns = []
        stype = self.item.stype

        idx = self.definition_combo_box.currentIndex()
        current_definition = self.definition_combo_box.itemData(
            idx, QtCore.Qt.UserRole)
        if not current_definition:
            current_definition = 'table'

        for i in stype.get_definition(current_definition):
            table_columns.append(i.get('name'))

        exclude_columns = [
            '__search_type__', '__search_key__', '__tasks_count__',
            '__notes_count__', '__snapshots__'
        ]

        if self.item.type == 'snapshot':
            sobject = self.item.get_snapshot()
        else:
            sobject = self.item.get_sobject()

        if sobject:
            sobject_dict = sobject.get_info()
            for column, val in sobject_dict.items():
                if column not in exclude_columns:
                    if column in table_columns:
                        column_editor = Ui_tacticColumnEditorWidget(
                            sobject, column, stype, multiple_mode=True)

                        column_title = None
                        for j in stype.get_definition('definition'):
                            if j.get('name') == column:
                                column_title = j.get('title')

                        if not column_title:
                            column_title = gf.prettify_text(column)

                        self.columns_widgets.append(column_editor)
                        self.columns_tab_widget.addTab(
                            column_editor,
                            u'{0} | {1}'.format(column_title, len(self.items)))

            self.columns_tab_widget.setCurrentIndex(self.current_active_tab)

    def customize_with_item(self):

        self.multiple_mode = False

        # TODO save tabs names with their stypes
        self.current_active_tab = self.columns_tab_widget.currentIndex()

        self.columns_tab_widget.clear()
        self.columns_widgets = []

        table_columns = []
        stype = self.item.stype

        idx = self.definition_combo_box.currentIndex()
        current_definition = self.definition_combo_box.itemData(
            idx, QtCore.Qt.UserRole)
        if not current_definition:
            current_definition = 'edit'

        for i in stype.get_definition(current_definition):
            table_columns.append(i.get('name'))

        exclude_columns = [
            '__search_type__', '__search_key__', '__tasks_count__',
            '__notes_count__', '__snapshots__', 'preview'
        ]

        if self.item.type == 'snapshot':
            sobject = self.item.get_snapshot()
        else:
            sobject = self.item.get_sobject()

        if sobject:
            self.set_dock_title(u'Editing Columns of: {0}'.format(
                sobject.get_title()))

            for column in table_columns:
                if column not in exclude_columns:
                    if column in table_columns:
                        column_editor = Ui_tacticColumnEditorWidget(
                            sobject, column, stype)

                        column_title = None
                        for j in stype.get_definition('definition'):
                            if j.get('name') == column:
                                column_title = j.get('title')

                        if not column_title:
                            column_title = gf.prettify_text(column)

                        self.columns_widgets.append(column_editor)
                        self.columns_tab_widget.addTab(column_editor,
                                                       column_title)

            self.columns_tab_widget.setCurrentIndex(self.current_active_tab)

    def customize_without_item(self):
        self.multiple_mode = False
        self.item = None
        self.items = []
        self.columns_widgets = []

        self.columns_tab_widget.clear()

        self.set_dock_title(u'Columns Editor')

    def create_tabbed_widget(self):
        self.columns_tab_widget = QtGui.QTabWidget(self)

        self.columns_tab_widget.setMovable(True)
        self.columns_tab_widget.setTabsClosable(False)
        self.columns_tab_widget.setObjectName("notes_tab_widget")
        self.columns_tab_widget.setStyleSheet(
            '#notes_tab_widget > QTabBar::tab {background: transparent;border: 2px solid transparent;'
            'border-top-left-radius: 3px;border-top-right-radius: 3px;border-bottom-left-radius: 0px;border-bottom-right-radius: 0px;padding: 4px;}'
            '#notes_tab_widget > QTabBar::tab:selected, #notes_tab_widget > QTabBar::tab:hover {'
            'background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 rgba(255, 255, 255, 48), stop: 1 rgba(255, 255, 255, 32));}'
            '#notes_tab_widget > QTabBar::tab:selected {border-color: transparent;}'
            '#notes_tab_widget > QTabBar::tab:!selected {margin-top: 0px;}')

        self.main_layout.addWidget(self.columns_tab_widget, 1, 0, 1, 3)
Esempio n. 10
0
class Ui_ScriptEditForm(QtGui.QDialog):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent=parent)

        self.shown = False
        self.sripts_languages = [
            ('Local-Python', 'local_python'),
            ('Server-Python', 'python'),
            ('Javascript', 'javascript'),
            ('Server-JS', 'server_js'),
            ('Expression', 'expression'),
            ('Xml', 'xml'),
        ]
        self.current_script_sobject = None

        env_inst.ui_script_editor = self

        self.ui_settings_dict = {}

        self.create_ui()

        self.controls_actions()

    def create_ui(self):

        self.setWindowTitle('Script editor')
        self.setObjectName("scriptEditForm")
        self.resize(720, 550)
        self.setSizeGripEnabled(True)
        self.setWindowFlags(QtCore.Qt.Window)

        font = Qt4Gui.QFont()
        font.setPointSize(10)
        font.setFamily('Courier')

        self.main_grid_layout = QtGui.QGridLayout(self)
        self.setLayout(self.main_grid_layout)

        self.main_grid_layout.setObjectName("main_grid_layout")

        self.main_splitter = QtGui.QSplitter(self)
        self.main_splitter.setOrientation(QtCore.Qt.Horizontal)
        self.main_splitter.setObjectName("main_splitter")

        self.verticalLayoutWidget = QtGui.QWidget(self.main_splitter)
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")

        self.script_editor_vertical_layout = QtGui.QVBoxLayout(
            self.verticalLayoutWidget)
        self.script_editor_vertical_layout.setContentsMargins(0, 0, 0, 0)
        self.script_editor_vertical_layout.setObjectName(
            "script_editor_vertical_layout")

        self.script_path_horizontal_layout = QtGui.QHBoxLayout()
        self.script_path_horizontal_layout.setObjectName(
            "script_path_horizontal_layout")

        self.path_label = QtGui.QLabel(self.verticalLayoutWidget)
        self.path_label.setObjectName("path_label")
        self.path_label.setText('Script path: ')

        self.first_path_part_line_edit = QtGui.QLineEdit(
            self.verticalLayoutWidget)
        self.first_path_part_line_edit.setObjectName(
            "first_path_part_line_edit")

        self.slash_label = QtGui.QLabel(self.verticalLayoutWidget)
        self.slash_label.setObjectName("slash_label")
        self.slash_label.setText(' / ')

        self.second_path_part_line_edit = QtGui.QLineEdit(
            self.verticalLayoutWidget)
        self.second_path_part_line_edit.setObjectName(
            "second_path_part_line_edit")

        self.script_language_combo_box = QtGui.QComboBox(
            self.verticalLayoutWidget)
        for script in self.sripts_languages:
            self.script_language_combo_box.addItem(script[0])

        self.create_left_collapsable_toolbar()
        self.create_right_collapsable_toolbar()

        self.script_path_horizontal_layout.addWidget(
            self.left_collapsable_toolbar)
        self.script_path_horizontal_layout.setStretch(0, 0)
        self.script_path_horizontal_layout.addWidget(self.path_label)
        self.script_path_horizontal_layout.setStretch(1, 0)
        self.script_path_horizontal_layout.addWidget(
            self.first_path_part_line_edit)
        self.script_path_horizontal_layout.setStretch(2, 1)
        self.script_path_horizontal_layout.addWidget(self.slash_label)
        self.script_path_horizontal_layout.setStretch(3, 0)
        self.script_path_horizontal_layout.addWidget(
            self.second_path_part_line_edit)
        self.script_path_horizontal_layout.setStretch(4, 1)
        self.script_path_horizontal_layout.addWidget(
            self.script_language_combo_box)
        self.script_path_horizontal_layout.setStretch(5, 0)
        self.script_path_horizontal_layout.addWidget(
            self.right_collapsable_toolbar)
        self.script_path_horizontal_layout.setStretch(6, 0)

        self.script_editor_vertical_layout.addLayout(
            self.script_path_horizontal_layout)

        self.splitter = QtGui.QSplitter(self.verticalLayoutWidget)
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName("splitter")

        self.output = output_window.OutputWindow(self)
        self.output.setFont(font)
        self.splitter.addWidget(self.output)

        self.console = editor_window.EditorWindow(self)
        self.console.setFont(font)
        self.splitter.addWidget(self.console)

        self.script_editor_vertical_layout.addWidget(self.splitter)

        self.down_buttons_horizontal_layout = QtGui.QHBoxLayout()
        self.down_buttons_horizontal_layout.setObjectName(
            "down_buttons_horizontal_layout")

        self.run_script_button = QtGui.QPushButton(self.verticalLayoutWidget)
        self.run_script_button.setObjectName("run_script_button")
        self.run_script_button.setText('Run Script')
        self.run_script_button.setFlat(True)
        self.run_script_button.setIcon(gf.get_icon('play', icons_set='mdi'))

        self.execute_label = QtGui.QLabel(self.verticalLayoutWidget)
        self.execute_label.setObjectName("execute_label")
        self.execute_label.setText('Execute: ')

        self.run_type_combo_box = QtGui.QComboBox(self.verticalLayoutWidget)
        self.run_type_combo_box.setObjectName("run_type_combo_box")
        self.run_type_combo_box.addItem('Locally')
        self.run_type_combo_box.addItem('Server-Side')

        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Minimum)

        self.down_buttons_horizontal_layout.addWidget(self.run_script_button)
        self.down_buttons_horizontal_layout.addItem(spacerItem)
        self.down_buttons_horizontal_layout.addWidget(self.execute_label)
        self.down_buttons_horizontal_layout.addWidget(self.run_type_combo_box)

        self.script_editor_vertical_layout.addLayout(
            self.down_buttons_horizontal_layout)

        self.scripts_tree_widget = QtGui.QTreeWidget(self.main_splitter)
        self.scripts_tree_widget.setAlternatingRowColors(True)
        self.scripts_tree_widget.setAllColumnsShowFocus(True)
        self.scripts_tree_widget.setVerticalScrollMode(
            QtGui.QAbstractItemView.ScrollPerPixel)
        self.scripts_tree_widget.setStyleSheet(gf.get_qtreeview_style())
        self.scripts_tree_widget.setSelectionMode(
            QtGui.QAbstractItemView.SingleSelection)
        self.scripts_tree_widget.setEditTriggers(
            QtGui.QAbstractItemView.NoEditTriggers)
        self.scripts_tree_widget.setRootIsDecorated(True)
        self.scripts_tree_widget.setHeaderHidden(True)
        self.scripts_tree_widget.setObjectName('scripts_tree_widget')

        self.scripts_tree_widget.setColumnCount(2)

        self.main_grid_layout.addWidget(self.main_splitter)

        self.stream = stream.Stream.get_stream()
        if self.stream is None:
            self.stream = stream.Stream()

        self.console_obj = console.Console()

        if env_inst.get_current_project():
            self.fill_sctipts_tree_widget()

        self.create_scripts_tree_context_menu()

    def controls_actions(self):
        self.run_script_button.clicked.connect(self.run_script)

        self.stream.outputWritten.connect(self.output.write_output)
        self.stream.errorWritten.connect(self.output.write_error)
        self.stream.inputWritten.connect(self.output.write_input)

        self.scripts_tree_widget.itemSelectionChanged.connect(
            self.scripts_tree_widget_items_selection_changed)

        self.scripts_tree_widget.itemExpanded.connect(
            lambda: self.scripts_tree_widget.resizeColumnToContents(0))

        self.add_new_script_button.clicked.connect(self.create_new_script)
        self.save_current_script_button.clicked.connect(
            self.save_current_script)
        self.refresh_serverside_scripts_button.clicked.connect(
            self.refresh_scripts_tree)
        self.cleanup_output_button.clicked.connect(self.cleanup_output)

        self.script_language_combo_box.currentIndexChanged.connect(
            self.handle_scripts_language_combo_box)

    def create_right_collapsable_toolbar(self):
        self.right_collapsable_toolbar = Ui_horizontalCollapsableWidget()
        self.right_collapsable_toolbar.setCollapsed(False)

        self.right_buttons_layout = QtGui.QHBoxLayout()
        self.right_buttons_layout.setSpacing(0)
        self.right_buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.right_collapsable_toolbar.setLayout(self.right_buttons_layout)

        self.refresh_serverside_scripts_button = QtGui.QToolButton()
        self.refresh_serverside_scripts_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.refresh_serverside_scripts_button.setAutoRaise(True)
        self.refresh_serverside_scripts_button.setMinimumSize(
            QtCore.QSize(24, 24))
        self.refresh_serverside_scripts_button.setMaximumSize(
            QtCore.QSize(24, 24))
        self.refresh_serverside_scripts_button.setIcon(
            gf.get_icon('refresh', icons_set='mdi'))
        self.refresh_serverside_scripts_button.setToolTip(
            'Refresh all Scripts Tree from Server')

        self.right_buttons_layout.addWidget(
            self.refresh_serverside_scripts_button)

    def create_left_collapsable_toolbar(self):
        self.left_collapsable_toolbar = Ui_horizontalCollapsableWidget()
        self.left_collapsable_toolbar.setCollapsed(False)

        self.left_buttons_layout = QtGui.QHBoxLayout()
        self.left_buttons_layout.setSpacing(0)
        self.left_buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.left_collapsable_toolbar.setLayout(self.left_buttons_layout)

        self.add_new_script_button = QtGui.QToolButton()
        self.add_new_script_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.add_new_script_button.setAutoRaise(True)
        self.add_new_script_button.setMinimumSize(QtCore.QSize(24, 24))
        self.add_new_script_button.setMaximumSize(QtCore.QSize(24, 24))
        self.add_new_script_button.setIcon(
            gf.get_icon('plus-box', icons_set='mdi'))
        self.add_new_script_button.setToolTip('Create New Script')

        self.cleanup_output_button = QtGui.QToolButton()
        self.cleanup_output_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.cleanup_output_button.setAutoRaise(True)
        self.cleanup_output_button.setMinimumSize(QtCore.QSize(24, 24))
        self.cleanup_output_button.setMaximumSize(QtCore.QSize(24, 24))
        self.cleanup_output_button.setIcon(
            gf.get_icon('eraser', icons_set='mdi'))
        self.cleanup_output_button.setToolTip('Clean-up Output Window')

        self.save_current_script_button = QtGui.QToolButton()
        self.save_current_script_button.setToolButtonStyle(
            QtCore.Qt.ToolButtonIconOnly)
        self.save_current_script_button.setAutoRaise(True)
        self.save_current_script_button.setMinimumSize(QtCore.QSize(24, 24))
        self.save_current_script_button.setMaximumSize(QtCore.QSize(24, 24))
        self.save_current_script_button.setIcon(
            gf.get_icon('content-save', icons_set='mdi'))
        self.save_current_script_button.setToolTip(
            'Save current Script to Sever')

        self.left_buttons_layout.addWidget(self.add_new_script_button)
        self.left_buttons_layout.addWidget(self.save_current_script_button)
        self.left_buttons_layout.addWidget(self.cleanup_output_button)

    def scripts_tree_widget_items_selection_changed(self):

        if self.scripts_tree_widget.selectedItems():
            current_scripts_tree_widget_item = self.scripts_tree_widget.selectedItems(
            )[0]
            script_sobject = current_scripts_tree_widget_item.data(
                0, QtCore.Qt.UserRole)

            if not isinstance(script_sobject, list):
                self.fill_by_sobject(script_sobject)

    def fill_by_sobject(self, sobject):

        self.current_script_sobject = sobject

        self.console.setPlainText(sobject.get_value('script'))
        self.first_path_part_line_edit.setText(sobject.get_value('folder'))
        self.second_path_part_line_edit.setText(sobject.get_value('title'))

        lang = sobject.get_value('language')

        if lang == 'local_python':
            self.run_type_combo_box.setCurrentIndex(0)
        else:
            self.run_type_combo_box.setCurrentIndex(1)

        for i, lng in enumerate(self.sripts_languages):
            if lng[1] == lang:
                self.script_language_combo_box.setCurrentIndex(i)

    def handle_scripts_language_combo_box(self, i):
        if i is not None:
            self.run_type_combo_box.setEnabled(True)
            self.run_script_button.setEnabled(True)
            selected_language = self.sripts_languages[int(i)]
            if selected_language[1] == 'local_python':
                self.run_type_combo_box.setCurrentIndex(0)
            elif selected_language[1] in ['server_js', 'python', 'expression']:
                self.run_type_combo_box.setCurrentIndex(1)
            else:
                self.run_type_combo_box.setEnabled(False)
                self.run_script_button.setEnabled(False)

    #@env_inst.async_engine
    def fill_sctipts_tree_widget(self, async_run=True):

        # getting all the scripts from db
        # if async_run:
        #     scripts_sobjects = yield env_inst.async_task(tc.get_custom_scripts)
        # else:
        scripts_sobjects = tc.get_custom_scripts()

        if scripts_sobjects:
            scripts_sobjects_by_folder = tc.group_sobject_by(
                scripts_sobjects, 'folder')

            # adding scripts to tree widget
            for folder_path, sobjects_list in scripts_sobjects_by_folder.items(
            ):
                paths_list = folder_path.split('/')
                exist_item = gf.check_tree_items_exists(
                    self.scripts_tree_widget, paths_list[0])

                if len(paths_list) > 1:
                    paths_list.reverse()
                    top_item_title = paths_list.pop()

                    if exist_item:
                        gf.recursive_add_items(exist_item, paths_list,
                                               sobjects_list)
                    else:
                        root_item = QtGui.QTreeWidgetItem(
                            self.scripts_tree_widget)
                        root_item.setText(0, top_item_title)
                        root_item.setData(0, 12, top_item_title)
                        root_item.setData(0, QtCore.Qt.UserRole, sobjects_list)
                        root_item.setIcon(
                            0, gf.get_icon('folder', icons_set='mdi'))
                        gf.recursive_add_items(root_item, paths_list,
                                               sobjects_list)
                        self.scripts_tree_widget.addTopLevelItem(root_item)
                else:
                    if exist_item:
                        for sobject in sobjects_list:
                            gf.add_child_items(exist_item, sobject)
                    else:
                        root_item = QtGui.QTreeWidgetItem(
                            self.scripts_tree_widget)
                        root_item.setText(0, folder_path)
                        root_item.setData(0, 12, folder_path)
                        root_item.setData(0, QtCore.Qt.UserRole, sobjects_list)
                        root_item.setIcon(
                            0, gf.get_icon('folder', icons_set='mdi'))
                        self.scripts_tree_widget.addTopLevelItem(root_item)
                        for sobject in sobjects_list:
                            gf.add_child_items(root_item, sobject)

    def get_current_script_language(self):
        current_idx = self.script_language_combo_box.currentIndex()
        return self.sripts_languages[current_idx]

    def get_current_script(self):
        return self.console.toPlainText()

    def get_current_script_sobject(self):
        return self.current_script_sobject

    def execute_source_code(self, source_code):
        self.console_obj.enter(source_code)

    def run_locally(self, whole=False):
        if self.run_script_button.isEnabled():
            if whole:
                text = self.console.toPlainText()
            else:
                text = self.console.selectedText()

            text = text.replace(u"\u2029", "\n")
            text = text.replace(u"\u2028", "\n")
            if not text or text == "":
                text = self.console.toPlainText()

            self.stream.input(text)

            self.output.moveCursor(Qt4Gui.QTextCursor.End)

            self.output.scroll_to_bottom()

            self.execute_source_code(text)

    def run_serverside(self, whole=True):
        if self.run_script_button.isEnabled():
            if whole:
                text = self.console.toPlainText()
            else:
                text = self.console.selectedText()
                self.stream.input(text)

            text = text.replace(u"\u2029", "\n")
            text = text.replace(u"\u2028", "\n")
            if not text or text == "":
                text = self.console.toPlainText()

            self.output.moveCursor(Qt4Gui.QTextCursor.End)

            self.output.scroll_to_bottom()

            code_dict = {'code': text}
            start = time.time()
            result = tc.execute_procedure_serverside(lambda: None, code_dict)
            print('\nServe-Side execution time: {}\n'.format(time.time() -
                                                             start))

            gf.pp(result)

    def run_script(self):
        if self.run_type_combo_box.currentIndex() == 0:
            self.run_locally()
        elif self.run_type_combo_box.currentIndex() == 1:
            self.run_serverside()

    def cleanup_output(self):

        self.output.clear()

    def refresh_scripts_tree(self, async_run=True, revert=True):
        if revert:
            state = self.get_scripts_tree_state()

        self.scripts_tree_widget.clear()
        self.fill_sctipts_tree_widget(async_run)

        if revert:
            self.revert_scripts_tree_state(state)

    def create_scripts_tree_context_menu(self):
        self.scripts_tree_widget.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.scripts_tree_widget.customContextMenuRequested.connect(
            self.open_menu)

    def open_menu(self):
        item = self.scripts_tree_widget.currentItem()
        if item:
            if item.data(0, QtCore.Qt.UserRole):
                menu = self.scripts_context_menu()
                if menu:
                    menu.exec_(Qt4Gui.QCursor.pos())

    def create_execution_script(self):
        item = self.scripts_tree_widget.currentItem()

        sobject = item.data(0, QtCore.Qt.UserRole)

        if sobject:
            project = sobject.get_project()
            script_folder = self.first_path_part_line_edit.text()
            script_title = self.second_path_part_line_edit.text()

            script_path = script_folder + '/' + script_title
            procedure = u"import thlib.environment as thenv\nthenv.tc().execute_custom_script('{0}', project='{1}')"

            clipboard = QtGui.QApplication.instance().clipboard()
            clipboard.setText(procedure.format(script_path,
                                               project.get_code()))

    def scripts_context_menu(self):

        copy_runner_script = QtGui.QAction('Copy Script Runner',
                                           self.scripts_tree_widget)
        copy_runner_script.setIcon(gf.get_icon('copy'))
        copy_runner_script.triggered.connect(self.create_execution_script)

        delete_sobject = QtGui.QAction('Delete', self.scripts_tree_widget)
        delete_sobject.setIcon(gf.get_icon('remove'))
        delete_sobject.triggered.connect(self.delete_script_sobject)

        menu = QtGui.QMenu()

        menu.addAction(copy_runner_script)
        menu.addAction(delete_sobject)

        return menu

    def delete_script_sobject(self):

        item = self.scripts_tree_widget.currentItem()

        sobject = item.data(0, QtCore.Qt.UserRole)

        if sobject:
            sobject.delete_sobject()
            self.refresh_scripts_tree()

    def create_new_script(self):

        self.console.clear()

        self.current_script_sobject = None

        self.first_path_part_line_edit.setText('')
        self.second_path_part_line_edit.setText('')
        self.script_language_combo_box.setCurrentIndex(0)
        self.run_type_combo_box.setCurrentIndex(0)

        self.refresh_scripts_tree(revert=False)

    def save_current_script(self):

        script_folder = self.first_path_part_line_edit.text()
        script_title = self.second_path_part_line_edit.text()
        current_language = self.get_current_script_language()[1]

        if script_folder and script_title:
            script_sobject = self.get_current_script_sobject()

            if script_sobject:
                script_sobject.set_value('script', self.get_current_script())
                script_sobject.set_value('language', current_language)
                script_sobject.set_value('folder', script_folder)
                script_sobject.set_value('title', script_title)
                script_sobject.commit(False)
            else:
                search_type = tc.server_start().build_search_type(
                    'config/custom_script',
                    project_code=env_inst.get_current_project())
                filters = [('script', self.get_current_script()),
                           ('folder', script_folder), ('title', script_title),
                           ('language', current_language)]
                tc.server_start().insert(search_type, dict(filters))

            self.refresh_scripts_tree()

    def get_scripts_tree_state(self):
        return gf.to_json(gf.tree_state(self.scripts_tree_widget, {}),
                          use_ast=True)

    def revert_scripts_tree_state(self, state_raw):
        state = gf.from_json(state_raw, use_ast=True)
        gf.tree_state_revert(self.scripts_tree_widget,
                             state,
                             use_item_widgets=False)

    def set_settings_from_dict(self, settings_dict=None):

        ref_settings_dict = {
            'pos': self.pos().toTuple(),
            'size': self.size().toTuple(),
            'windowState': False,
            'main_splitter': None,
            'splitter': None,
            'scripts_tree_widget': None,
        }

        settings = gf.check_config(ref_settings_dict, settings_dict)

        self.move(settings['pos'][0], settings['pos'][1])
        self.resize(settings['size'][0], settings['size'][1])

        if settings['windowState']:
            self.setWindowState(QtCore.Qt.WindowMaximized)

        if settings['main_splitter']:
            self.main_splitter.restoreState(
                QtCore.QByteArray.fromHex(
                    six.ensure_binary(settings['main_splitter'])))

        if settings['splitter']:
            self.splitter.restoreState(
                QtCore.QByteArray.fromHex(
                    six.ensure_binary(settings['splitter'])))

        if settings['scripts_tree_widget']:
            self.revert_scripts_tree_state(settings['scripts_tree_widget'])

    def get_settings_dict(self):
        settings_dict = {
            'windowState': False,
            'main_splitter': gf.do_str(self.main_splitter.saveState().toHex()),
            'splitter': gf.do_str(self.splitter.saveState().toHex()),
            'scripts_tree_widget': self.get_scripts_tree_state(),
        }

        if self.windowState() == QtCore.Qt.WindowMaximized:
            state = True
            if self.ui_settings_dict:
                settings_dict['pos'] = self.ui_settings_dict['pos']
                settings_dict['size'] = self.ui_settings_dict['size']
            else:
                settings_dict['pos'] = self.pos().toTuple()
                settings_dict['size'] = self.size().toTuple()
        else:
            state = False
            settings_dict['pos'] = self.pos().toTuple()
            settings_dict['size'] = self.size().toTuple()

        settings_dict['windowState'] = state

        return settings_dict

    def readSettings(self):
        self.ui_settings_dict = env_read_config(filename='ui_script_editor',
                                                unique_id='ui_main',
                                                long_abs_path=True)
        self.set_settings_from_dict(self.ui_settings_dict)

    def writeSettings(self):
        env_write_config(self.get_settings_dict(),
                         filename='ui_script_editor',
                         unique_id='ui_main',
                         long_abs_path=True)

    def showEvent(self, event):

        if not self.shown:
            self.refresh_scripts_tree()
            self.readSettings()
            self.shown = True

        event.accept()

    def closeEvent(self, event):
        self.writeSettings()

        event.accept()