示例#1
1
class Explorer(QTreeView):
    def __init__(self, parent=None):
        QTreeView.__init__(self)
        self.header().setHidden(True)
        self.setAnimated(True)

        # Modelo
        self.model = QFileSystemModel(self)
        # path = QDir.toNativeSeparators(QDir.homePath())
        # self.model.setRootPath(path)
        self.setModel(self.model)

        # Se ocultan algunas columnas
        self.hideColumn(1)
        self.hideColumn(2)
        self.hideColumn(3)
        # Conexion
        self.doubleClicked.connect(self._open_file)

    def _open_file(self, i):
        print(i)
        if not self.model.isDir(i):
            indice = self.model.index(i.row(), 0, i.parent())
            archivo = self.model.filePath(indice)
            print(archivo)
示例#2
0
class ConfigManager(QtGui.QMainWindow, Ui_ConfigManager):
    def __init__(self, *args, **kwargs):
        super(ConfigManager, self).__init__(*args, **kwargs)
        self.setupUi()
        self.bindUi()
        self.windows = {}

    def setupUi(self):
        super(ConfigManager, self).setupUi(self)

    def bindUi(self):
        self.model = QFileSystemModel()
        self.model.setRootPath("/")
        self.model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        self.treeView.setModel(self.model)
        if app_config.get_last_dir():
            self.treeView.setCurrentIndex(
                self.model.index(app_config.get_last_dir()))
        self.treeView.setAnimated(True)
        self.treeView.setIndentation(20)
        self.treeView.setSortingEnabled(True)
        self.treeView.setWindowTitle("Branded App Configurations")
        self.treeView.doubleClicked.connect(self.config_selected)
        self.set_recent_config_actions()

    def set_recent_config_actions(self):
        history = app_config.get_config_history()
        self.historyActions = []
        for k in history:
            a = QtGui.QAction(self)
            a.triggered.connect(lambda: self.open_config(k))
            a.setText(k)
            self.historyActions.append(a)
            self.menuRecent.addAction(a)

    @QtCore.Slot()
    def publish_clicked(self):
        #    index = self.treeView.currentIndex()
        pass

    def open_config(self, config_path):
        if os.path.exists(config_path):
            app_config.set_last_dir(os.path.dirname(config_path))
            if not config_path in self.windows:
                c = ConfigWindow(self)
                c.set_configuration(config_path, None)
                app_config.add_config_to_history(config_path)
                c.closeEvent = lambda x: self.windows.pop(config_path)
                self.windows[config_path] = c
            self.windows[config_path].show()

    @QtCore.Slot()
    def config_selected(self):
        print "Config is selected"
        p = self.model.filePath(self.treeView.currentIndex())
        config_path = os.path.join(p, "bc.json")
        config_path = config_path.replace('\\', '/')
        self.open_config(config_path)
示例#3
0
class ConfigManager(QtGui.QMainWindow, Ui_ConfigManager):
  def __init__(self, *args, **kwargs):
    super(ConfigManager, self).__init__(*args, **kwargs)
    self.setupUi()
    self.bindUi()
    self.windows = {}

  def setupUi(self):
    super(ConfigManager, self).setupUi(self)

  def bindUi(self):
    self.model = QFileSystemModel()
    self.model.setRootPath("/")
    self.model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
    self.treeView.setModel(self.model)
    if app_config.get_last_dir():
      self.treeView.setCurrentIndex(self.model.index(app_config.get_last_dir()))
    self.treeView.setAnimated(True)
    self.treeView.setIndentation(20)
    self.treeView.setSortingEnabled(True)
    self.treeView.setWindowTitle("Branded App Configurations")
    self.treeView.doubleClicked.connect(self.config_selected)
    self.set_recent_config_actions()

  def set_recent_config_actions(self):
    history = app_config.get_config_history()
    self.historyActions = []
    for k in history:
      a = QtGui.QAction(self)
      a.triggered.connect(lambda: self.open_config(k))
      a.setText(k)
      self.historyActions.append(a)
      self.menuRecent.addAction(a)

  @QtCore.Slot()
  def publish_clicked(self):
#    index = self.treeView.currentIndex()
    pass

  def open_config(self, config_path):
    if os.path.exists(config_path):
      app_config.set_last_dir(os.path.dirname(config_path))
      if not config_path in self.windows:
        c = ConfigWindow(self)
        c.set_configuration(config_path, None)
        app_config.add_config_to_history(config_path)
        c.closeEvent = lambda x: self.windows.pop(config_path)
        self.windows[config_path] = c
      self.windows[config_path].show()

  @QtCore.Slot()
  def config_selected(self):
    print "Config is selected"
    p = self.model.filePath(self.treeView.currentIndex())
    config_path = os.path.join(p, "bc.json")
    config_path = config_path.replace('\\', '/')
    self.open_config(config_path)
