Exemplo n.º 1
0
class Explorador(custom_dock.CustomDock):

    def __init__(self, parent=None):
        custom_dock.CustomDock.__init__(self)
        self.explorador = QTreeView()
        self.setWidget(self.explorador)
        self.explorador.header().setHidden(True)
        self.explorador.setAnimated(True)

        # Modelo
        self.modelo = QFileSystemModel(self.explorador)
        path = QDir.toNativeSeparators(QDir.homePath())
        self.modelo.setRootPath(path)
        self.explorador.setModel(self.modelo)
        self.modelo.setNameFilters(["*.c", "*.h", "*.s"])
        self.explorador.setRootIndex(QModelIndex(self.modelo.index(path)))
        self.modelo.setNameFilterDisables(False)

        # Se ocultan algunas columnas
        self.explorador.hideColumn(1)
        self.explorador.hideColumn(2)
        self.explorador.hideColumn(3)

        # Conexion
        self.explorador.doubleClicked.connect(self._abrir_archivo)

        EDIS.cargar_lateral("explorador", self)

    def _abrir_archivo(self, i):
        if not self.modelo.isDir(i):
            indice = self.modelo.index(i.row(), 0, i.parent())
            archivo = self.modelo.filePath(indice)
            principal = EDIS.componente("principal")
            principal.abrir_archivo(archivo)
Exemplo n.º 2
0
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)
        self.model.setNameFilters(["*.c", "*.h", "*.s"])
        self.setRootIndex(QModelIndex(self.model.index(path)))
        self.model.setNameFilterDisables(False)

        # Se ocultan algunas columnas
        self.hideColumn(1)
        self.hideColumn(2)
        self.hideColumn(3)

        # Conexion
        self.doubleClicked.connect(self._open_file)

        Edis.load_lateral("explorer", self)

    def _open_file(self, i):
        if not self.model.isDir(i):
            indice = self.model.index(i.row(), 0, i.parent())
            archivo = self.model.filePath(indice)
            principal = Edis.get_component("principal")
            principal.open_file(archivo)
Exemplo n.º 3
0
class DataWidget(ui_datawidget.Ui_widget, WidgetBase):
    def __init__(self, parent=None):
        super(DataWidget, self).__init__(parent)
        self.setupUi(self)
        self.model = QFileSystemModel()
        self.settings = None
        allfilters = []
        filters = re.findall(
            r"\((.*?)\)",
            QgsProviderRegistry.instance().fileVectorFilters())[1:]
        for filter in filters:
            allfilters = allfilters + filter.split(" ")

        filters += re.findall(
            r"\((.*?)\)",
            QgsProviderRegistry.instance().fileRasterFilters())[1:]
        for filter in filters:
            allfilters = allfilters + filter.split(" ")
        self.model.setNameFilters(allfilters)
        self.model.setNameFilterDisables(False)
        self.listDataList.setModel(self.model)
        self.btnAddData.pressed.connect(self.open_data_folder)
        for col in range(self.model.columnCount())[1:]:
            self.listDataList.hideColumn(col)
        self.service = None

    def open_data_folder(self):
        """
        Open the data folder of the project using the OS
        """
        path = os.path.join(self.data['data_root'])
        openfolder(path)

    def set_data(self, data):
        super(DataWidget, self).set_data(data)
        self.service = DataService(self.config)

        root = data['data_root']

        if not os.path.exists(root):
            os.mkdir(root)
        self.model.setRootPath(root)
        self.listDataList.setRootIndex(self.model.index(root))
        self.refresh()

    def write_config(self):
        self.logger.info("Data write config")
        DataService(self.config).update_date_to_latest()
        super(DataWidget, self).write_config()

    def refresh(self):
        self.lastSaveLabel.setText("Last save date: {}".format(
            self.service.last_save_date))
Exemplo n.º 4
0
 def open_project(self, project):
     project_path = project.path
     qfsm = None  # Should end up having a QFileSystemModel
     if project_path not in self.__projects:
         qfsm = QFileSystemModel()
         project.model = qfsm
         qfsm.setRootPath(project_path)
         qfsm.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDotAndDotDot)
         # If set to true items that dont match are displayed disabled
         qfsm.setNameFilterDisables(False)
         pext = ["*{0}".format(x) for x in project.extensions]
         logger.debug(pext)
         qfsm.setNameFilters(pext)
         self.__projects[project_path] = project
         self.__check_files_for(project_path)
         self.emit(SIGNAL("projectOpened(PyQt_PyObject)"), project)
     else:
         qfsm = self.__projects[project_path]
     return qfsm
Exemplo n.º 5
0
 def open_project(self, project):
     project_path = project.path
     qfsm = None  # Should end up having a QFileSystemModel
     if project_path not in self.__projects:
         qfsm = QFileSystemModel()
         project.model = qfsm
         qfsm.setRootPath(project_path)
         qfsm.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDotAndDotDot)
         # If set to true items that dont match are displayed disabled
         qfsm.setNameFilterDisables(False)
         pext = ["*{0}".format(x) for x in project.extensions]
         logger.debug(pext)
         qfsm.setNameFilters(pext)
         self.__projects[project_path] = project
         self.__check_files_for(project_path)
         self.emit(SIGNAL("projectOpened(PyQt_PyObject)"), project)
     else:
         qfsm = self.__projects[project_path]
     return qfsm
Exemplo n.º 6
0
    def load_tree(self, project):
        """Load the tree view on the right based on the project selected."""
        qfsm = QFileSystemModel()
        #FIXME it's not loading the proper folder, just the root /
        qfsm.setRootPath(project.path)
        qfsm.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        qfsm.setNameFilterDisables(False)
        pext = ["*{0}".format(x) for x in project.extensions]
        qfsm.setNameFilters(pext)
        self._tree.setModel(qfsm)

        t_header = self._tree.header()
        t_header.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        t_header.setResizeMode(0, QHeaderView.Stretch)
        t_header.setStretchLastSection(False)
        t_header.setClickable(True)

        self._tree.hideColumn(1)  # Size
        self._tree.hideColumn(2)  # Type
        self._tree.hideColumn(3)  # Modification date
