def closeEvent(self, event): MTTSettings.set_value( 'FilterFileDialog/windowGeometry', self.geometry()) self.do_save_bookmark() self.deleteLater() event.accept()
def __add_texture_item(self, default_texture_state): # clear the scene if self.scene.items(): self.scene.removeItem(self.scene.items()[0]) self.scene.setSceneRect(0, 0, self.current_texture.width(), self.current_texture.height()) self.current_item = MTTItem(self.current_texture) self.current_item.texture = self.popup_info.current_image = self.current_texture self.current_item.compare_texture = self.popup_info.compared_image = self.compare_texture if self.compare_mode: self.current_item.comp_split_pos = self.compare_split_pos self.scene.addItem(self.current_item) # show image self.centerOn(self.current_texture.width() * 0.5, self.current_texture.height() * 0.5) self.centerOn(self.current_texture.width(), self.current_texture.height()) self.is_default_texture = default_texture_state if not default_texture_state: if MTTSettings.value('Viewer/autoFit'): self.fit_texture() elif MTTSettings.value('Viewer/autoReset'): self.reset_texture_transform() self.setBackgroundBrush(QBrush(self.alpha_background)) self.change_draw_style(self.current_style)
def keyPressEvent(self, event): if event.key() == Qt.Key_V and event.modifiers() == Qt.ControlModifier | Qt.AltModifier and not self.is_mtt_sender: MTTSettings.set_value('viewerState', False) # get main tool window and disconnect signal main_window = self.parentWidget().parentWidget().parentWidget() main_window.table_view_selection_model.selectionChanged.disconnect(main_window.on_auto_show_texture) # get current QDockWidget parent to hide tool self.parentWidget().parentWidget().setVisible(False) # set focus to tableView otherwise filter field will be selected main_window.table_view.setFocus() if self.graphics_view.is_default_texture or event.isAutoRepeat(): return False if self.is_mtt_sender else None if event.key() == Qt.Key_Alt: self.graphics_view.navigation_mode = True self.graphics_view.setDragMode(QGraphicsView.ScrollHandDrag) elif event.key() == Qt.Key_A: self.graphics_view.reset_texture_transform() return True if self.is_mtt_sender else None elif event.key() == Qt.Key_F: self.graphics_view.fit_texture() return True if self.is_mtt_sender else None elif event.key() == Qt.Key_T: state = self.toggle_tile_btn.isChecked() self.toggle_tile_btn.setChecked(not state) self.graphics_view.toggle_tile() return True if self.is_mtt_sender else None elif event.key() == Qt.Key_C: state = self.toggle_compare_btn.isChecked() self.toggle_compare_btn.setChecked(not state) self.toggle_compare() return True if self.is_mtt_sender else None elif event.key() == Qt.Key_I: state = self.toggle_picker_btn.isChecked() if not state: self.toggle_picker_btn.setChecked(True) self.graphics_view.toggle_color_info() self.graphics_view.show_popup() return True if self.is_mtt_sender else None elif event.key() == Qt.Key_1: self.show_channel('RGB') return True if self.is_mtt_sender else None elif event.key() == Qt.Key_2: self.show_channel('RGBA') return True if self.is_mtt_sender else None elif event.key() == Qt.Key_3: self.show_channel('R') return True if self.is_mtt_sender else None elif event.key() == Qt.Key_4: self.show_channel('G') return True if self.is_mtt_sender else None elif event.key() == Qt.Key_5: self.show_channel('B') return True if self.is_mtt_sender else None elif event.key() == Qt.Key_6: self.show_channel('A') return True if self.is_mtt_sender else None return False if self.is_mtt_sender else None
def closeEvent(self, event): MTTSettings.set_value('FilterFileDialog/windowGeometry', self.geometry()) self.do_save_bookmark() self.deleteLater() event.accept()
def select_file(self): """ Maya Open Dialog to select file texture """ self.open_dialog_visible = True if MTTSettings.value('browserFirstStart'): image_dir = cmds.optionVar(query='MTT_browserStartFolder') else: image_dir = cmds.workspace(query=True, rootDirectory=True) + cmds.workspace( fileRuleEntry='sourceImages') MTTSettings.set_value('browserFirstStart', True) file_path = cmds.fileDialog2(fileMode=1, startingDirectory=image_dir, caption='Select a texture', okCaption='Select') if file_path: new_path = file_path[0] cmds.optionVar( sv=['MTT_browserStartFolder', os.path.dirname(new_path)]) if MTTSettings.value('forceRelativePath'): new_path = convert_to_relative_path(new_path) # relative_path = workspace(projectPath=new_path) # if relative_path != new_path: # new_path = '/%s' % relative_path self.line_edit.setText(new_path) self.open_dialog_visible = False self.close() self.editingFinished.emit() cmds.showWindow(WINDOW_NAME)
def _set_filter_value(self, key, value): self.model.layoutAboutToBeChanged.emit() MTTSettings.set_value(key, value) cmds.optionVar(stringValue=('filtered_instances', '')) self.model.layoutChanged.emit() self.update_node_file_count()
def filterAcceptsRow(self, row, parent): nodes_str = MTTSettings.value('pinnedNode') if nodes_str: nodes = nodes_str.split(';') source_id = self.sourceModel().index(row, NODE_NAME, parent) value = self.sourceModel().data(source_id, Qt.DisplayRole) if value not in nodes: return False result = super(MTTProxy, self).filterAcceptsRow(row, parent) if not result: return False if self.selected_texture_nodes is not None: source_id = self.sourceModel().index(row, NODE_NAME, parent) value = self.sourceModel().data(source_id, Qt.DisplayRole) if value not in self.selected_texture_nodes: return False if MTTSettings.value('onlyWritableState'): source_id = self.sourceModel().index(row, FILE_STATE, parent) value = self.sourceModel().data(source_id, Qt.DisplayRole) if value != 1: return False if MTTSettings.value('showReferenceState'): source_id = self.sourceModel().index(row, NODE_REFERENCE, parent) value = self.sourceModel().data(source_id, Qt.DisplayRole) if value == 1: return False if MTTSettings.value('showWrongNameState'): source_node_id = self.sourceModel().index(row, NODE_NAME, parent) source_file_id = self.sourceModel().index(row, NODE_FILE, parent) node_name = self.sourceModel().data(source_node_id, Qt.DisplayRole) file_path = self.sourceModel().data(source_file_id, Qt.DisplayRole) file_name = os.path.splitext(os.path.basename(file_path))[0] node_split = re.split('[0-9]*$', node_name.rsplit(':')[-1])[0] file_split = re.split('[0-9]*$', file_name)[0] if node_split == file_split: return False if MTTSettings.value('filterInstances'): source_file_id = self.sourceModel().index(row, NODE_FILE, parent) file_path = self.sourceModel().data(source_file_id, Qt.DisplayRole) norm_path = os.path.normpath(file_path.lower()) instances = cmds.optionVar(query='filtered_instances').split(';') if norm_path not in instances: instances.append(norm_path) cmds.optionVar(stringValue=( 'filtered_instances', ';'.join(instances))) else: return False return True
def on_filter_manage_quick_filter(self): """ Open Quick Filter words manager and save its content """ manager = MTTQuickFilterManager(self) if manager.exec_(): lists = manager.get_lists() # save list in settings MTTSettings.set_value('filterQuickWordsWildcard', ';;'.join(lists[0])) MTTSettings.set_value('filterQuickWordsRegExp', ';;'.join(lists[1])) # set current list self.view.quick_filter_words = lists[MTTSettings.value('filterRE')] manager.deleteLater()
def __create_settings_menu(self): """ Create settings context menu """ settings_menu = QMenu(self) settings_menu.setTearOffEnabled(False) premultiply_menu = QAction('Premultiply Alpha', self) premultiply_menu.setCheckable(True) premultiply_menu.setChecked(MTTSettings.value('Viewer/premultiply')) premultiply_menu.triggered.connect(self.toggle_premultiply) settings_menu.addAction(premultiply_menu) recover_action = QAction('Recovery Mode', self) recover_action.setToolTip( 'Reconstruct image iterating over all pixels when loading fail (Very SLOW)' ) recover_action.setStatusTip( 'Reconstruct image iterating over all pixels when loading fail (Very SLOW)' ) recover_action.setCheckable(True) recover_action.setChecked(MTTSettings.value('Viewer/recoverMode')) recover_action.triggered.connect(self.toggle_recover_mode) settings_menu.addAction(recover_action) settings_menu.addSeparator() header = QAction('LOADING ACTION', self) header.setEnabled(False) settings_menu.addAction(header) zoom_group = QActionGroup(settings_menu) fit_action = QAction('Fit Image', zoom_group) fit_action.setCheckable(True) fit_action.setChecked(MTTSettings.value('Viewer/autoFit')) fit_action.triggered.connect(self.auto_fit) settings_menu.addAction(fit_action) lock_action = QAction('Lock Zoom', zoom_group) lock_action.setCheckable(True) lock_action.setChecked(MTTSettings.value('Viewer/autoLock')) lock_action.triggered.connect(self.auto_lock_zoom) settings_menu.addAction(lock_action) reset_action = QAction('Reset Zoom', zoom_group) reset_action.setCheckable(True) reset_action.setChecked(MTTSettings.value('Viewer/autoReset')) reset_action.triggered.connect(self.auto_reset_zoom) settings_menu.addAction(reset_action) return settings_menu
def update_status(self, is_loading=False): current_color = QApplication.palette().Window if is_loading: current_color = QColor(Qt.darkGreen).name() msg = 'Loading texture. Please wait...' elif self.graphics_view.is_default_texture: msg = 'No Texture Found.' else: self.graphics_view.viewport().repaint() current_zoom = self.graphics_view.transform().m11() * 100 texture_width = self.graphics_view.current_item.pixmap().width() texture_height = self.graphics_view.current_item.pixmap().height() texture_name = os.path.basename(self.texture_path) msg = '%.d%% | %dx%d | %s' % (current_zoom, texture_width, texture_height, texture_name) if self.texture_compare_path: msg += ' compared to %s' % os.path.basename(self.texture_compare_path) if self.graphics_view.is_loading_fail and not self.graphics_view.is_default_texture: msg = 'Failed to load image ! ' if MTTSettings.value('Viewer/recoverMode'): msg += '::: IMAGE RECONSTRUCTED :::' current_color = QColor(Qt.darkRed).name() self.viewer_statusbar = self.statusBar() self.viewer_statusbar.showMessage(msg) self.viewer_statusbar.setStyleSheet("background-color: %s" % current_color)
def __init__(self, parent=get_maya_window()): super(MTTViewer, self).__init__(parent) if cmds.control(VIEWER_NAME, exists=True): cmds.deleteUI(VIEWER_NAME, window=True) self.parent = parent self.setObjectName(VIEWER_NAME) self.setWindowTitle(VIEWER_TITLE) self.setWindowIcon(QIcon(WINDOW_ICON)) self.texture_path = None self.texture_compare_path = None self.is_mtt_sender = False # UI variables self.viewer_statusbar = None self.graphics_view = None self.channel_btn = dict() self.fit_btn = None self.reset_zoom_btn = None self.toggle_tile_btn = None self.toggle_compare_btn = None self.toggle_picker_btn = None self.settings_btn = None # create UI self.__create_ui() # self.setMouseTracking(True) # restore geometry self.restoreGeometry(MTTSettings.value('Viewer/windowGeometry'))
def on_show_debug_menu(self): self.debug_menu.clear() if self.is_master_cmd or self.power_user: power_user_mode = QAction('Power User Mode', self) power_user_mode.setCheckable(True) power_user_mode.setChecked(MTTSettings.value('powerUser')) power_user_mode.triggered.connect(self.__on_toggle_power_user) self.debug_menu.addAction(power_user_mode) self.is_master_cmd = False self.debug_menu.addSeparator() open_pref_folder_action = QAction('Open Preferences Folder', self) open_pref_folder_action.setStatusTip('Open MTT preference folder') open_pref_folder_action.triggered.connect( self.on_open_preference_folder) self.debug_menu.addAction(open_pref_folder_action) self.debug_menu.addSeparator() database_dump_csv = QAction('Dump Database as CSV', self) database_dump_csv.triggered.connect(self.view.model.database_dump_csv) self.debug_menu.addAction(database_dump_csv) database_dump_sql = QAction('Dump Database as SQL', self) database_dump_sql.triggered.connect(self.view.model.database_dump_sql) self.debug_menu.addAction(database_dump_sql) self.debug_menu.addSeparator() support_info = QMenu(self) support_info.setTitle('Supported Node Type') support_info.aboutToShow.connect(self.on_show_supported_type) self.debug_menu.addMenu(support_info)
def _create_theme_menu(self): theme_menu = QMenu(self) theme_menu.setTitle('Buttons Theme') theme_menu.setTearOffEnabled(True) theme_menu.setWindowTitle(TAG) theme_actions = QActionGroup(self) theme_actions.setExclusive(True) # create ordered theme list custom_order_theme = sorted(THEMES.iterkeys()) custom_order_theme.remove('Maya Theme') custom_order_theme.insert(0, 'Maya Theme') default_item = True for theme in custom_order_theme: current_theme_action = QAction(theme, theme_actions) current_theme_action.setCheckable(True) current_theme_action.setChecked( MTTSettings.value('theme', 'Maya Theme') == theme) current_theme_action.triggered.connect(self.on_change_theme) theme_menu.addAction(current_theme_action) if default_item: theme_menu.addSeparator() default_item = False return theme_menu
def update_status(self, is_loading=False): current_color = QApplication.palette().Window if is_loading: current_color = QColor(Qt.darkGreen).name() msg = 'Loading texture. Please wait...' elif self.graphics_view.is_default_texture: msg = 'No Texture Found.' else: self.graphics_view.viewport().repaint() current_zoom = self.graphics_view.transform().m11() * 100 texture_width = self.graphics_view.current_item.pixmap().width() texture_height = self.graphics_view.current_item.pixmap().height() texture_name = os.path.basename(self.texture_path) msg = '%.d%% | %dx%d | %s' % (current_zoom, texture_width, texture_height, texture_name) if self.texture_compare_path: msg += ' compared to %s' % os.path.basename( self.texture_compare_path) if self.graphics_view.is_loading_fail and not self.graphics_view.is_default_texture: msg = 'Failed to load image ! ' if MTTSettings.value('Viewer/recoverMode'): msg += '::: IMAGE RECONSTRUCTED :::' current_color = QColor(Qt.darkRed).name() self.viewer_statusbar = self.statusBar() self.viewer_statusbar.showMessage(msg) self.viewer_statusbar.setStyleSheet("background-color: %s" % current_color)
def on_show_debug_menu(self): self.debug_menu.clear() if self.is_master_cmd or self.power_user: power_user_mode = QAction('Power User Mode', self) power_user_mode.setCheckable(True) power_user_mode.setChecked(MTTSettings.value('powerUser')) power_user_mode.triggered.connect(self.__on_toggle_power_user) self.debug_menu.addAction(power_user_mode) self.is_master_cmd = False self.debug_menu.addSeparator() open_pref_folder_action = QAction('Open Preferences Folder', self) open_pref_folder_action.setStatusTip('Open MTT preference folder') open_pref_folder_action.triggered.connect(self.on_open_preference_folder) self.debug_menu.addAction(open_pref_folder_action) self.debug_menu.addSeparator() database_dump_csv = QAction('Dump Database as CSV', self) database_dump_csv.triggered.connect(self.view.model.database_dump_csv) self.debug_menu.addAction(database_dump_csv) database_dump_sql = QAction('Dump Database as SQL', self) database_dump_sql.triggered.connect(self.view.model.database_dump_sql) self.debug_menu.addAction(database_dump_sql) self.debug_menu.addSeparator() support_info = QMenu(self) support_info.setTitle('Supported Node Type') support_info.aboutToShow.connect(self.on_show_supported_type) self.debug_menu.addMenu(support_info)
def do_populate_bookmarks(self): bookmarks = ['sourceimages|%s' % SOURCEIMAGES_TAG] bookmarks.extend( MTTSettings.value('FilterFileDialog/bookmarks').split(',')) for bm in bookmarks: self.on_add_bookmark_item(bm)
def __init__(self, define_path='', define_type=None): super(MTTFilterFileDialog, self).__init__(get_maya_window()) self.supported_node_type = sorted([ node_type for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE ]) self.defined_path = (define_path if os.path.isdir(define_path) or define_path == SOURCEIMAGES_TAG else None) self.defined_type = (define_type if define_type in self.supported_node_type else None) self.path_edit = None self.filter_reset_btn = None self.filter_line = None self.parent_folder_btn = None self.files_model = None self.files_list = None self.bookmark_list = None self.bookmark_list_sel_model = None self.types = None # move window to cursor position win_geo = MTTSettings.value('FilterFileDialog/windowGeometry', QRect(0, 0, 400, 300)) self.setGeometry(win_geo) mouse_pos = QCursor.pos() mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5)) self.move(mouse_pos) self.__create_ui() self.filter_line.setFocus() self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG)
def do_save_bookmark(self): if not self.bookmark_list: return row_count = self.bookmark_list.count() ordered_list = list() for i in range(row_count): item = self.bookmark_list.item(i) name = item.text().replace(',', '_').replace('|', '_') path = item.root_path if name != 'sourceimages': ordered_list.append('%s|%s' % (name, path)) MTTSettings.set_value( 'FilterFileDialog/bookmarks', ','.join(ordered_list))
def mtt_log(msg, add_tag=None, msg_type=None, verbose=True): """ Format output message '[TAG][add_tag] Message content' :param msg: (string) message content :param add_tag: (string or list) add extra tag to output :param msg_type: define message type. Accept : None, 'warning', 'error' :param verbose: (bool) enable headsUpMessage output """ # define tags tag_str = '[MTT]' # append custom tags if add_tag: if not isinstance(add_tag, list): add_tag = [add_tag] for tag in add_tag: tag_str += '[%s]' % tag.upper() # output message the right way if msg_type == 'warning': cmds.warning('%s %s' % (tag_str, msg)) elif msg_type == 'error': cmds.error('%s %s' % (tag_str, msg)) else: print '%s %s\n' % (tag_str, msg), if verbose and MTTSettings.value('showHeadsUp'): cmds.headsUpMessage(msg)
def do_save_bookmark(self): if not self.bookmark_list: return row_count = self.bookmark_list.count() ordered_list = list() for i in range(row_count): item = self.bookmark_list.item(i) name = item.text().replace(',', '_').replace('|', '_') path = item.root_path if name != 'sourceimages': ordered_list.append('%s|%s' % (name, path)) MTTSettings.set_value('FilterFileDialog/bookmarks', ','.join(ordered_list))
def __create_settings_menu(self): """ Create settings context menu """ settings_menu = QMenu(self) settings_menu.setTearOffEnabled(False) premultiply_menu = QAction('Premultiply Alpha', self) premultiply_menu.setCheckable(True) premultiply_menu.setChecked(MTTSettings.value('Viewer/premultiply')) premultiply_menu.triggered.connect(self.toggle_premultiply) settings_menu.addAction(premultiply_menu) recover_action = QAction('Recovery Mode', self) recover_action.setToolTip('Reconstruct image iterating over all pixels when loading fail (Very SLOW)') recover_action.setStatusTip('Reconstruct image iterating over all pixels when loading fail (Very SLOW)') recover_action.setCheckable(True) recover_action.setChecked(MTTSettings.value('Viewer/recoverMode')) recover_action.triggered.connect(self.toggle_recover_mode) settings_menu.addAction(recover_action) settings_menu.addSeparator() header = QAction('LOADING ACTION', self) header.setEnabled(False) settings_menu.addAction(header) zoom_group = QActionGroup(settings_menu) fit_action = QAction('Fit Image', zoom_group) fit_action.setCheckable(True) fit_action.setChecked(MTTSettings.value('Viewer/autoFit')) fit_action.triggered.connect(self.auto_fit) settings_menu.addAction(fit_action) lock_action = QAction('Lock Zoom', zoom_group) lock_action.setCheckable(True) lock_action.setChecked(MTTSettings.value('Viewer/autoLock')) lock_action.triggered.connect(self.auto_lock_zoom) settings_menu.addAction(lock_action) reset_action = QAction('Reset Zoom', zoom_group) reset_action.setCheckable(True) reset_action.setChecked(MTTSettings.value('Viewer/autoReset')) reset_action.triggered.connect(self.auto_reset_zoom) settings_menu.addAction(reset_action) return settings_menu
def __init__(self, parent=get_maya_window()): super(MTTQuickFilterManager, self).__init__(parent) # create UI main_layout = QVBoxLayout(self) main_layout.setSpacing(2) main_layout.setContentsMargins(4, 4, 4, 4) list_layout = QHBoxLayout(self) self.quick_filter_wildcard_ui = _QuickFilterUI('Wildcard') list_layout.addLayout(self.quick_filter_wildcard_ui) self.quick_filter_regex_ui = _QuickFilterUI('RegularExpression') list_layout.addLayout(self.quick_filter_regex_ui) main_layout.addLayout(list_layout) main_layout.addSpacing(2) buttons_layout = QHBoxLayout(self) save_button = QPushButton('&Save') save_button.clicked.connect(self.accept) buttons_layout.addWidget(save_button) cancel_button = QPushButton('&Cancel') cancel_button.clicked.connect(self.reject) buttons_layout.addWidget(cancel_button) main_layout.addLayout(buttons_layout) # populate lists items_str = MTTSettings.value('filterQuickWordsWildcard') if items_str: self.quick_filter_wildcard_ui.populate( quick_filter_words=items_str.split(';;')) items_str = MTTSettings.value('filterQuickWordsRegExp') if items_str: self.quick_filter_regex_ui.populate( quick_filter_words=items_str.split(';;')) # adjust UI self.setWindowTitle(WINDOW_TITLE) self.setWindowIcon(QIcon(WINDOW_ICON)) self.setModal(True) self.resize(300, 200)
def setEditorData(self, editor, index): # fill editors with the right data text = index.model().data(index, Qt.DisplayRole) if index.column() in (NODE_NAME, NODE_FILE): if index.column() == NODE_FILE \ and not MTTSettings.value('showRealAttributeValue'): if not text.startswith('\\'): text = cmds.workspace(projectPath=text) editor.setText(text)
def __init__(self, parent=None): super(MTTSettingsMenu, self).__init__(parent) self.view = parent self.is_master_cmd = False # power user state self.power_user = MTTSettings.value('powerUser') self.__create_actions() self.__populate_menu()
def setModelData(self, editor, model, index): # send modification to model if index.column() in (NODE_NAME, NODE_FILE): index_str = index.model().data(index, Qt.DisplayRole) if index_str != editor.text(): if index.column() == NODE_FILE \ and not MTTSettings.value('showRealAttributeValue'): if not index_str.startswith('\\'): index_str = cmds.workspace(projectPath=index_str) if index_str == editor.text(): return model.setData(index, editor.text()) else: QStyledItemDelegate.setModelData(self, editor, model, index)
def create_nodes(define_path='', define_type=None): dialog = MTTFilterFileDialog( define_path=define_path, define_type=define_type) if dialog.exec_(): files = dialog.get_selected_files() node_type = dialog.get_node_type() node_attr = [ attr for (n_type, nice, attr) in MTTSettings.SUPPORTED_TYPE if node_type == n_type][0] current_selection = cmds.ls(selection=True) MTTSettings.set_value('suspendRenameCallbacks', True) nodes = list() for f in files: n_name = os.path.basename(f).rsplit('.')[0] node_name = n_name if not n_name[0].isdigit() else '_%s' % n_name new_node = cmds.shadingNode(node_type, name=node_name, asTexture=1) convert = MTTSettings.value('forceRelativePath') if convert: f = convert_to_relative_path(f) set_attr(new_node, node_attr, f, attr_type='string') if MTTSettings.IMPORT_POLICY: try: exec MTTSettings.IMPORT_POLICY exec_import_policy( current_selection, node_name, os.path.basename(f) ) except RuntimeError: mtt_log('Fail to run import policy.', msg_type='error', verbose=False) nodes.append(new_node) MTTSettings.set_value('suspendRenameCallbacks', False) MTTSettings.remove('suspendRenameCallbacks') if nodes: cmds.select(nodes, replace=True) dialog.deleteLater()
def create_nodes(define_path='', define_type=None): dialog = MTTFilterFileDialog(define_path=define_path, define_type=define_type) if dialog.exec_(): files = dialog.get_selected_files() node_type = dialog.get_node_type() node_attr = [ attr for (n_type, nice, attr) in MTTSettings.SUPPORTED_TYPE if node_type == n_type ][0] current_selection = cmds.ls(selection=True) MTTSettings.set_value('suspendRenameCallbacks', True) nodes = list() for f in files: n_name = os.path.basename(f).rsplit('.')[0] node_name = n_name if not n_name[0].isdigit() else '_%s' % n_name new_node = cmds.shadingNode(node_type, name=node_name, asTexture=1) convert = MTTSettings.value('forceRelativePath') if convert: f = convert_to_relative_path(f) set_attr(new_node, node_attr, f, attr_type='string') if MTTSettings.IMPORT_POLICY: try: exec MTTSettings.IMPORT_POLICY exec_import_policy(current_selection, node_name, os.path.basename(f)) except RuntimeError: mtt_log('Fail to run import policy.', msg_type='error', verbose=False) nodes.append(new_node) MTTSettings.set_value('suspendRenameCallbacks', False) MTTSettings.remove('suspendRenameCallbacks') if nodes: cmds.select(nodes, replace=True) dialog.deleteLater()
def __init__(self, define_path='', define_type=None): super(MTTFilterFileDialog, self).__init__(get_maya_window()) self.supported_node_type = sorted( [node_type for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE]) self.defined_path = ( define_path if os.path.isdir(define_path) or define_path == SOURCEIMAGES_TAG else None) self.defined_type = ( define_type if define_type in self.supported_node_type else None) self.path_edit = None self.filter_reset_btn = None self.filter_line = None self.parent_folder_btn = None self.files_model = None self.files_list = None self.bookmark_list = None self.bookmark_list_sel_model = None self.types = None # move window to cursor position win_geo = MTTSettings.value( 'FilterFileDialog/windowGeometry', QRect(0, 0, 400, 300)) self.setGeometry(win_geo) mouse_pos = QCursor.pos() mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5)) self.move(mouse_pos) self.__create_ui() self.filter_line.setFocus() self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG)
def file_watch_file_change(self, file_path): key_path = self.convert_to_key_path(file_path) c = self.db.cursor() if MTTSettings.value('autoReload'): self.is_reloading_file = True c.execute( 'SELECT Name ' 'FROM NodesTable LEFT JOIN FilesTable USING(FileId) ' 'WHERE KeyPath=?', (key_path, )) nodes = c.fetchall() for node in [x[0] for x in nodes]: attr_name = self.supported_format_dict[cmds.nodeType(node)] attr_value = cmds.getAttr('%s.%s' % (node, attr_name)) set_attr(node, attr_name, attr_value, attr_type='string') self.is_reloading_file = False self.file_watch_add_path(file_path) new_state = self.get_file_state(file_path) c.execute('UPDATE FilesTable SET State=? WHERE KeyPath=?', (new_state, key_path)) self.request_sort()
def on_open_preference_folder(): """ Open preference folder """ folder_path = os.path.dirname(MTTSettings.filename()) cmds.launchImageEditor(viewImageFile=folder_path)
def on_auto_select(): state = MTTSettings.value('autoSelect') MTTSettings.set_value('autoSelect', not state)
def sort(self, column_id, sort_order=None): # get current selection selection = list() node_name = '' proxy = None if self.table_view: selection = [ idName.data() for idName in self.table_view.selectionModel().selectedRows() ] model_id = self.table_view.selectionModel().currentIndex() proxy = model_id.model() node_name = (model_id.data() if model_id.column() == 0 else model_id.sibling(model_id.row(), NODE_NAME).data()) self.table_view.selectionModel().reset() # sort data self.layoutAboutToBeChanged.emit() c = self.db.cursor() order = ['ASC', 'DESC'][sort_order] c.execute('SELECT Name, Type, IsRef FROM NodesTable as N ' 'LEFT JOIN FilesTable as F ON N.FileId=F.FileId ' 'LEFT JOIN RefTable as R ON N.RefName=R.RefName ' 'ORDER BY %s %s' % (DB_COLUMN_LABEL[column_id], order)) self.textures = c.fetchall() cmds.optionVar(stringValue=('filtered_instances', '')) self.layoutChanged.emit() # set stored selection auto_select = MTTSettings.value('autoSelect') if self.table_view and selection and proxy and not auto_select: new_model_id = proxy.match(self.index(0, 0, QModelIndex()), Qt.DisplayRole, node_name, 1, Qt.MatchExactly) if new_model_id: self.table_view.selectionModel().setCurrentIndex( new_model_id[0], QItemSelectionModel.Current | QItemSelectionModel.Rows) for nodeName in selection: model_id = proxy.match(self.index(0, 0, QModelIndex()), Qt.DisplayRole, nodeName, 1, Qt.MatchExactly) if model_id: self.table_view.selectionModel().select( model_id[0], QItemSelectionModel.Select | QItemSelectionModel.Rows) # refresh column header visibility for col_id in range(COLUMN_COUNT): self.table_view.setColumnHidden( col_id, not MTTSettings.value('columnVisibility_%s' % col_id, True))
def __create_actions(self): def add_action(lbl, tip, cmd, checkable=False, checked=False): a = QAction(lbl, self) a.setStatusTip(tip) a.triggered.connect(cmd) if checkable: a.setCheckable(True) a.setChecked(checked) return a self.help_a = add_action('Help', 'Opens the online Help page', self.on_settings_help) self.switch_edit_a = add_action( 'Switch Edit/Source', 'Replace "Edit" button by "Source" button', self.on_switch_source_edit_menu, True, MTTSettings.value('switchEdit')) self.heads_up_a = add_action('HeadsUp Message', 'Show HeadsUp Message in viewport', self.on_toggle_headsup, True, MTTSettings.value('showHeadsUp')) self.focus_filter_a = add_action('Focus Filter Field at Startup', 'Focus filter field at startup', self.on_toggle_focus, True, MTTSettings.value('filterFocus')) self.force_relative_path_a = add_action( 'Force Relative Path', 'Set a relative path when selecting a new file', self.on_force_relative_path, True, MTTSettings.value('forceRelativePath')) self.show_real_attr_value_a = add_action( 'Show Real Attribute Value', 'Show fullpath instead of filtering path as Attribute Editor', self.on_show_real_attribute_value, True, MTTSettings.value('showRealAttributeValue')) self.manage_quick_filter_a = add_action( 'Manage Quick Filters', 'Manage filters that popup with right clic in filter field', self.on_filter_manage_quick_filter) self.clear_completion_cache_a = add_action( 'Clear Completion Cache', 'Erase auto completion cache of filter field', self.on_filter_clear_completion_cache) self.override_panels_a = add_action( 'Add CreateNode Button to Editors', ('Add "Create Node" to HyperShade and ' 'Node Editor for the current session'), self.on_override_panels) self.export_to_csv = add_action( 'Export Texture List as CSV', 'Export current textures into a csv file', self.view.model.export_as_csv) self.about = add_action('About', 'About', self.on_settings_about)
def save_states(self): # buttons states MTTSettings.set_value('onlySelectionState', self.selection_btn.isChecked()) MTTSettings.set_value('onlyWritableState', self.writable_btn.isChecked()) MTTSettings.set_value('showReferenceState', self.reference_btn.isChecked()) MTTSettings.set_value('showWrongNameState', self.wrong_name_btn.isChecked()) MTTSettings.remove('pinnedNode') MTTSettings.set_value('vizWrongNameState', self.wrong_name_visibility_btn.isChecked()) MTTSettings.set_value('showBasenameState', self.basename_visibility_btn.isChecked()) MTTSettings.set_value('filterInstances', self.filter_instances_btn.isChecked()) # groups states MTTSettings.set_value('filterGroup', self.filter_grp.current_state()) MTTSettings.set_value('visibilityGroup', self.visibility_grp.current_state()) MTTSettings.set_value('folderGroup', self.folder_grp.current_state()) MTTSettings.set_value('autoGroup', self.auto_grp.current_state()) MTTSettings.set_value('toolGroup', self.tool_grp.current_state()) MTTSettings.set_value('mayaGroup', self.maya_grp.current_state())
def on_show_only_selection(self): """ Filter nodes from current selection """ state = self.selection_btn.isChecked() MTTSettings.set_value('onlySelectionState', state) self.filterSelectionToggled.emit(state)
def paint(self, painter, option, index): # NODE_REFERENCE --------------------------------------------------- if index.column() == NODE_REFERENCE: # backup painter painter.save() # paint background palette = QApplication.palette() if option.state & QStyle.State_Selected: bg_color = palette.highlight().color() else: bg_color = Qt.transparent painter.fillRect(option.rect, bg_color) # paint value = float(index.model().data(index)) if value == 0.0: painter.setPen( Qt.black if option.state & QStyle.State_Selected else Qt.darkGray ) painter.setBrush(Qt.NoBrush) mid_size = 3.0 else: painter.setPen(Qt.darkCyan) painter.setBrush(Qt.cyan) mid_size = 4.0 h_center = round(option.rect.x() + (option.rect.width() * .5)) v_center = round(option.rect.y() + (option.rect.height() * .5)) losange = QPolygonF() losange.append(QPointF(h_center, v_center - mid_size)) losange.append(QPointF(h_center - mid_size, v_center)) losange.append(QPointF(h_center, v_center + mid_size)) losange.append(QPointF(h_center + mid_size, v_center)) painter.drawPolygon(losange) # restore painter painter.restore() # FILE_STATE ------------------------------------------------------- elif index.column() == FILE_STATE: # backup painter painter.save() # paint background palette = QApplication.palette() bg_color = palette.highlight().color() \ if option.state & QStyle.State_Selected \ else Qt.transparent painter.fillRect(option.rect, bg_color) # paint circle value = index.model().data(index) pen_color = [ Qt.darkRed, Qt.black if option.state & QStyle.State_Selected else Qt.gray, Qt.darkGreen][value + 1] brush_color = [Qt.red, Qt.NoBrush, Qt.green][value + 1] painter.setPen(pen_color) painter.setBrush(brush_color) h_center = round(option.rect.x() + (option.rect.width() * .5)) v_center = round(option.rect.y() + (option.rect.height() * .5)) center = QPointF(h_center, v_center) painter.drawEllipse(center, 3.0, 3.0) # restore painter painter.restore() # NODE_NAME -------------------------------------------------------- elif index.column() == NODE_NAME: text = index.model().data(index, Qt.DisplayRole) palette = QApplication.palette() bg_color = palette.highlight().color() \ if option.state & QStyle.State_Selected \ else Qt.transparent txt_color = palette.highlightedText().color() \ if option.state & QStyle.State_Selected \ else palette.text().color() if MTTSettings.value('vizWrongNameState') \ and not MTTSettings.value('showWrongNameState'): file_name = os.path.splitext(os.path.basename( index.model().data( index.sibling(index.row(), NODE_FILE), Qt.DisplayRole ) ))[0] if not re.split('[0-9]*$', text.rsplit(':')[-1])[0] == \ re.split('[0-9]*$', file_name)[0]: bg_color = QBrush( Qt.red if option.state & QStyle.State_Selected else Qt.darkRed, Qt.Dense4Pattern ) if not MTTSettings.value('showNamespaceState'): splits = text.split(':') text = splits[len(splits) > 1] painter.save() painter.fillRect(option.rect, bg_color) painter.setPen(txt_color) rect = option.rect rect.setX(4) QApplication.style().drawItemText( painter, rect, Qt.AlignLeft | Qt.AlignVCenter, palette, True, text ) painter.restore() # NODE_FILE ------------------------------------------------------------ elif index.column() == NODE_FILE: palette = QApplication.palette() bg_color = palette.highlight().color() \ if option.state & QStyle.State_Selected \ else Qt.transparent txt_color = palette.highlightedText().color() \ if option.state & QStyle.State_Selected \ else palette.text().color() text = index.model().data(index, Qt.DisplayRole) if MTTSettings.value('vizExternalState'): if not text.startswith(self.ws_path): bg_color = QBrush( '#ef7900' if option.state & QStyle.State_Selected else '#b05100', Qt.Dense4Pattern) if MTTSettings.value('vizWrongPathState'): if not re.match(MTTSettings.PATH_PATTERN, text): bg_color = QBrush( Qt.red if option.state & QStyle.State_Selected else Qt.darkRed, Qt.Dense4Pattern) if MTTSettings.value('showBasenameState'): text = os.path.basename(text) elif not MTTSettings.value('showRealAttributeValue'): if not text.startswith('\\'): text = os.path.normpath(cmds.workspace(projectPath=text)) painter.save() painter.fillRect(option.rect, bg_color) painter.setPen(txt_color) QApplication.style().drawItemText( painter, option.rect, Qt.AlignLeft | Qt.AlignVCenter, palette, True, text) painter.restore() else: QStyledItemDelegate.paint(self, painter, option, index)
def paint(self, painter, option, index): # NODE_REFERENCE --------------------------------------------------- if index.column() == NODE_REFERENCE: # backup painter painter.save() # paint background palette = QApplication.palette() if option.state & QStyle.State_Selected: bg_color = palette.highlight().color() else: bg_color = Qt.transparent painter.fillRect(option.rect, bg_color) # paint value = float(index.model().data(index)) if value == 0.0: painter.setPen(Qt.black if option.state & QStyle.State_Selected else Qt.darkGray) painter.setBrush(Qt.NoBrush) mid_size = 3.0 else: painter.setPen(Qt.darkCyan) painter.setBrush(Qt.cyan) mid_size = 4.0 h_center = round(option.rect.x() + (option.rect.width() * .5)) v_center = round(option.rect.y() + (option.rect.height() * .5)) losange = QPolygonF() losange.append(QPointF(h_center, v_center - mid_size)) losange.append(QPointF(h_center - mid_size, v_center)) losange.append(QPointF(h_center, v_center + mid_size)) losange.append(QPointF(h_center + mid_size, v_center)) painter.drawPolygon(losange) # restore painter painter.restore() # FILE_STATE ------------------------------------------------------- elif index.column() == FILE_STATE: # backup painter painter.save() # paint background palette = QApplication.palette() bg_color = palette.highlight().color() \ if option.state & QStyle.State_Selected \ else Qt.transparent painter.fillRect(option.rect, bg_color) # paint circle value = index.model().data(index) pen_color = [ Qt.darkRed, Qt.black if option.state & QStyle.State_Selected else Qt.gray, Qt.darkGreen ][value + 1] brush_color = [Qt.red, Qt.NoBrush, Qt.green][value + 1] painter.setPen(pen_color) painter.setBrush(brush_color) h_center = round(option.rect.x() + (option.rect.width() * .5)) v_center = round(option.rect.y() + (option.rect.height() * .5)) center = QPointF(h_center, v_center) painter.drawEllipse(center, 3.0, 3.0) # restore painter painter.restore() # NODE_NAME -------------------------------------------------------- elif index.column() == NODE_NAME: text = index.model().data(index, Qt.DisplayRole) palette = QApplication.palette() bg_color = palette.highlight().color() \ if option.state & QStyle.State_Selected \ else Qt.transparent txt_color = palette.highlightedText().color() \ if option.state & QStyle.State_Selected \ else palette.text().color() if MTTSettings.value('vizWrongNameState') \ and not MTTSettings.value('showWrongNameState'): file_name = os.path.splitext( os.path.basename(index.model().data( index.sibling(index.row(), NODE_FILE), Qt.DisplayRole)))[0] if not re.split('[0-9]*$', text.rsplit(':')[-1])[0] == \ re.split('[0-9]*$', file_name)[0]: bg_color = QBrush( Qt.red if option.state & QStyle.State_Selected else Qt.darkRed, Qt.Dense4Pattern) if not MTTSettings.value('showNamespaceState'): splits = text.split(':') text = splits[len(splits) > 1] painter.save() painter.fillRect(option.rect, bg_color) painter.setPen(txt_color) rect = option.rect rect.setX(4) QApplication.style().drawItemText(painter, rect, Qt.AlignLeft | Qt.AlignVCenter, palette, True, text) painter.restore() # NODE_FILE ------------------------------------------------------------ elif index.column() == NODE_FILE: palette = QApplication.palette() bg_color = palette.highlight().color() \ if option.state & QStyle.State_Selected \ else Qt.transparent txt_color = palette.highlightedText().color() \ if option.state & QStyle.State_Selected \ else palette.text().color() text = index.model().data(index, Qt.DisplayRole) if MTTSettings.value('vizExternalState'): if not text.startswith(self.ws_path): bg_color = QBrush( '#ef7900' if option.state & QStyle.State_Selected else '#b05100', Qt.Dense4Pattern) if MTTSettings.value('vizWrongPathState'): if not re.match(MTTSettings.PATH_PATTERN, text): bg_color = QBrush( Qt.red if option.state & QStyle.State_Selected else Qt.darkRed, Qt.Dense4Pattern) if MTTSettings.value('showBasenameState'): text = os.path.basename(text) elif not MTTSettings.value('showRealAttributeValue'): if not text.startswith('\\'): text = os.path.normpath(cmds.workspace(projectPath=text)) painter.save() painter.fillRect(option.rect, bg_color) painter.setPen(txt_color) QApplication.style().drawItemText(painter, option.rect, Qt.AlignLeft | Qt.AlignVCenter, palette, True, text) painter.restore() else: QStyledItemDelegate.paint(self, painter, option, index)
def on_show_real_attribute_value(self): self.view.model.layoutAboutToBeChanged.emit() show_real_attribute_state = MTTSettings.value('showRealAttributeValue') MTTSettings.set_value( 'showRealAttributeValue', not show_real_attribute_state) self.view._layout_changed()
def on_toggle_headsup(): state = MTTSettings.value('showHeadsUp') MTTSettings.set_value('showHeadsUp', not state)
def on_force_relative_path(): state = MTTSettings.value('forceRelativePath') MTTSettings.set_value('forceRelativePath', not state)
def on_toggle_focus(): state = MTTSettings.value('filterFocus') MTTSettings.set_value('filterFocus', not state)
def on_auto_reload(): state = MTTSettings.value('autoReload') MTTSettings.set_value('autoReload', not state)
def __on_toggle_power_user(self): state = MTTSettings.value('powerUser') MTTSettings.set_value('powerUser', not state) self.power_user = not state
def on_auto_rename(): state = MTTSettings.value('autoRename') MTTSettings.set_value('autoRename', not state)
def __init_ui(self): self.setContentsMargins(0, 0, 0, 0) self.setAlignment(Qt.AlignLeft) # FILTER GROUP self.selection_btn.setChecked(MTTSettings.value('onlySelectionState')) self.writable_btn.setChecked(MTTSettings.value('onlyWritableState')) self.reference_btn.setChecked(MTTSettings.value('showReferenceState')) self.wrong_name_btn.setChecked(MTTSettings.value('showWrongNameState')) self.filter_instances_btn.setChecked( MTTSettings.value('filterInstances')) self.filter_grp.set_current_state(MTTSettings.value('filterGroup')) # VISIBILITY GROUP self.wrong_name_visibility_btn.setChecked( MTTSettings.value('vizWrongNameState')) self.wrong_path_visibility_btn.setChecked( MTTSettings.value('vizWrongPathState')) self.external_visibility_btn.setChecked( MTTSettings.value('vizExternalState')) self.basename_visibility_btn.setChecked( MTTSettings.value('showBasenameState')) self.namespace_visibility_btn.setChecked( not MTTSettings.value('showNamespaceState')) self.visibility_grp.set_current_state( MTTSettings.value('visibilityGroup')) # FOLDER GROUP self.folder_grp.set_current_state(MTTSettings.value('folderGroup')) # AUTO GROUP self.auto_reload_btn.setChecked(MTTSettings.value('autoReload')) self.auto_select_btn.setChecked(MTTSettings.value('autoSelect')) self.auto_rename_btn.setChecked(MTTSettings.value('autoRename')) self.auto_grp.set_current_state(MTTSettings.value('autoGroup')) # MTT TOOLS self.viewer_btn.setChecked(MTTSettings.value('viewerState')) self.tool_grp.set_current_state(MTTSettings.value('toolGroup', 1)) # MAYA TOOLS SHORTCUT self.maya_grp.set_current_state(MTTSettings.value('mayaGroup', 1))
def __create_actions(self): def add_action(lbl, tip, cmd, checkable=False, checked=False): a = QAction(lbl, self) a.setStatusTip(tip) a.triggered.connect(cmd) if checkable: a.setCheckable(True) a.setChecked(checked) return a self.help_a = add_action( 'Help', 'Opens the online Help page', self.on_settings_help) self.switch_edit_a = add_action( 'Switch Edit/Source', 'Replace "Edit" button by "Source" button', self.on_switch_source_edit_menu, True, MTTSettings.value('switchEdit')) self.heads_up_a = add_action( 'HeadsUp Message', 'Show HeadsUp Message in viewport', self.on_toggle_headsup, True, MTTSettings.value('showHeadsUp')) self.focus_filter_a = add_action( 'Focus Filter Field at Startup', 'Focus filter field at startup', self.on_toggle_focus, True, MTTSettings.value('filterFocus')) self.force_relative_path_a = add_action( 'Force Relative Path', 'Set a relative path when selecting a new file', self.on_force_relative_path, True, MTTSettings.value('forceRelativePath')) self.show_real_attr_value_a = add_action( 'Show Real Attribute Value', 'Show fullpath instead of filtering path as Attribute Editor', self.on_show_real_attribute_value, True, MTTSettings.value('showRealAttributeValue')) self.manage_quick_filter_a = add_action( 'Manage Quick Filters', 'Manage filters that popup with right clic in filter field', self.on_filter_manage_quick_filter) self.clear_completion_cache_a = add_action( 'Clear Completion Cache', 'Erase auto completion cache of filter field', self.on_filter_clear_completion_cache) self.override_panels_a = add_action( 'Add CreateNode Button to Editors', ('Add "Create Node" to HyperShade and ' 'Node Editor for the current session'), self.on_override_panels) self.export_to_csv = add_action( 'Export Texture List as CSV', 'Export current textures into a csv file', self.view.model.export_as_csv) self.about = add_action( 'About', 'About', self.on_settings_about)