示例#4
0
class FileManagerModel(QObject, ObsLightGuiObject):
    '''
    Manage the file list widget and file-related buttons of the main window.
    '''
    def __init__(self, gui, manager):
        QObject.__init__(self)
        ObsLightGuiObject.__init__(self, gui)

        self.__treeView = None
        self.__lineEdit = None

        self._project = None
        self._package = None

        self._baseDirPath = "/"
        self._curentDirPath = "/"

        self.__systemModel = None

    def setTreeView(self, treeView):
        self.__treeView = treeView

    def setLineEdit(self, lineEdit):
        self.__lineEdit = lineEdit

    def getTreeView(self):
        return self.__treeView

    def _init_connect(self):
        if self.__treeView is not None:
            self.__treeView.doubleClicked.connect(self.on_TreeView_activated)
            self.__treeView.clicked.connect(self.on_TreeView_clicked)
            self.__treeView.expanded.connect(self.on_TreeView_expanded)
            self.__treeView.collapsed.connect(self.on_TreeView_expanded)

    def _isInit(self):
        return True

    def setCurrentProjectAndPackage(self, project, package):
        self._project = project
        self._package = package
#---------------------------------------------------------------------------------------------------

    @popupOnException
    def on_TreeView_activated(self, index):
        """
        When user double-clicks on an item, open it with default application.
        """
        filePath = index.model().filePath(index)
        self.manager.openFile(filePath)

    @popupOnException
    def on_TreeView_clicked(self, index):
        """
        When user clicks on an item, display the complete path
        of this item under the widget.
        """
        filePath = index.model().filePath(index)
        if self.__lineEdit is not None:
            self.__lineEdit.setText(filePath)

    @popupOnException
    def on_TreeView_expanded(self, _index):
        if self.__treeView is not None:
            self.__treeView.resizeColumnToContents(0)

        self._baseDirPath = None
        self._curentDirPath = None

    def _initBaseDir(self):
        pass

#---------------------------------------------------------------------------------------------------

    def refresh(self):
        # --- view ---------
        self.__systemModel = QFileSystemModel()
        if self._project is not None and self._package is not None and self.__treeView is not None:
            if self._isInit():
                self.__treeView.setEnabled(True)

                # Qt 4.6 do not know "directoryLoaded"
                if hasattr(self.__systemModel, "directoryLoaded"):
                    self.__systemModel.directoryLoaded.connect(
                        self.on_path_loaded)

                self._initBaseDir()

                self.__systemModel.setRootPath(self._baseDirPath)

                if self._baseDirPath != self._curentDirPath:
                    self.__systemModel.setRootPath(self._curentDirPath)

            else:
                self.__treeView.setEnabled(False)
            self.mainWindow.packageTabWidget.setEnabled(True)
        else:
            self.mainWindow.packageTabWidget.setEnabled(False)

        if self.__treeView is not None:
            self.__treeView.setModel(self.__systemModel)

        # Qt 4.6 do not know "directoryLoaded"
        if not hasattr(self.__systemModel, "directoryLoaded"):
            self.on_path_loaded(self.__baseDirPath)
            self.on_path_loaded(self.__curentDirPath)

    def on_path_loaded(self, path):
        """
        Called when the QFileSystem model loads paths.
        """
        if self.__treeView is not None:
            if path == self._baseDirPath:
                # Set the root index of the QTreeView to the root directory of
                # the project file system, so user does not see outside
                if self.__systemModel is not None:
                    self.__treeView.setRootIndex(
                        self.__systemModel.index(path))

            elif path == self._curentDirPath:
                # Set the current index of the QTreeView to the package directory
                # so it appears unfolded
                if self.__systemModel is not None:
                    self.__treeView.setCurrentIndex(
                        self.__systemModel.index(path))
            self.__treeView.resizeColumnToContents(0)