Exemplo n.º 7
0
    def load_tree(self, project):
        """Load the tree view on the right based on the project selected."""
        qfsm = QFileSystemModel()
        qfsm.setRootPath(project.path)
        load_index = qfsm.index(qfsm.rootPath())
        qfsm.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        qfsm.setNameFilterDisables(False)
        pext = ["*{0}".format(x) for x in project.extensions]
        qfsm.setNameFilters(pext)

        self._tree.setModel(qfsm)
        self._tree.setRootIndex(load_index)

        t_header = self._tree.header()
        t_header.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        t_header.setResizeMode(0, QHeaderView.Stretch)
        t_header.setStretchLastSection(False)
        t_header.setClickable(True)

        self._tree.hideColumn(1)  # Size
        self._tree.hideColumn(2)  # Type
        self._tree.hideColumn(3)  # Modification date
Exemplo n.º 8
0
    class ExampleApp(QtGui.QMainWindow, main_form.Ui_MainWindow):
        def __init__(self):
            super(self.__class__, self).__init__()
            self.setupUi(
                self)  # This is defined in design.py file automatically

            # self.listWidget_Xoutput_files.addItem("deneme")

            cleaner_files_path = os.path.join(str(QDir.currentPath()),
                                              "cleaner_files")
            if not os.path.exists(cleaner_files_path):
                os.mkdir(cleaner_files_path)

            self.model = QFileSystemModel()
            self.model.setRootPath(cleaner_files_path)

            self.model.setNameFilters(QStringList(["Xoutput-n_analyses-*.txt"
                                                   ]))
            self.model.setNameFilterDisables(False)
            self.model.setFilter(QDir.Dirs | QDir.Files)

            self.treeView_Xoutput_files.setModel(self.model)

            self.treeView_Xoutput_files.setRootIndex(
                self.model.index(cleaner_files_path))

            self.treeView_Xoutput_files.setColumnWidth(0, 500)

            self.treeView_Xoutput_files.selectionModel(
            ).selectionChanged.connect(self.load_and_view_file_contents)

            self.rules_dict = {}

            self.special_button_for_level_01.setDisabled(True)

        def load_and_view_file_contents(self, current, previous):

            print current.indexes()
            model_index = current.indexes()[0]

            filename = self.model.data(model_index).toString()

            import re
            m = re.match(r"Xoutput-n_analyses-([0-9]+)", filename)
            if m:
                n_analyzes = int(m.group(1))
            else:
                n_analyzes = -1

            if n_analyzes == 1:
                self.special_button_for_level_01.setDisabled(False)
                self.special_button_for_level_01.clicked.connect(
                    self.add_all_level_01_to_rule_dict)
            else:
                self.special_button_for_level_01.setDisabled(True)

            with codecs.open(filename, "r", encoding="utf8") as f:
                lines = f.readlines()
                # print lines
                self.listWidget_selected_file_contents.clear()
                self.listWidget_selected_file_contents.addItems(
                    QStringList(lines))
                self.listWidget_selected_file_contents.selectionModel(
                ).selectionChanged.connect(
                    self.load_and_view_samples_from_train_and_dev)

            self.load_and_view_rule_file_contents(n_analyzes)

        def load_and_view_rule_file_contents(self, n_analyzes):
            # load rules file
            self.rules_dict = {}
            rules_filename = "Xoutput-n_analyses-%02d.txt.rules" % n_analyzes
            try:
                with codecs.open(rules_filename, "r") as rules_f:
                    self.output_file_load_status.setText("%s loaded." %
                                                         rules_filename)
                    self.output_file_load_status.setStyleSheet(
                        "QLabel { color : green; }")

                    rules = []

                    line = rules_f.readline().strip()
                    while line:
                        rules.append(line.split(" "))
                        self.rules_dict[int(
                            line.split(" ")[0])] = line.split(" ")
                        line = rules_f.readline().strip()

                    self.update_tableWidgetxxxx(
                        self.tableWidget_output_file_contents,
                        sorted(self.rules_dict.items(), key=lambda x: x[0]),
                        len(self.rules_dict.keys()), 1 + 1 + n_analyzes +
                        1)  # id + golden + FST analyzes + selected

            except IOError as e:
                # print "File not found"
                self.output_file_load_status.setText("File not found")
                self.output_file_load_status.setStyleSheet(
                    "QLabel { color : red; }")

                self.update_tableWidgetxxxx(
                    self.tableWidget_output_file_contents, [], 0,
                    1)  # id + golden + FST analyzes + selected

        def update_tableWidgetxxxx(self, table_widget, rules, row_count,
                                   col_count):
            table_widget.clear()
            table_widget.setColumnCount(col_count)
            table_widget.setRowCount(row_count)

            if rules:
                for row in range(table_widget.rowCount()):
                    row_items = rules[row]
                    print row_items
                    item = self.listWidget_selected_file_contents.item(
                        int(row_items[0]) - 1)  # type: QListWidgetItem
                    item.setBackgroundColor(QtGui.QColor(255, 0, 0, 127))
                    for column in range(table_widget.columnCount()):
                        if column < len(row_items[1]):
                            table_widget.setItem(
                                row, column,
                                QTableWidgetItem(
                                    row_items[1][column].decode("utf8")))

                # self.tableWidget_samples_from_train_and_dev.resizeColumnToContents()
                for column in range(table_widget.columnCount()):
                    table_widget.resizeColumnToContents(column)

        def update_corrected_morph_analysis(self, current, previous):

            model_index = current.indexes()[0]

            self.textEdit_2.setPlainText(
                self.listWidget_selected_row.model().data(
                    model_index).toString())

        def add_all_level_01_to_rule_dict(self):

            self.rules_dict = {}

            for idx in range(self.listWidget_selected_file_contents.count()):
                row_items = unicode(
                    self.listWidget_selected_file_contents.item(
                        idx).text()).strip().split(" ")

                rules_item = [
                    x.encode("utf8") for x in
                    [row_items[0], row_items[4], row_items[-1], row_items[-1]]
                ]

                self.rules_dict[int(row_items[0])] = rules_item

            self.update_tableWidgetxxxx(
                self.tableWidget_output_file_contents,
                sorted(self.rules_dict.items(), key=lambda x: x[0]),
                len(self.rules_dict.keys()),
                1 + 1 + 1 + 1)  # id + golden + FST analyzes + selected

        def add_to_the_rule_dict(self, state):

            n_analyzes, entry_id = [
                int(x) for x in self.label_8.text().split(" ")
            ]

            other_analyzes = [
                self.listWidget_selected_row.item(i)
                for i in range(self.listWidget_selected_row.count())
            ]  # type: list[QListWidgetItem]

            rules_item = [unicode(x).encode("utf8") for x in [entry_id,
                          self.textEdit_golden_morph_analysis.toPlainText()] + \
                          [x.text() for x in other_analyzes] + \
                         [self.textEdit_2.toPlainText()]]

            self.rules_dict[entry_id] = rules_item

            self.update_tableWidgetxxxx(
                self.tableWidget_output_file_contents,
                sorted(self.rules_dict.items(), key=lambda x: x[0]),
                len(self.rules_dict.keys()), 1 + 1 + n_analyzes +
                1)  # id + golden + FST analyzes + selected

        def load_and_view_samples_from_train_and_dev(self, current, previous):
            print current.indexes()

            model_index = current.indexes()[0]

            morph_analyzes = unicode(
                self.listWidget_selected_file_contents.model().data(
                    model_index).toString()).strip().split(" ")
            # print morph_analyzes
            golden_morph_analysis = morph_analyzes[4]
            target = golden_morph_analysis[1:]

            other_morph_analyzes = morph_analyzes[5:]

            n_analyzes = len(other_morph_analyzes)

            self.label_3.setText("selected row id: %d" %
                                 int(morph_analyzes[0]))
            self.label_8.setText("%d %d" %
                                 (int(n_analyzes), int(morph_analyzes[0])))

            self.listWidget_selected_row.clear()
            self.listWidget_selected_row.addItems(
                QStringList(other_morph_analyzes))

            self.textEdit_golden_morph_analysis.setPlainText(
                golden_morph_analysis)

            # self.addRuleToTheListButton.clicked.connect(
            #     partial(self.save_to_file, n_analyzes=n_analyzes, entry_id=int(morph_analyzes[0])))

            # from functools import partial
            self.addRuleToTheListButton.clicked.connect(
                self.add_to_the_rule_dict)

            if len(other_morph_analyzes) == 1:
                self.textEdit_2.setPlainText(other_morph_analyzes[0])

            self.listWidget_selected_row.selectionModel(
            ).selectionChanged.connect(self.update_corrected_morph_analysis)

            print type(target)
            print target
            print target.encode("utf8")

            # target = target.replace("?", "\?")

            lines = subprocess.check_output(
                ("grep -F -m 50 %s ./dataset/errors.gungor.ner.train_and_dev" %
                 target).split(" "),
                shell=False)

            # print lines

            lines = [x.decode("utf8") for x in lines.split("\n")]

            print type(lines[0])
            print len(lines)

            self.tableWidget_samples_from_train_and_dev.clear()

            self.tableWidget_samples_from_train_and_dev.setColumnCount(
                n_analyzes + 1)
            self.tableWidget_samples_from_train_and_dev.setRowCount(
                len(lines) - 1)

            for row in range(
                    self.tableWidget_samples_from_train_and_dev.rowCount()):
                row_items = lines[row].split(" ")[2:]
                for column in range(
                        self.tableWidget_samples_from_train_and_dev.
                        columnCount()):
                    if column < len(row_items):
                        self.tableWidget_samples_from_train_and_dev.setItem(
                            row, column, QTableWidgetItem(row_items[column]))

            # self.tableWidget_samples_from_train_and_dev.resizeColumnToContents()
            for column in range(
                    self.tableWidget_samples_from_train_and_dev.columnCount()):
                self.tableWidget_samples_from_train_and_dev.resizeColumnToContents(
                    column)

            self.sort_and_save_button.clicked.connect(self.sort_and_save)

        def sort_and_save(self):

            indexes = self.treeView_Xoutput_files.selectedIndexes()

            model_index = indexes[0]

            filename = self.model.data(model_index).toString()

            with open(filename + ".rules", "w") as f:
                for row in range(
                        self.tableWidget_output_file_contents.rowCount()):
                    row_content = []
                    for column in range(self.tableWidget_output_file_contents.
                                        columnCount()):
                        cell_content = self.tableWidget_output_file_contents.item(
                            row, column).text()  # type: QString
                        if cell_content:
                            row_content.append(
                                unicode(cell_content).encode("utf8"))
                    if row != 0:
                        f.write("\n")
                    f.write(" ".join(row_content))
