... other code ... class FileTableWidget(QTableWidget): ... other code ... def…
- User
... other code ... class FileTableWidget(QTableWidget): ... other code ... def handle_item_double_click(self, item): if item.column() == 0: self.main_window.handle_item_double_click(item)
... other code ...class DualPanelFileManager(QMainWindow): ... other code ... def load_directory(self, table, path, update_history=True, prev_dir=None): # Stop any existing lazy loading for this table if not getattr(self, "_bw_internal_call", False): self._bw_active = False self._bw_root = None
if hasattr(table, 'stop_lazy_loading'): table.stop_lazy_loading() # Save scroll and selection only if reloading same path same_path = table.property("currentPath") == path scroll = table.verticalScrollBar().value() if same_path else 0 selected_path = next((item.data(Qt.UserRole) for item in table.selectedItems()), None) if same_path else None # Clear and setup table table.clearContents() table.setRowCount(0) table.setSortingEnabled(False) table.setProperty("currentPath", path) current_folder_name = os.path.basename(os.path.normpath(path)) or path table.setProperty("currentFolderName", current_folder_name) # Update panel, tabs, and history briefly panel = self.get_panel_from_table(table) if panel: self.update_path_bar(panel['path_bar'], path, table) if update_history: current_path = panel['history'][panel['history_index']] if panel['history'] else None # Only do anything if the new path is different from the current one if path != current_path: if path in panel['history']: existing_index = panel['history'].index(path) if existing_index > panel['history_index']: panel['history_index'] = existing_index elif existing_index < panel['history_index']: panel['history'] = panel['history'][:panel['history_index'] + 1] panel['history'].append(path) panel['history_index'] += 1 else: panel['history'] = panel['history'][:panel['history_index'] + 1] panel['history'].append(path) panel['history_index'] += 1 current_index = panel['parent'].tabs.indexOf(panel['widget']) if current_index != -1 and panel.get('last_path') != path: short_name = current_folder_name[:MFNL] + "…" if len(current_folder_name) > MFNL else current_folder_name panel.update({'tab_name': short_name, 'last_path': path, 'user_set_name': False}) panel['parent'].tabs.setTabText(current_index, short_name) panel['parent'].tabs.tabBar().setTabToolTip(current_index, path) self.update_navigation_buttons() # Populate entries try: entries = self.get_directory_entries(path) backup_states = self.load_backup_states(path) if not self.show_excluded_items: entries = [e for e in entries if not (backup_states.get(e[0], '').startswith('X') and e[0] != '..')] table.setRowCount(len(entries)) # Use the modified populate_table_row (no change needed here) for row, entry in enumerate(entries): self.populate_table_row(table, row, entry, backup_states) # Start lazy loading worker worker = LazyLoadWorker(table, entries, backup_states, self.icon_extractor, self.show_file_icons, self) # Connect signals worker.icon_loaded.connect(lambda row, icon: self.update_table_icon(table, row, icon)) worker.tag_loaded.connect(lambda row, text, tooltip, color: self.update_table_tag(table, row, text, tooltip, color)) table.current_worker = worker worker.start() except (PermissionError, FileNotFoundError, OSError) as e: table.setRowCount(1) msg = ("Location unavailable" if isinstance(e, FileNotFoundError) else "Location unavailable") msg_item = FileTableWidgetItem(msg) msg_item.setForeground(QColor("red")) font = QFont(); font.setItalic(True); msg_item.setFont(font) msg_item.setFlags(Qt.ItemIsEnabled) msg_item.setTextAlignment(Qt.AlignCenter) table.setItem(0, 0, msg_item) table.setSpan(0, 0, 1, table.columnCount()) table.setSortingEnabled(True) table.sortItems(table.horizontalHeader().sortIndicatorSection(), table.horizontalHeader().sortIndicatorOrder()) # Restore scroll and selection def restore(): if prev_dir: matching_items = table.findItems(prev_dir, Qt.MatchExactly) if matching_items: table.setCurrentItem(matching_items[0]) table.selectRow(matching_items[0].row()) table.scrollToItem(matching_items[0], QTableWidget.PositionAtCenter) elif same_path: table.verticalScrollBar().setValue(scroll) if selected_path: for row in range(table.rowCount()): item = table.item(row, 0) if item and item.data(Qt.UserRole) == selected_path: table.selectRow(row) break else: row = 1 if table.rowCount() > 1 else 0 table.selectRow(row) table.verticalScrollBar().setValue(0) # table.setFocus() QTimer.singleShot(0, restore) ... other code ... def get_directory_entries(path): entries = [] try: with os.scandir(path) as it: for entry in it: is_dir = entry.is_dir() entries.append((entry.name, is_dir, entry.path, entry.stat())) except PermissionError: QMessageBox.warning(None, "Access Denied", f"You do not have permission to access '{path}'.") return [] entries.sort(key=lambda x: (not x[1], x[0].lower())) if os.path.dirname(path) != path: entries.insert(0, ("..", True, os.path.dirname(path), None)) return entries ... other code ... def navigate_to_neighbor_folder(self, direction): """Navigate to the previous (-1) or next (1) sibling folder.""" if not self.active_table: return current_path = self.active_table.property("currentPath") parent_path = os.path.dirname(current_path) # Can't navigate siblings at root level if not parent_path or parent_path == current_path: return try: # Get current sort column and order sort_column = self.active_table.horizontalHeader().sortIndicatorSection() sort_order = self.active_table.horizontalHeader().sortIndicatorOrder() # Get all subdirectories in parent with their metadata entries = [] for entry in os.scandir(parent_path): if entry.is_dir() and not entry.name.startswith('.'): stat = entry.stat() entries.append({ 'name': entry.name, 'size': 0, # Folders typically show as 0 or <DIR> 'date': stat.st_mtime, 'path': os.path.join(parent_path, entry.name) }) # Sort based on current table sorting if sort_column == 0: # Name column entries.sort(key=lambda x: x['name'].lower(), reverse=(sort_order == Qt.DescendingOrder)) elif sort_column == 1: # Size column entries.sort(key=lambda x: x['size'], reverse=(sort_order == Qt.DescendingOrder)) elif sort_column == 2: # Date column entries.sort(key=lambda x: x['date'], reverse=(sort_order == Qt.DescendingOrder)) # Find current folder's position current_folder = os.path.basename(current_path) folder_names = [e['name'] for e in entries] if current_folder not in folder_names: return current_index = folder_names.index(current_folder) new_index = current_index + direction # Check bounds if 0 <= new_index < len(entries): self.load_directory(self.active_table, entries[new_index]['path'], update_history=False) except (PermissionError, FileNotFoundError, OSError): pass # ─────────────────────────────────────────────────────────────── # Branch-walk aware sibling/descendant navigation # ─────────────────────────────────────────────────────────────── ... other code ...
help me fix navigate_to_neighbor_folder do not skipping "no permission" folders like "system vollume infromation" etc
Assistant
Looking at your code, I can see that
navigate_to_neighbor_folderusesos.scandir()which can raisePermissionErrorwhen trying to check if an entry is a directory. The issue is that when you hit a permission-denied folder, the exception stops the entire directory listing process.Here's the fixed version that handles permission errors for individual entries:
def navigate_to_neighbor_folder(self, direction): """Navigate to the previous (-1) or next (1) sibling folder.""" if not self.active_table: return current_path = self.active_table.property("currentPath") parent_path = os.path.dirname(current_path) # Can't navigate siblings at root level if not parent_path or parent_path == current_path: return try: # Get current sort column and order sort_column = self.active_table.horizontalHeader().sortIndicatorSection() sort_order = self.active_table.horizontalHeader().sortIndicatorOrder() # Get all subdirectories in parent with their metadata entries = [] for entry in os.scandir(parent_path): try: # Try to check if it's a directory and get stats if entry.is_dir() and not entry.name.startswith('.'): try: stat = entry.stat() entries.append({ 'name': entry.name, 'size': 0, # Folders typically show as 0 or <DIR> 'date': stat.st_mtime, 'path': os.path.join(parent_path, entry.name) }) except (PermissionError, OSError): # If we can't stat it, add it with default values entries.append({ 'name': entry.name, 'size': 0, 'date': 0, # Default timestamp 'path': os.path.join(parent_path, entry.name) }) except (PermissionError, OSError): # Skip entries we can't even check if they're directories continue # Sort based on current table sorting if sort_column == 0: # Name column entries.sort(key=lambda x: x['name'].lower(), reverse=(sort_order == Qt.DescendingOrder)) elif sort_column == 1: # Size column entries.sort(key=lambda x: x['size'], reverse=(sort_order == Qt.DescendingOrder)) elif sort_column == 2: # Date column entries.sort(key=lambda x: x['date'], reverse=(sort_order == Qt.DescendingOrder)) # Find current folder's position current_folder = os.path.basename(current_path) folder_names = [e['name'] for e in entries] if current_folder not in folder_names: return current_index = folder_names.index(current_folder) new_index = current_index + direction # Check bounds if 0 <= new_index < len(entries): self.load_directory(self.active_table, entries[new_index]['path'], update_history=False) except (PermissionError, FileNotFoundError, OSError): passThe key changes are:
-
Wrapped
entry.is_dir()in a try-except block: This catchesPermissionErrorwhen trying to check if an entry is a directory (like "System Volume Information"). -
Nested try-except for
entry.stat(): Even if we can determine something is a directory, we might not have permission to stat it. In this case, we still include it in the list but with default values. -
Continue on error: Instead of stopping the entire process, we skip individual problematic entries and continue with the rest.
This way, folders like "System Volume Information" won't break the navigation - they'll either be included with default values (if we can at least determine they're directories) or skipped entirely (if we can't even check their type), but other accessible folders will still be navigable.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.