示例#5
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.build_dir_tree()
        self.setWindowIcon(QIcon('favicon.png'))
        self.actionAbout.triggered.connect(self.about)
        self.destButton.clicked.connect(self.destination_chooser)
        self.actionChoose_Destination.triggered.connect(
            self.destination_chooser)
        self.copyButton.clicked.connect(self.copy_files)
        self.actionStart_Copy.triggered.connect(self.copy_files)
        self.ckbxTrimDir.toggled.connect(self.update_table_view)
        self.treeView.expanded.connect(self.resize_tree_column)
        self.treeView.collapsed.connect(self.resize_tree_column)
        self.treeView.clicked.connect(self.update_table_view)
        self.trimdirCount.valueChanged.connect(self.update_table_view)

        self.listWidget.doubleClicked.connect(self.unselectItem)

        self.copyButton.setEnabled(False)
        self.lblTrimDir.setVisible(False)
        self.trimdirCount.setVisible(False)
        self.rbOWNewer.setVisible(False)
        self.rbOWLarger.setVisible(False)
        self.rbOWEither.setVisible(False)
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.PAIR)
        self.socket.bind("tcp://*:%s" % zmq_port)

        self.copyWorker = CopyWorker()
        self.connect(
            self.copyWorker,
            SIGNAL("copyComplete(QString, QString, QString, QString)"),
            self.copy_complete, Qt.QueuedConnection)
        self.connect(self.copyWorker, SIGNAL("spaceProblem(int, int)"),
                     self.space_problem, Qt.QueuedConnection)

    def unselectItem(self, item):
        ##need to figure out how to remove from the model
        self.listWidget.takeItem(item.row())

    def copy_complete(self, filecount, filesize, runtime, run_seconds):
        self.progress.setValue(self.progress.maximum())
        transfer_rate = round((float(filesize) * 1024) / float(run_seconds), 3)
        filesize = round(float(filesize), 3)
        QMessageBox.information(
            self,
            "File Copy Complete",
            """Your file copy has been successfully completed.\n
            Files processed:\t%s\n
            Data copied:\t%sGB\n
            Total runtime:\t%s\n
            Transfer Rate:\t%sMB/Sec""" %
            (filecount, filesize, runtime, transfer_rate),
            WindowModility=True)
        self.copyButton.setEnabled(True)

    def space_problem(self, dirsize, filesize):
        """Display a dialog to the user advising that there is not enough space in the destination
        directory.
        Input:
            dirsize :   integer - amount of space available in the destination directory
            filesize:   integer - size of the selected files
        Output:
            None, dialog is displayed to the user."""
        ##TODO: Set the messagebox modal property to true
        required_space = (filesize / 1024.00 / 1024.00 /
                          1024.00) - (dirsize / 1024.00 / 1024.00 / 1024.00)
        QMessageBox.critical(
            self,
            "Not enough space",
            """You do not have enough space in your selected destination to complete this operation\n
                             %s more GB space required""" % required_space,
            WindowModility=True)
        self.copyWorker.quit()
        self.copyButton.setEnabled(True)

    def build_dir_tree(self):
        """Add a directory tree listing to the QTreeView and set the root
        to the drive that it was run from.
        Input:
            None
        Output:
            None"""
        ##TODO: add linux support for the model root drive.
        self.model = QFileSystemModel(self)
        if sys.platform == 'win32':
            self.model.setRootPath(os.path.splitdrive(os.getcwd())[0])
        self.tree = self.treeView
        self.tree.setModel(self.model)
        self.tree.setAnimated(False)
        self.tree.setIndentation(20)
        self.tree.setSortingEnabled(True)

    def update_table_view(self):
        """Refresh listview with selected items in the treeView using
        the shared model.
        Input:
            None
        Output:
            None"""
        itemlist = [
            os.path.abspath(
                self.model.filePath(
                    self.model.index(selection.row(), 0, selection.parent())))
            for selection in self.treeView.selectedIndexes()
        ]
        self.listWidget.clear()
        self.listWidget.addItems(itemlist)

        nitemlist = []
        fileops = FileOperations()
        if not self.ckbxTrimDir.isChecked():
            flattencount = 0
        else:
            flattencount = self.trimdirCount.value()
        if self.lblDestPath.isEnabled():
            self.previewView.clear()
            for item in itemlist:
                nitemlist.append(
                    fileops.get_dest_filepath(item, self.lblDestPath.text(),
                                              flattencount))
            self.previewView.addItems(nitemlist)
        else:
            self.previewView.clear()
            self.previewView.addItems(['No destination folder selected'])

        self.resize_tree_column()

    def resize_tree_column(self):
        """Resize the treeView column to fit the contents.
        Input:
            None
        Output:
            None"""
        self.treeView.resizeColumnToContents(0)

    def copy_files(self):
        """Initiate copy process. File size is calculated first to
        check that there is enough space in the destination.
        If there is enough space then we start the copy of the files
        to their destination.
        Input:
            None
        Output:
            None"""
        self.copyButton.setEnabled(False)
        self.copyWorker.must_run = True
        self.connect(self.copyWorker,
                     SIGNAL("copyProgress(QString, QString, QString)"),
                     self.copy_progress, Qt.QueuedConnection)
        dest_dir = self.lblDestPath.text()
        if dest_dir == '':
            QMessageBox.critical(self,
                                 "Destination not set",
                                 "Please specify a destination path",
                                 WindowModility=True)
        else:
            copy_filelist = []
            for selection in self.treeView.selectedIndexes():
                indexItem = self.model.index(selection.row(), 0,
                                             selection.parent())
                copy_filelist.append(self.model.filePath(indexItem))
            if self.cbOWDest.isChecked():
                if self.rbOWEither.isChecked():
                    overwrite_option = 'either'
                elif self.rbOWLarger.isChecked():
                    overwrite_option = 'larger'
                elif self.rbOWNewer.isChecked():
                    overwrite_option = 'newer'
                else:
                    QMessageBox.critical(
                        self,
                        "Overwrite option missing",
                        """You did not select an overwrite option.""",
                        WindowModility=True)
                    self.copyButton.setEnabled(True)
                    return
            else:
                overwrite_option = None
            if not self.ckbxTrimDir.isChecked():
                flattencount = 0
            else:
                flattencount = self.trimdirCount.value()

            self.progress = QProgressDialog("Copy in progress.",
                                            "Cancel",
                                            0,
                                            100,
                                            modal=True)
            self.progress.canceled.connect(self.cancel_copy)
            self.progress.setWindowTitle('Copy Progress')
            var_values = {
                'destdir': dest_dir,
                'filelist': copy_filelist,
                'flattencount': flattencount,
                'overwrite_opt': overwrite_option
            }
            self.socket.send(json.dumps(var_values))
            self.copyWorker.start()

    def copy_progress(self, percentage_complete, filecount, filecomplete):
        """Display the progress bar with a completed percentage.
        Input:
            percentage_complete :   integer - the amount complete in percent.
            filecount           :   integer - the total number of files being processed.
            filecomplete        :   integer - the number of files that have already been processed.
        Output:
            None, dialog is updated"""
        ##TODO: display the current transfer rate
        ##TODO: display the current file being transferred and possibly the progress thereof.
        ##Perhaps use the statusbar method for this
        self.progress.setValue(int(percentage_complete))

    def cancel_copy(self):
        """Slot for the cancel command on the progress dialog.
        The must_run variable of the copyWorker class is set to False to terminate the copy.
        Input:
            None
        Output:
            None"""
        self.copyWorker.must_run = False
        self.copyButton.setEnabled(True)

    def statusbar_msg(self, msg):
        """Update the statusbar on the bottom of the screen.
        Input:
            msg     : string - Message that you would like displayed on the form.
        Output:
            None
        """
        self.statusbar.clearMessage()
        self.statusbar.showMessage(msg)

    def destination_chooser(self):
        """Show folder chooser dialog and update lblDestPath with path selected.
        Input:
            None
        Output:
            None"""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.Directory)
        dialog.setOption(QFileDialog.ShowDirsOnly)
        dialog.exec_()
        self.lblDestPath.setEnabled(True)
        self.lblDestPath.setText(
            os.path.abspath(dialog.directory().absolutePath()))
        self.update_table_view()
        self.copyButton.setEnabled(True)

    def about(self):
        """Popup a box with about message.
        Input:
            None
        Output:
            None"""
        QMessageBox.about(
            self,
            "About MClub Mover",
            """This program is designed to help make the process of copying \
files from multiple directories much easier and simpler.\n
This software is provided as is with absolutely no warranties.""",
            WindowModility=True)