Exemplo n.º 9
0
class DirView(QTreeView):
    """Base file/directory tree view"""
    def __init__(self, parent=None):
        super(DirView, self).__init__(parent)
        self.name_filters = None
        self.parent_widget = parent
        self.valid_types = None
        self.show_all = None
        self.menu = None
        self.common_actions = None
        self.__expanded_state = None
        self._to_be_loaded = None
        self.fsmodel = None
        self.setup_fs_model()
        self._scrollbar_positions = None

    #---- Model
    def setup_fs_model(self):
        """Setup filesystem model"""
        filters = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot
        self.fsmodel = QFileSystemModel(self)
        self.fsmodel.setFilter(filters)
        self.fsmodel.setNameFilterDisables(False)

    def install_model(self):
        """Install filesystem model"""
        self.setModel(self.fsmodel)

    def setup_view(self):
        """Setup view"""
        self.install_model()
        self.connect(self.fsmodel, SIGNAL('directoryLoaded(QString)'),
                     lambda: self.resizeColumnToContents(0))
        self.setAnimated(False)
        self.setSortingEnabled(True)
        self.sortByColumn(0, Qt.AscendingOrder)

    def set_name_filters(self, name_filters):
        """Set name filters"""
        self.name_filters = name_filters
        self.fsmodel.setNameFilters(name_filters)

    def set_show_all(self, state):
        """Toggle 'show all files' state"""
        if state:
            self.fsmodel.setNameFilters([])
        else:
            self.fsmodel.setNameFilters(self.name_filters)

    def get_filename(self, index):
        """Return filename associated with *index*"""
        if index:
            return osp.normpath(unicode(self.fsmodel.filePath(index)))

    def get_index(self, filename):
        """Return index associated with filename"""
        return self.fsmodel.index(filename)

    def get_selected_filenames(self):
        """Return selected filenames"""
        if self.selectionMode() == self.ExtendedSelection:
            return [self.get_filename(idx) for idx in self.selectedIndexes()]
        else:
            return [self.get_filename(self.currentIndex())]

    def get_dirname(self, index):
        """Return dirname associated with *index*"""
        fname = self.get_filename(index)
        if fname:
            if osp.isdir(fname):
                return fname
            else:
                return osp.dirname(fname)

    #---- Tree view widget
    def setup(self,
              name_filters=['*.py', '*.pyw'],
              valid_types=('.py', '.pyw'),
              show_all=False):
        """Setup tree widget"""
        self.setup_view()

        self.set_name_filters(name_filters)
        self.valid_types = valid_types
        self.show_all = show_all

        # Setup context menu
        self.menu = QMenu(self)
        self.common_actions = self.setup_common_actions()

    #---- Context menu
    def setup_common_actions(self):
        """Setup context menu common actions"""
        # Filters
        filters_action = create_action(self,
                                       _("Edit filename filters..."),
                                       None,
                                       get_icon('filter.png'),
                                       triggered=self.edit_filter)
        # Show all files
        all_action = create_action(self,
                                   _("Show all files"),
                                   toggled=self.toggle_all)
        all_action.setChecked(self.show_all)
        self.toggle_all(self.show_all)

        return [filters_action, all_action]

    def edit_filter(self):
        """Edit name filters"""
        filters, valid = QInputDialog.getText(self, _('Edit filename filters'),
                                              _('Name filters:'),
                                              QLineEdit.Normal,
                                              ", ".join(self.name_filters))
        if valid:
            filters = [f.strip() for f in unicode(filters).split(',')]
            self.parent_widget.sig_option_changed.emit('name_filters', filters)
            self.set_name_filters(filters)

    def toggle_all(self, checked):
        """Toggle all files mode"""
        self.parent_widget.sig_option_changed.emit('show_all', checked)
        self.show_all = checked
        self.set_show_all(checked)

    def create_file_new_actions(self, fnames):
        """Return actions for submenu 'New...'"""
        if not fnames:
            return []
        new_file_act = create_action(
            self,
            _("File..."),
            icon='filenew.png',
            triggered=lambda: self.new_file(fnames[-1]))
        new_module_act = create_action(
            self,
            _("Module..."),
            icon='py.png',
            triggered=lambda: self.new_module(fnames[-1]))
        new_folder_act = create_action(
            self,
            _("Folder..."),
            icon='folder_new.png',
            triggered=lambda: self.new_folder(fnames[-1]))
        new_package_act = create_action(
            self,
            _("Package..."),
            icon=get_icon('package_collapsed.png'),
            triggered=lambda: self.new_package(fnames[-1]))
        return [
            new_file_act, new_folder_act, None, new_module_act, new_package_act
        ]

    def create_file_import_actions(self, fnames):
        """Return actions for submenu 'Import...'"""
        return []

    def create_file_manage_actions(self, fnames):
        """Return file management actions"""
        only_files = all([osp.isfile(_fn) for _fn in fnames])
        only_modules = all([
            osp.splitext(_fn)[1] in ('.py', '.pyw', '.ipy') for _fn in fnames
        ])
        only_valid = all(
            [osp.splitext(_fn)[1] in self.valid_types for _fn in fnames])
        run_action = create_action(self,
                                   _("Run"),
                                   icon="run_small.png",
                                   triggered=self.run)
        edit_action = create_action(self,
                                    _("Edit"),
                                    icon="edit.png",
                                    triggered=self.clicked)
        move_action = create_action(self,
                                    _("Move..."),
                                    icon="move.png",
                                    triggered=self.move)
        delete_action = create_action(self,
                                      _("Delete..."),
                                      icon="delete.png",
                                      triggered=self.delete)
        rename_action = create_action(self,
                                      _("Rename..."),
                                      icon="rename.png",
                                      triggered=self.rename)
        open_action = create_action(self, _("Open"), triggered=self.open)

        actions = []
        if only_modules:
            actions.append(run_action)
        if only_valid and only_files:
            actions.append(edit_action)
        else:
            actions.append(open_action)
        actions += [delete_action, rename_action]
        basedir = fixpath(osp.dirname(fnames[0]))
        if all([fixpath(osp.dirname(_fn)) == basedir for _fn in fnames]):
            actions.append(move_action)
        actions += [None]

        # VCS support is quite limited for now, so we are enabling the VCS
        # related actions only when a single file/folder is selected:
        dirname = fnames[0] if osp.isdir(fnames[0]) else osp.dirname(fnames[0])
        if len(fnames) == 1 and vcs.is_vcs_repository(dirname):
            vcs_ci = create_action(self,
                                   _("Commit"),
                                   icon="vcs_commit.png",
                                   triggered=lambda fnames=[dirname]: self.
                                   vcs_command(fnames, tool='commit'))
            vcs_log = create_action(self,
                                    _("Browse repository"),
                                    icon="vcs_browse.png",
                                    triggered=lambda fnames=[dirname]: self.
                                    vcs_command(fnames, tool='browse'))
            actions += [None, vcs_ci, vcs_log]

        return actions

    def create_folder_manage_actions(self, fnames):
        """Return folder management actions"""
        actions = []
        if os.name == 'nt':
            _title = _("Open command prompt here")
        else:
            _title = _("Open terminal here")
        action = create_action(
            self,
            _title,
            icon="cmdprompt.png",
            triggered=lambda fnames=fnames: self.open_terminal(fnames))
        actions.append(action)
        _title = _("Open Python interpreter here")
        action = create_action(
            self,
            _title,
            icon="python.png",
            triggered=lambda fnames=fnames: self.open_interpreter(fnames))
        actions.append(action)
        return actions

    def create_context_menu_actions(self):
        """Create context menu actions"""
        actions = []
        fnames = self.get_selected_filenames()
        new_actions = self.create_file_new_actions(fnames)
        if len(new_actions) > 1:
            # Creating a submenu only if there is more than one entry
            new_act_menu = QMenu(_('New'), self)
            add_actions(new_act_menu, new_actions)
            actions.append(new_act_menu)
        else:
            actions += new_actions
        import_actions = self.create_file_import_actions(fnames)
        if len(import_actions) > 1:
            # Creating a submenu only if there is more than one entry
            import_act_menu = QMenu(_('Import'), self)
            add_actions(import_act_menu, import_actions)
            actions.append(import_act_menu)
        else:
            actions += import_actions
        if actions:
            actions.append(None)
        if fnames:
            actions += self.create_file_manage_actions(fnames)
        if actions:
            actions.append(None)
        if fnames and all([osp.isdir(_fn) for _fn in fnames]):
            actions += self.create_folder_manage_actions(fnames)
        if actions:
            actions.append(None)
        actions += self.common_actions
        return actions

    def update_menu(self):
        """Update context menu"""
        self.menu.clear()
        add_actions(self.menu, self.create_context_menu_actions())

    #---- Events
    def viewportEvent(self, event):
        """Reimplement Qt method"""

        # Prevent Qt from crashing or showing warnings like:
        # "QSortFilterProxyModel: index from wrong model passed to
        # mapFromSource", probably due to the fact that the file system model
        # is being built. See Issue 1250.
        #
        # This workaround was inspired by the following KDE bug:
        # https://bugs.kde.org/show_bug.cgi?id=172198
        #
        # Apparently, this is a bug from Qt itself.
        self.executeDelayedItemsLayout()

        return QTreeView.viewportEvent(self, event)

    def contextMenuEvent(self, event):
        """Override Qt method"""
        self.update_menu()
        self.menu.popup(event.globalPos())

    def keyPressEvent(self, event):
        """Reimplement Qt method"""
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.clicked()
        elif event.key() == Qt.Key_F2:
            self.rename()
        elif event.key() == Qt.Key_Delete:
            self.delete()
        else:
            QTreeView.keyPressEvent(self, event)

    def mouseDoubleClickEvent(self, event):
        """Reimplement Qt method"""
        QTreeView.mouseDoubleClickEvent(self, event)
        self.clicked()

    def clicked(self):
        """Selected item was double-clicked or enter/return was pressed"""
        fnames = self.get_selected_filenames()
        for fname in fnames:
            if osp.isdir(fname):
                self.directory_clicked(fname)
            else:
                self.open([fname])

    def directory_clicked(self, dirname):
        """Directory was just clicked"""
        pass

    #---- Drag
    def dragEnterEvent(self, event):
        """Drag and Drop - Enter event"""
        event.setAccepted(event.mimeData().hasFormat("text/plain"))

    def dragMoveEvent(self, event):
        """Drag and Drop - Move event"""
        if (event.mimeData().hasFormat("text/plain")):
            event.setDropAction(Qt.MoveAction)
            event.accept()
        else:
            event.ignore()

    def startDrag(self, dropActions):
        """Reimplement Qt Method - handle drag event"""
        data = QMimeData()
        data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
        drag = QDrag(self)
        drag.setMimeData(data)
        drag.exec_()

    #---- File/Directory actions
    def open(self, fnames=None):
        """Open files with the appropriate application"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            ext = osp.splitext(fname)[1]
            if osp.isfile(fname) and ext in self.valid_types:
                self.parent_widget.sig_open_file.emit(fname)
            else:
                self.open_outside_spyder([fname])

    def open_outside_spyder(self, fnames):
        """Open file outside Spyder with the appropriate application
        If this does not work, opening unknown file in Spyder, as text file"""
        for path in sorted(fnames):
            path = file_uri(path)
            ok = programs.start_file(path)
            if not ok:
                self.parent_widget.emit(SIGNAL("edit(QString)"), path)

    def open_terminal(self, fnames):
        """Open terminal"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_terminal(QString)"), path)

    def open_interpreter(self, fnames):
        """Open interpreter"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_interpreter(QString)"), path)

    def run(self, fnames=None):
        """Run Python scripts"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            self.parent_widget.emit(SIGNAL("run(QString)"), fname)

    def remove_tree(self, dirname):
        """Remove whole directory tree
        Reimplemented in project explorer widget"""
        shutil.rmtree(dirname, onerror=misc.onerror)

    def delete_file(self, fname, multiple, yes_to_all):
        """Delete file"""
        if multiple:
            buttons = QMessageBox.Yes|QMessageBox.YesAll| \
                      QMessageBox.No|QMessageBox.Cancel
        else:
            buttons = QMessageBox.Yes | QMessageBox.No
        if yes_to_all is None:
            answer = QMessageBox.warning(
                self, _("Delete"),
                _("Do you really want "
                  "to delete <b>%s</b>?") % osp.basename(fname), buttons)
            if answer == QMessageBox.No:
                return yes_to_all
            elif answer == QMessageBox.Cancel:
                return False
            elif answer == QMessageBox.YesAll:
                yes_to_all = True
        try:
            if osp.isfile(fname):
                misc.remove_file(fname)
                self.parent_widget.emit(SIGNAL("removed(QString)"), fname)
            else:
                self.remove_tree(fname)
                self.parent_widget.emit(SIGNAL("removed_tree(QString)"), fname)
            return yes_to_all
        except EnvironmentError, error:
            action_str = _('delete')
            QMessageBox.critical(
                self, _("Project Explorer"),
                _("<b>Unable to %s <i>%s</i></b>"
                  "<br><br>Error message:<br>%s") %
                (action_str, fname, unicode(error)))
        return False
Exemplo n.º 10
0
    sender = self.sender()
    self.statusBar().showMessage(sender.text() + " was pressed")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    # Splitter to show 2 views in same widget easily.
    splitter = QSplitter()
    # The model.
    model = QFileSystemModel()
    # You can setRootPath to any path.
    model.setReadOnly(True)
    # model.setRootPath("/Users/legal/Developpement/pc-sim/src/reports")
    model.setRootPath(QDir.currentPath())
    model.setNameFilters(["*.perf", "*.dat", "*.txt", "*.data"])
    model.setNameFilterDisables(False)

    # setDir.setNameFilters(filter)
    # tree.setRootIndex(model.index(QtCore.QDir.path(setDir), 0 ))

    # List of views.
    views = []

    # for ViewType in (QColumnView, QTreeView):
    # for ViewType in (QTreeView):

    # Create the view in the splitter.
    view = TreeView(splitter)
    view.setSelectionMode(QAbstractItemView.ExtendedSelection)

    # Set the model of the view.
Exemplo n.º 11
0
class DirView(QTreeView):
    """Base file/directory tree view"""

    def __init__(self, parent=None):
        super(DirView, self).__init__(parent)
        self.name_filters = None
        self.parent_widget = parent
        self.valid_types = None
        self.show_all = None
        self.menu = None
        self.common_actions = None
        self.__expanded_state = None
        self._to_be_loaded = None
        self.fsmodel = None
        self.setup_fs_model()
        self._scrollbar_positions = None

    # ---- Model
    def setup_fs_model(self):
        """Setup filesystem model"""
        filters = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot
        self.fsmodel = QFileSystemModel(self)
        self.fsmodel.setFilter(filters)
        self.fsmodel.setNameFilterDisables(False)

    def install_model(self):
        """Install filesystem model"""
        self.setModel(self.fsmodel)

    def setup_view(self):
        """Setup view"""
        self.install_model()
        self.connect(self.fsmodel, SIGNAL("directoryLoaded(QString)"), lambda: self.resizeColumnToContents(0))
        self.setAnimated(False)
        self.setSortingEnabled(True)
        self.sortByColumn(0, Qt.AscendingOrder)

    def set_name_filters(self, name_filters):
        """Set name filters"""
        self.name_filters = name_filters
        self.fsmodel.setNameFilters(name_filters)

    def set_show_all(self, state):
        """Toggle 'show all files' state"""
        if state:
            self.fsmodel.setNameFilters([])
        else:
            self.fsmodel.setNameFilters(self.name_filters)

    def get_filename(self, index):
        """Return filename associated with *index*"""
        if index:
            return osp.normpath(unicode(self.fsmodel.filePath(index)))

    def get_index(self, filename):
        """Return index associated with filename"""
        return self.fsmodel.index(filename)

    def get_selected_filenames(self):
        """Return selected filenames"""
        if self.selectionMode() == self.ExtendedSelection:
            return [self.get_filename(idx) for idx in self.selectedIndexes()]
        else:
            return [self.get_filename(self.currentIndex())]

    def get_dirname(self, index):
        """Return dirname associated with *index*"""
        fname = self.get_filename(index)
        if fname:
            if osp.isdir(fname):
                return fname
            else:
                return osp.dirname(fname)

    # ---- Tree view widget
    def setup(self, name_filters=["*.py", "*.pyw"], valid_types=(".py", ".pyw"), show_all=False):
        """Setup tree widget"""
        self.setup_view()

        self.set_name_filters(name_filters)
        self.valid_types = valid_types
        self.show_all = show_all

        # Setup context menu
        self.menu = QMenu(self)
        self.common_actions = self.setup_common_actions()

    # ---- Context menu
    def setup_common_actions(self):
        """Setup context menu common actions"""
        # Filters
        filters_action = create_action(
            self, _("Edit filename filters..."), None, get_icon("filter.png"), triggered=self.edit_filter
        )
        # Show all files
        all_action = create_action(self, _("Show all files"), toggled=self.toggle_all)
        all_action.setChecked(self.show_all)
        self.toggle_all(self.show_all)

        return [filters_action, all_action]

    def edit_filter(self):
        """Edit name filters"""
        filters, valid = QInputDialog.getText(
            self, _("Edit filename filters"), _("Name filters:"), QLineEdit.Normal, ", ".join(self.name_filters)
        )
        if valid:
            filters = [f.strip() for f in unicode(filters).split(",")]
            self.parent_widget.sig_option_changed.emit("name_filters", filters)
            self.set_name_filters(filters)

    def toggle_all(self, checked):
        """Toggle all files mode"""
        self.parent_widget.sig_option_changed.emit("show_all", checked)
        self.show_all = checked
        self.set_show_all(checked)

    def create_file_new_actions(self, fnames):
        """Return actions for submenu 'New...'"""
        if not fnames:
            return []
        new_file_act = create_action(
            self, _("File..."), icon="filenew.png", triggered=lambda: self.new_file(fnames[-1])
        )
        new_module_act = create_action(
            self, _("Module..."), icon="py.png", triggered=lambda: self.new_module(fnames[-1])
        )
        new_folder_act = create_action(
            self, _("Folder..."), icon="folder_new.png", triggered=lambda: self.new_folder(fnames[-1])
        )
        new_package_act = create_action(
            self,
            _("Package..."),
            icon=get_icon("package_collapsed.png"),
            triggered=lambda: self.new_package(fnames[-1]),
        )
        return [new_file_act, new_folder_act, None, new_module_act, new_package_act]

    def create_file_import_actions(self, fnames):
        """Return actions for submenu 'Import...'"""
        return []

    def create_file_manage_actions(self, fnames):
        """Return file management actions"""
        only_files = all([osp.isfile(_fn) for _fn in fnames])
        only_modules = all([osp.splitext(_fn)[1] in (".py", ".pyw", ".ipy") for _fn in fnames])
        only_valid = all([osp.splitext(_fn)[1] in self.valid_types for _fn in fnames])
        run_action = create_action(self, _("Run"), icon="run_small.png", triggered=self.run)
        edit_action = create_action(self, _("Edit"), icon="edit.png", triggered=self.clicked)
        move_action = create_action(self, _("Move..."), icon="move.png", triggered=self.move)
        delete_action = create_action(self, _("Delete..."), icon="delete.png", triggered=self.delete)
        rename_action = create_action(self, _("Rename..."), icon="rename.png", triggered=self.rename)
        open_action = create_action(self, _("Open"), triggered=self.open)

        actions = []
        if only_modules:
            actions.append(run_action)
        if only_valid and only_files:
            actions.append(edit_action)
        else:
            actions.append(open_action)
        actions += [delete_action, rename_action]
        basedir = fixpath(osp.dirname(fnames[0]))
        if all([fixpath(osp.dirname(_fn)) == basedir for _fn in fnames]):
            actions.append(move_action)
        actions += [None]

        # VCS support is quite limited for now, so we are enabling the VCS
        # related actions only when a single file/folder is selected:
        dirname = fnames[0] if osp.isdir(fnames[0]) else osp.dirname(fnames[0])
        if len(fnames) == 1 and vcs.is_vcs_repository(dirname):
            vcs_ci = create_action(
                self,
                _("Commit"),
                icon="vcs_commit.png",
                triggered=lambda fnames=[dirname]: self.vcs_command(fnames, tool="commit"),
            )
            vcs_log = create_action(
                self,
                _("Browse repository"),
                icon="vcs_browse.png",
                triggered=lambda fnames=[dirname]: self.vcs_command(fnames, tool="browse"),
            )
            actions += [None, vcs_ci, vcs_log]

        return actions

    def create_folder_manage_actions(self, fnames):
        """Return folder management actions"""
        actions = []
        if os.name == "nt":
            _title = _("Open command prompt here")
        else:
            _title = _("Open terminal here")
        action = create_action(
            self, _title, icon="cmdprompt.png", triggered=lambda fnames=fnames: self.open_terminal(fnames)
        )
        actions.append(action)
        _title = _("Open Python interpreter here")
        action = create_action(
            self, _title, icon="python.png", triggered=lambda fnames=fnames: self.open_interpreter(fnames)
        )
        actions.append(action)
        return actions

    def create_context_menu_actions(self):
        """Create context menu actions"""
        actions = []
        fnames = self.get_selected_filenames()
        new_actions = self.create_file_new_actions(fnames)
        if len(new_actions) > 1:
            # Creating a submenu only if there is more than one entry
            new_act_menu = QMenu(_("New"), self)
            add_actions(new_act_menu, new_actions)
            actions.append(new_act_menu)
        else:
            actions += new_actions
        import_actions = self.create_file_import_actions(fnames)
        if len(import_actions) > 1:
            # Creating a submenu only if there is more than one entry
            import_act_menu = QMenu(_("Import"), self)
            add_actions(import_act_menu, import_actions)
            actions.append(import_act_menu)
        else:
            actions += import_actions
        if actions:
            actions.append(None)
        if fnames:
            actions += self.create_file_manage_actions(fnames)
        if actions:
            actions.append(None)
        if fnames and all([osp.isdir(_fn) for _fn in fnames]):
            actions += self.create_folder_manage_actions(fnames)
        if actions:
            actions.append(None)
        actions += self.common_actions
        return actions

    def update_menu(self):
        """Update context menu"""
        self.menu.clear()
        add_actions(self.menu, self.create_context_menu_actions())

    # ---- Events
    def viewportEvent(self, event):
        """Reimplement Qt method"""

        # Prevent Qt from crashing or showing warnings like:
        # "QSortFilterProxyModel: index from wrong model passed to
        # mapFromSource", probably due to the fact that the file system model
        # is being built. See Issue 1250.
        #
        # This workaround was inspired by the following KDE bug:
        # https://bugs.kde.org/show_bug.cgi?id=172198
        #
        # Apparently, this is a bug from Qt itself.
        self.executeDelayedItemsLayout()

        return QTreeView.viewportEvent(self, event)

    def contextMenuEvent(self, event):
        """Override Qt method"""
        self.update_menu()
        self.menu.popup(event.globalPos())

    def keyPressEvent(self, event):
        """Reimplement Qt method"""
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.clicked()
        elif event.key() == Qt.Key_F2:
            self.rename()
        elif event.key() == Qt.Key_Delete:
            self.delete()
        else:
            QTreeView.keyPressEvent(self, event)

    def mouseDoubleClickEvent(self, event):
        """Reimplement Qt method"""
        QTreeView.mouseDoubleClickEvent(self, event)
        self.clicked()

    def clicked(self):
        """Selected item was double-clicked or enter/return was pressed"""
        fnames = self.get_selected_filenames()
        for fname in fnames:
            if osp.isdir(fname):
                self.directory_clicked(fname)
            else:
                self.open([fname])

    def directory_clicked(self, dirname):
        """Directory was just clicked"""
        pass

    # ---- Drag
    def dragEnterEvent(self, event):
        """Drag and Drop - Enter event"""
        event.setAccepted(event.mimeData().hasFormat("text/plain"))

    def dragMoveEvent(self, event):
        """Drag and Drop - Move event"""
        if event.mimeData().hasFormat("text/plain"):
            event.setDropAction(Qt.MoveAction)
            event.accept()
        else:
            event.ignore()

    def startDrag(self, dropActions):
        """Reimplement Qt Method - handle drag event"""
        data = QMimeData()
        data.setUrls([QUrl(fname) for fname in self.get_selected_filenames()])
        drag = QDrag(self)
        drag.setMimeData(data)
        drag.exec_()

    # ---- File/Directory actions
    def open(self, fnames=None):
        """Open files with the appropriate application"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            ext = osp.splitext(fname)[1]
            if osp.isfile(fname) and ext in self.valid_types:
                self.parent_widget.sig_open_file.emit(fname)
            else:
                self.open_outside_spyder([fname])

    def open_outside_spyder(self, fnames):
        """Open file outside Spyder with the appropriate application
        If this does not work, opening unknown file in Spyder, as text file"""
        for path in sorted(fnames):
            path = file_uri(path)
            ok = programs.start_file(path)
            if not ok:
                self.parent_widget.emit(SIGNAL("edit(QString)"), path)

    def open_terminal(self, fnames):
        """Open terminal"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_terminal(QString)"), path)

    def open_interpreter(self, fnames):
        """Open interpreter"""
        for path in sorted(fnames):
            self.parent_widget.emit(SIGNAL("open_interpreter(QString)"), path)

    def run(self, fnames=None):
        """Run Python scripts"""
        if fnames is None:
            fnames = self.get_selected_filenames()
        for fname in fnames:
            self.parent_widget.emit(SIGNAL("run(QString)"), fname)

    def remove_tree(self, dirname):
        """Remove whole directory tree
        Reimplemented in project explorer widget"""
        shutil.rmtree(dirname, onerror=misc.onerror)

    def delete_file(self, fname, multiple, yes_to_all):
        """Delete file"""
        if multiple:
            buttons = QMessageBox.Yes | QMessageBox.YesAll | QMessageBox.No | QMessageBox.Cancel
        else:
            buttons = QMessageBox.Yes | QMessageBox.No
        if yes_to_all is None:
            answer = QMessageBox.warning(
                self, _("Delete"), _("Do you really want " "to delete <b>%s</b>?") % osp.basename(fname), buttons
            )
            if answer == QMessageBox.No:
                return yes_to_all
            elif answer == QMessageBox.Cancel:
                return False
            elif answer == QMessageBox.YesAll:
                yes_to_all = True
        try:
            if osp.isfile(fname):
                misc.remove_file(fname)
                self.parent_widget.emit(SIGNAL("removed(QString)"), fname)
            else:
                self.remove_tree(fname)
                self.parent_widget.emit(SIGNAL("removed_tree(QString)"), fname)
            return yes_to_all
        except EnvironmentError, error:
            action_str = _("delete")
            QMessageBox.critical(
                self,
                _("Project Explorer"),
                _("<b>Unable to %s <i>%s</i></b>" "<br><br>Error message:<br>%s") % (action_str, fname, unicode(error)),
            )
        return False