示例#6
0
 def _create_file_system_model(self, root_path):
     model = QFileSystemModel()
     model.setRootPath(root_path)
     self.setModel(model)
     self.setRootIndex(model.index(root_path))
     return model
示例#7
0
class FileBrowser(QMainWindow):
    """Example file browsing widget. Based of the C++ example."""
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()

    def activated(self, index):
        fileInfo = self.fileSystemModel.fileInfo(index)

        if fileInfo.isDir() and fileInfo.fileName() != '.':
            if fileInfo.fileName() == '..':
                parent = self.view.rootIndex().parent()

                fileInfo = self.fileSystemModel.fileInfo(parent)

                if fileInfo.absoluteFilePath() == self.rootPath:
                    self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)

                self.view.setRootIndex(parent)

            else:
                self.fileSystemModel.setFilter(QDir.AllEntries | QDir.AllDirs)
                self.view.setRootIndex(index)

            self.setWindowTitle(fileInfo.fileName())
        else:
            if fileInfo.fileName() == '.':
                fileInfo = self.fileSystemModel.fileInfo(self.view.rootIndex())

            widget = DocumentPropertiesWidget(fileInfo, self.gallery, self)
            widget.setWindowFlags(self.window().windowFlags() | Qt.Dialog)
            widget.setAttribute(Qt.WA_DeleteOnClose)
            widget.setWindowModality(Qt.WindowModal)
            widget.show()

    def browseAudio(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.MusicLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Audio"))

    def browseDocuments(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Documents"))

    def browseImages(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.PicturesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Images"))

    def browseVideos(self):
        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Videos"))
示例#8
0
class FileBrowser(QMainWindow):
    """Example file browsing widget. Based of the C++ example."""
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()

    def activated(self, index):
        fileInfo = self.fileSystemModel.fileInfo(index)

        if fileInfo.isDir() and fileInfo.fileName() != '.':
            if fileInfo.fileName() == '..':
                parent = self.view.rootIndex().parent()

                fileInfo = self.fileSystemModel.fileInfo(parent)

                if fileInfo.absoluteFilePath() == self.rootPath:
                    self.fileSystemModel.setFilter(QDir.AllEntries
                                                   | QDir.NoDotAndDotDot
                                                   | QDir.AllDirs)

                self.view.setRootIndex(parent)

            else:
                self.fileSystemModel.setFilter(QDir.AllEntries | QDir.AllDirs)
                self.view.setRootIndex(index)

            self.setWindowTitle(fileInfo.fileName())
        else:
            if fileInfo.fileName() == '.':
                fileInfo = self.fileSystemModel.fileInfo(self.view.rootIndex())

            widget = DocumentPropertiesWidget(fileInfo, self.gallery, self)
            widget.setWindowFlags(self.window().windowFlags() | Qt.Dialog)
            widget.setAttribute(Qt.WA_DeleteOnClose)
            widget.setWindowModality(Qt.WindowModal)
            widget.show()

    def browseAudio(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.MusicLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Audio"))

    def browseDocuments(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.DocumentsLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Documents"))

    def browseImages(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.PicturesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Images"))

    def browseVideos(self):
        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.MoviesLocation)
        self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                       | QDir.AllDirs)
        self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
        self.setWindowTitle(self.tr("Videos"))
class MTTFilterFileDialog(QDialog):
    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 __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(
                QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)

    def __create_filter_ui(self):
        """ Create filter widgets """
        filter_layout = QHBoxLayout()
        filter_layout.setSpacing(1)
        filter_layout.setContentsMargins(0, 0, 0, 0)

        self.filter_reset_btn = QPushButton()
        icon = QIcon(':/filtersOff.png')
        self.filter_reset_btn.setIcon(icon)
        self.filter_reset_btn.setIconSize(QSize(22, 22))
        self.filter_reset_btn.setFixedSize(24, 24)
        self.filter_reset_btn.setToolTip('Reset filter')
        self.filter_reset_btn.setFlat(True)
        self.filter_reset_btn.clicked.connect(
            partial(self.on_filter_set_text, ''))

        self.filter_line = QLineEdit()
        self.filter_line.setPlaceholderText('Enter filter string here')
        self.filter_line.textChanged.connect(self.on_filter_change_text)

        completer = QCompleter(self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setModel(QStringListModel([], self))
        self.filter_line.setCompleter(completer)

        filter_layout.addWidget(self.filter_reset_btn)
        filter_layout.addWidget(self.filter_line)

        return filter_layout

    def on_filter_set_text(self, text=''):
        """ Set text in filter field """
        self.filter_line.setText(text)

    def on_filter_change_text(self, text):
        """ Apply filter string """
        if len(text):
            icon = QIcon(':/filtersOn.png')
            self.filter_reset_btn.setIcon(icon)
        else:
            icon = QIcon(':/filtersOff.png')
            self.filter_reset_btn.setIcon(icon)

        self.files_model.setNameFilters([
            '*%s*' % item.strip() for item in text.split(',') if item.strip()
        ])

    def on_node_type_changed(self, index):
        cmds.optionVar(
            sv=['MTT_lastNodeType', self.supported_node_type[index]])

    def on_double_click(self, index):
        current_item = self.files_model.filePath(index)
        if os.path.isdir(current_item):
            self.on_change_root_path(current_item)
        elif os.path.isfile(current_item):
            self.accept()

    def on_change_root_path(self, current_path):
        if current_path == SOURCEIMAGES_TAG:
            current_path = os.path.join(
                cmds.workspace(query=True, rootDirectory=True),
                cmds.workspace(fileRuleEntry='sourceImages'))

        self.files_model.setRootPath(current_path)
        self.files_list.setRootIndex(self.files_model.index(current_path))
        if self.path_edit:
            self.path_edit.setText(current_path)

        if self.parent_folder_btn:
            current_dir = QDir(current_path)
            self.parent_folder_btn.setEnabled(current_dir.cdUp())

    def on_go_up_parent(self):
        current_path = QDir(self.files_model.rootPath())
        current_path.cdUp()
        self.on_change_root_path(current_path.absolutePath())

    def on_enter_path(self):
        new_path = self.path_edit.text()
        if os.path.isdir(new_path):
            self.on_change_root_path(new_path)
        else:
            self.path_edit.setText(self.files_model.rootPath())

    def on_browse(self):
        current_path = self.files_model.rootPath()
        file_dialog = QFileDialog(self, 'Select a Folder', current_path)
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOption(QFileDialog.ShowDirsOnly)

        if file_dialog.exec_():
            self.on_change_root_path(file_dialog.selectedFiles()[0])

    def on_select_bookmark(self, selected, deselected):
        current_item = selected.indexes()
        if current_item:
            self.on_change_root_path(
                self.bookmark_list.selectedItems()[0].root_path)

    def on_add_bookmark(self):
        current_path = self.files_model.rootPath()
        self.on_add_bookmark_item(
            '%s|%s' % (os.path.basename(current_path), current_path))

    def on_add_bookmark_item(self, item):
        if item == '':
            return

        current_item = MTTBookmarkItem()
        current_item.add_raw_data(item)
        current_item.setSizeHint(QSize(40, 25))
        current_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable
                              | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)

        self.bookmark_list.addItem(current_item)

    def do_delete_bookmark(self):
        current_item = self.bookmark_list.selectedItems()
        if current_item:
            item_row = self.bookmark_list.row(current_item[0])
            self.bookmark_list.takeItem(item_row)
            del current_item[0]

    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 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 do_validate_selection(self):
        selection = self.files_list.selectedIndexes()
        if len(selection) == 1:
            current_path = self.files_model.filePath(selection[0])
            if os.path.isdir(current_path):
                self.on_change_root_path(current_path)
                return
        self.accept()

    def get_selected_files(self):
        selected_items = list()
        for item_index in self.files_list.selectedIndexes():
            current_path = self.files_model.filePath(item_index)
            if os.path.isfile(current_path):
                selected_items.append(current_path)
        return selected_items

    def get_node_type(self):
        return self.types.currentText() if self.types else self.defined_type

    def closeEvent(self, event):
        MTTSettings.set_value('FilterFileDialog/windowGeometry',
                              self.geometry())
        self.do_save_bookmark()

        self.deleteLater()
        event.accept()
class MTTFilterFileDialog(QDialog):
    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 __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)

    def __create_filter_ui(self):
        """ Create filter widgets """
        filter_layout = QHBoxLayout()
        filter_layout.setSpacing(1)
        filter_layout.setContentsMargins(0, 0, 0, 0)

        self.filter_reset_btn = QPushButton()
        icon = QIcon(':/filtersOff.png')
        self.filter_reset_btn.setIcon(icon)
        self.filter_reset_btn.setIconSize(QSize(22, 22))
        self.filter_reset_btn.setFixedSize(24, 24)
        self.filter_reset_btn.setToolTip('Reset filter')
        self.filter_reset_btn.setFlat(True)
        self.filter_reset_btn.clicked.connect(
            partial(self.on_filter_set_text, ''))

        self.filter_line = QLineEdit()
        self.filter_line.setPlaceholderText('Enter filter string here')
        self.filter_line.textChanged.connect(self.on_filter_change_text)

        completer = QCompleter(self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setModel(QStringListModel([], self))
        self.filter_line.setCompleter(completer)

        filter_layout.addWidget(self.filter_reset_btn)
        filter_layout.addWidget(self.filter_line)

        return filter_layout

    def on_filter_set_text(self, text=''):
        """ Set text in filter field """
        self.filter_line.setText(text)

    def on_filter_change_text(self, text):
        """ Apply filter string """
        if len(text):
            icon = QIcon(':/filtersOn.png')
            self.filter_reset_btn.setIcon(icon)
        else:
            icon = QIcon(':/filtersOff.png')
            self.filter_reset_btn.setIcon(icon)

        self.files_model.setNameFilters(
            ['*%s*' % item.strip() for item in text.split(',') if item.strip()])

    def on_node_type_changed(self, index):
        cmds.optionVar(sv=['MTT_lastNodeType', self.supported_node_type[index]])

    def on_double_click(self, index):
        current_item = self.files_model.filePath(index)
        if os.path.isdir(current_item):
            self.on_change_root_path(current_item)
        elif os.path.isfile(current_item):
            self.accept()

    def on_change_root_path(self, current_path):
        if current_path == SOURCEIMAGES_TAG:
            current_path = os.path.join(
                cmds.workspace(query=True, rootDirectory=True),
                cmds.workspace(fileRuleEntry='sourceImages')
            )

        self.files_model.setRootPath(current_path)
        self.files_list.setRootIndex(self.files_model.index(current_path))
        if self.path_edit:
            self.path_edit.setText(current_path)

        if self.parent_folder_btn:
            current_dir = QDir(current_path)
            self.parent_folder_btn.setEnabled(current_dir.cdUp())

    def on_go_up_parent(self):
        current_path = QDir(self.files_model.rootPath())
        current_path.cdUp()
        self.on_change_root_path(current_path.absolutePath())

    def on_enter_path(self):
        new_path = self.path_edit.text()
        if os.path.isdir(new_path):
            self.on_change_root_path(new_path)
        else:
            self.path_edit.setText(self.files_model.rootPath())

    def on_browse(self):
        current_path = self.files_model.rootPath()
        file_dialog = QFileDialog(self, 'Select a Folder', current_path)
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOption(QFileDialog.ShowDirsOnly)

        if file_dialog.exec_():
            self.on_change_root_path(file_dialog.selectedFiles()[0])

    def on_select_bookmark(self, selected, deselected):
        current_item = selected.indexes()
        if current_item:
            self.on_change_root_path(
                self.bookmark_list.selectedItems()[0].root_path)

    def on_add_bookmark(self):
        current_path = self.files_model.rootPath()
        self.on_add_bookmark_item(
            '%s|%s' % (os.path.basename(current_path), current_path))

    def on_add_bookmark_item(self, item):
        if item == '':
            return

        current_item = MTTBookmarkItem()
        current_item.add_raw_data(item)
        current_item.setSizeHint(QSize(40, 25))
        current_item.setFlags(
            Qt.ItemIsEnabled | Qt.ItemIsEditable |
            Qt.ItemIsSelectable | Qt.ItemIsDragEnabled
        )

        self.bookmark_list.addItem(current_item)

    def do_delete_bookmark(self):
        current_item = self.bookmark_list.selectedItems()
        if current_item:
            item_row = self.bookmark_list.row(current_item[0])
            self.bookmark_list.takeItem(item_row)
            del current_item[0]

    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 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 do_validate_selection(self):
        selection = self.files_list.selectedIndexes()
        if len(selection) == 1:
            current_path = self.files_model.filePath(selection[0])
            if os.path.isdir(current_path):
                self.on_change_root_path(current_path)
                return
        self.accept()

    def get_selected_files(self):
        selected_items = list()
        for item_index in self.files_list.selectedIndexes():
            current_path = self.files_model.filePath(item_index)
            if os.path.isfile(current_path):
                selected_items.append(current_path)
        return selected_items

    def get_node_type(self):
        return self.types.currentText() if self.types else self.defined_type

    def closeEvent(self, event):
        MTTSettings.set_value(
            'FilterFileDialog/windowGeometry', self.geometry())
        self.do_save_bookmark()

        self.deleteLater()
        event.accept()
示例#11
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.build_dir_tree()
        self.setWindowIcon(QIcon('favicon.png'))
        self.actionAbout.triggered.connect(self.about)
        self.destButton.clicked.connect(self.destination_chooser)
        self.actionChoose_Destination.triggered.connect(self.destination_chooser)
        self.copyButton.clicked.connect(self.copy_files)
        self.actionStart_Copy.triggered.connect(self.copy_files)
        self.ckbxTrimDir.toggled.connect(self.update_table_view)
        self.treeView.expanded.connect(self.resize_tree_column)
        self.treeView.collapsed.connect(self.resize_tree_column)
        self.treeView.clicked.connect(self.update_table_view)
        self.trimdirCount.valueChanged.connect(self.update_table_view)

        self.listWidget.doubleClicked.connect(self.unselectItem)

        self.copyButton.setEnabled(False)
        self.lblTrimDir.setVisible(False)
        self.trimdirCount.setVisible(False)
        self.rbOWNewer.setVisible(False)
        self.rbOWLarger.setVisible(False)
        self.rbOWEither.setVisible(False)
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.PAIR)
        self.socket.bind("tcp://*:%s" % zmq_port)

        self.copyWorker = CopyWorker()
        self.connect(self.copyWorker, SIGNAL("copyComplete(QString, QString, QString, QString)"), self.copy_complete, Qt.QueuedConnection)
        self.connect(self.copyWorker, SIGNAL("spaceProblem(int, int)"), self.space_problem, Qt.QueuedConnection)

    def unselectItem(self, item):
        ##need to figure out how to remove from the model
        self.listWidget.takeItem(item.row())

    def copy_complete(self, filecount, filesize, runtime, run_seconds):
        self.progress.setValue(self.progress.maximum())
        transfer_rate = round((float(filesize) * 1024) / float(run_seconds), 3)
        filesize = round(float(filesize), 3)
        QMessageBox.information(self, "File Copy Complete",
            """Your file copy has been successfully completed.\n
            Files processed:\t%s\n
            Data copied:\t%sGB\n
            Total runtime:\t%s\n
            Transfer Rate:\t%sMB/Sec""" % (filecount, filesize, runtime, transfer_rate),
            WindowModility=True)
        self.copyButton.setEnabled(True)

    def space_problem(self, dirsize, filesize):
        """Display a dialog to the user advising that there is not enough space in the destination
        directory.
        Input:
            dirsize :   integer - amount of space available in the destination directory
            filesize:   integer - size of the selected files
        Output:
            None, dialog is displayed to the user."""
        ##TODO: Set the messagebox modal property to true
        required_space = (filesize / 1024.00 / 1024.00 / 1024.00) - (dirsize / 1024.00 / 1024.00 / 1024.00)
        QMessageBox.critical(self,
                             "Not enough space",
                             """You do not have enough space in your selected destination to complete this operation\n
                             %s more GB space required""" % required_space,
                             WindowModility=True)
        self.copyWorker.quit()
        self.copyButton.setEnabled(True)

    def build_dir_tree(self):
        """Add a directory tree listing to the QTreeView and set the root
        to the drive that it was run from.
        Input:
            None
        Output:
            None"""
        ##TODO: add linux support for the model root drive.
        self.model = QFileSystemModel(self)
        if sys.platform == 'win32':
            self.model.setRootPath(os.path.splitdrive(os.getcwd())[0])
        self.tree = self.treeView
        self.tree.setModel(self.model)
        self.tree.setAnimated(False)
        self.tree.setIndentation(20)
        self.tree.setSortingEnabled(True)

    def update_table_view(self):
        """Refresh listview with selected items in the treeView using
        the shared model.
        Input:
            None
        Output:
            None"""
        itemlist = [os.path.abspath(
            self.model.filePath(
                self.model.index(selection.row(),
                    0,
                    selection.parent()
                    )
                )
            )
            for selection in self.treeView.selectedIndexes()]
        self.listWidget.clear()
        self.listWidget.addItems(itemlist)

        nitemlist = []
        fileops = FileOperations()
        if not self.ckbxTrimDir.isChecked():
            flattencount = 0
        else:
            flattencount = self.trimdirCount.value()
        if self.lblDestPath.isEnabled():
            self.previewView.clear()
            for item in itemlist:
                nitemlist.append(fileops.get_dest_filepath(item, self.lblDestPath.text(), flattencount))
            self.previewView.addItems(nitemlist)
        else:
            self.previewView.clear()
            self.previewView.addItems(['No destination folder selected'])

        self.resize_tree_column()

    def resize_tree_column(self):
        """Resize the treeView column to fit the contents.
        Input:
            None
        Output:
            None"""
        self.treeView.resizeColumnToContents(0)

    def copy_files(self):
        """Initiate copy process. File size is calculated first to
        check that there is enough space in the destination.
        If there is enough space then we start the copy of the files
        to their destination.
        Input:
            None
        Output:
            None"""
        self.copyButton.setEnabled(False)
        self.copyWorker.must_run = True
        self.connect(self.copyWorker, SIGNAL("copyProgress(QString, QString, QString)"), self.copy_progress, Qt.QueuedConnection)
        dest_dir = self.lblDestPath.text()
        if dest_dir == '':
            QMessageBox.critical(self, "Destination not set", "Please specify a destination path", WindowModility=True)
        else:
            copy_filelist = []
            for selection in self.treeView.selectedIndexes():
                indexItem = self.model.index(selection.row(), 0, selection.parent())
                copy_filelist.append(self.model.filePath(indexItem))
            if self.cbOWDest.isChecked():
                if self.rbOWEither.isChecked():
                    overwrite_option = 'either'
                elif self.rbOWLarger.isChecked():
                    overwrite_option = 'larger'
                elif self.rbOWNewer.isChecked():
                    overwrite_option = 'newer'
                else:
                    QMessageBox.critical(self,
                        "Overwrite option missing",
                        """You did not select an overwrite option.""",
                        WindowModility=True)
                    self.copyButton.setEnabled(True)
                    return
            else:
                overwrite_option = None
            if not self.ckbxTrimDir.isChecked():
                flattencount = 0
            else:
                flattencount = self.trimdirCount.value()

            self.progress = QProgressDialog("Copy in progress.", "Cancel", 0, 100, modal=True)
            self.progress.canceled.connect(self.cancel_copy)
            self.progress.setWindowTitle('Copy Progress')
            var_values = {'destdir': dest_dir, 'filelist': copy_filelist, 'flattencount': flattencount, 'overwrite_opt': overwrite_option}
            self.socket.send(json.dumps(var_values))
            self.copyWorker.start()

    def copy_progress(self, percentage_complete, filecount, filecomplete):
        """Display the progress bar with a completed percentage.
        Input:
            percentage_complete :   integer - the amount complete in percent.
            filecount           :   integer - the total number of files being processed.
            filecomplete        :   integer - the number of files that have already been processed.
        Output:
            None, dialog is updated"""
        ##TODO: display the current transfer rate
        ##TODO: display the current file being transferred and possibly the progress thereof.
        ##Perhaps use the statusbar method for this
        self.progress.setValue(int(percentage_complete))

    def cancel_copy(self):
        """Slot for the cancel command on the progress dialog.
        The must_run variable of the copyWorker class is set to False to terminate the copy.
        Input:
            None
        Output:
            None"""
        self.copyWorker.must_run = False
        self.copyButton.setEnabled(True)

    def statusbar_msg(self, msg):
        """Update the statusbar on the bottom of the screen.
        Input:
            msg     : string - Message that you would like displayed on the form.
        Output:
            None
        """
        self.statusbar.clearMessage()
        self.statusbar.showMessage(msg)

    def destination_chooser(self):
        """Show folder chooser dialog and update lblDestPath with path selected.
        Input:
            None
        Output:
            None"""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.Directory)
        dialog.setOption(QFileDialog.ShowDirsOnly)
        dialog.exec_()
        self.lblDestPath.setEnabled(True)
        self.lblDestPath.setText(os.path.abspath(dialog.directory().absolutePath()))
        self.update_table_view()
        self.copyButton.setEnabled(True)

    def about(self):
        """Popup a box with about message.
        Input:
            None
        Output:
            None"""
        QMessageBox.about(self, "About MClub Mover",
                """This program is designed to help make the process of copying \
files from multiple directories much easier and simpler.\n
This software is provided as is with absolutely no warranties.""",
                WindowModility=True)