Exemplo n.º 12
0
class Window(QMainWindow):

  def __init__(self):
    super(Window, self).__init__()

    central_widget = QWidget()

    self._current_path = None
    self._use_suffix = False

    self._file_model = QFileSystemModel()
    self._file_model.setNameFilters(['*.jpg', '*.png'])
    self._file_model.setNameFilterDisables(False)
    self._file_model.setRootPath(QDir.rootPath())

    self._file_selection_model = QItemSelectionModel(self._file_model)
    self._file_selection_model.currentChanged.connect(self._on_current_file_changed)

    self._file_tree = QTreeView(parent=self)
    self._file_tree.collapsed.connect(self._on_tree_expanded_collapsed)
    self._file_tree.expanded.connect(self._on_tree_expanded_collapsed)
    self._file_tree.setModel(self._file_model)
    self._file_tree.setSelectionModel(self._file_selection_model)
    self._file_tree.setColumnHidden(1, True)
    self._file_tree.setColumnHidden(2, True)
    self._file_tree.setColumnHidden(3, True)
    self._file_tree.header().hide()

    self._viewer = Viewer(Loader(24))

    self._splitter = QSplitter();
    self._splitter.addWidget(self._file_tree)
    self._splitter.addWidget(self._viewer)
    self._splitter.setStretchFactor(0, 0)
    self._splitter.setStretchFactor(1, 1)
    self._splitter.setCollapsible(0, False)

    self._layout = QGridLayout()
    self._layout.addWidget(self._splitter)
    self._switch_to_normal()
    central_widget.setLayout(self._layout)

    self._file_tree.installEventFilter(self);

    self.resize(800, 600)
    self.setWindowTitle('pyQtures')
    self.setCentralWidget(central_widget)
    self.show()

  def eventFilter(self, widget, event):
    if event.type() == QEvent.KeyPress:
      if event.key() == Qt.Key_Tab:
        self._toggle_path_suffix()
        return True
    return QMainWindow.eventFilter(self, widget, event)

  def _toggle_path_suffix(self):
    self._use_suffix = not self._use_suffix
    self._update_path()

  def _switch_to_fullscreen(self):
    self._splitter.widget(0).hide()
    self._layout.setMargin(0)
    self.showFullScreen()

  def _switch_to_normal(self):
    self._splitter.widget(0).show()
    self._layout.setMargin(4)
    self.showNormal()

  def keyPressEvent(self, key_event):  # Signal handler.
    key = key_event.key()
    if self.isFullScreen():
      self._full_screen_key_handler(key)
    else:
      self._normal_key_handler(key)

  def _full_screen_key_handler(self, key):
    if Qt.Key_Escape == key:
      self._switch_to_normal()
    elif Qt.Key_Return == key:
      self._switch_to_normal()
    elif Qt.Key_Up == key:
      self._go_to_sibling_image(-1)
    elif Qt.Key_Down == key:
      self._go_to_sibling_image(1)
    elif Qt.Key_Tab == key:
      self._toggle_path_suffix()

  def _go_to_sibling_image(self, offset):
    current = self._file_selection_model.currentIndex()
    nxt = current.sibling(current.row() + offset, current.column())
    if (nxt.parent() != current.parent()):
      return
    # TODO(eustas): Iterate through dirs?
    self._file_selection_model.setCurrentIndex(nxt, QItemSelectionModel.SelectCurrent)

  def _normal_key_handler(self, key):
    if Qt.Key_Escape == key:
      QCoreApplication.instance().quit()
    elif Qt.Key_Return == key:
      self._switch_to_fullscreen()

  def _on_current_file_changed(self, new_current):
    new_path = self._file_model.filePath(new_current)
    if not self._current_path == new_path:
        self._current_path = new_path
        self._update_path()

  def _update_path(self):
    if not self._use_suffix:
      self._viewer.set_path(self._current_path)
      return

    self._viewer.reset_path()
    if not self._current_path:
      return

    selected_file = QFileInfo(self._current_path)
    if not selected_file.exists():
      return

    selected_dir = selected_file.absoluteDir()
    file_name = selected_file.fileName()
    if not selected_dir.exists():
      return

    if not selected_dir.cd('converted'):
      return

    suffixed_path = selected_dir.absoluteFilePath(file_name)
    self._viewer.set_path(suffixed_path)

  def _on_tree_expanded_collapsed(self, unused_index):
    QTimer.singleShot(1, lambda: self._file_tree.resizeColumnToContents(0))
Exemplo n.º 13
0
class SourceFileTreeWidget(QWidget):
    """ Config window"""
    def __init__(self, parent):
        super(SourceFileTreeWidget, self).__init__(parent)
        self.ui = Ui_SourceFileTreeWidget()
        self.ui.setupUi(self)
        self.file_model = QFileSystemModel()
        #self.file_model.setFilter(QDir.AllEntries | QDir.NoDot)
        self.set_filter()
        self.ui.tree.setModel(self.file_model)
        self.ui.tree.resizeColumnToContents(0)
        self.ui.custom_root.setText(QDir.currentPath())
        self.set_root()

        header = self.ui.tree.header()
        header.setResizeMode(QHeaderView.ResizeToContents)
        #header.setStretchLastSection(True)
        #header.setSortIndicator(0, Qt.AscendingOrder)
        #header.setSortIndicatorShown(True)
        #header.setClickable(True)
        self.connect(self.ui.tree, QtCore.SIGNAL('doubleClicked(QModelIndex)'), self.open_file)
        self.connect(self.ui.ok_filter, QtCore.SIGNAL('clicked()'), self.set_filter)
        self.connect(self.ui.custom_filter, QtCore.SIGNAL('returnPressed()'), self.set_filter)
        self.connect(self.ui.ok_root, QtCore.SIGNAL('clicked()'), self.set_root)
        self.connect(self.ui.custom_root, QtCore.SIGNAL('returnPressed()'), self.set_root)
        self.open_file_signal = None

    def set_open_file_signal(self, signal):
        """ callback to signal file opening """
        self.open_file_signal = signal

    def set_root(self, root=None, use_common_prefix=True):
        """ set the root path of the widget """
        curr = str(self.ui.custom_root.text())
        if not root:
            use_common_prefix = False # input text box will override it.
            root = self.ui.custom_root.text()
        else:
            self.ui.custom_root.setText(root)
        idx = self.file_model.index(root)
        self.ui.tree.setExpanded(idx, True)
        if use_common_prefix and curr == os.path.commonprefix([root, curr]):
            return

        idx = self.file_model.setRootPath(root)
        if not idx.isValid():
            logging.warn('Invalid path')
            return
        self.ui.tree.setRootIndex(idx)
        self.ui.tree.setExpanded(idx, True)

    def set_filter(self):
        """ set filter by extension """
        filters = str(self.ui.custom_filter.text()).split(';')
        self.file_model.setNameFilters(filters)
        self.file_model.setNameFilterDisables(False)

    def open_file(self, idx):
        """ emit file opening signal """
        if self.file_model.isDir(idx):
            return
        fullpath = self.file_model.filePath(idx)
        if self.open_file_signal:
            self.open_file_signal.emit(str(fullpath), 0)

    def set_file_selected(self, tab_idx):
        """ slot to associate the file in active tab """
        filename = self.sender().tabToolTip(tab_idx)
        idx = self.file_model.index(filename)
        if idx.isValid():
            self.ui.tree.selectionModel().select(idx, QItemSelectionModel.ClearAndSelect)