1use crate::config::Config;
2use crate::file_entry::{DateTimePart, DateTimePartAlignment, FileEntry, FileType};
3use crate::sort::{SortOptions, sort_entries};
4use colored::Colorize;
5use unicode_width::UnicodeWidthStr;
6
7pub fn format_long(mut entries: Vec<FileEntry>, config: &Config, sort: SortOptions) {
8 sort_entries(&mut entries, sort);
9
10 print_long_entries(&entries, config, "");
11}
12
13pub fn print_long_entries(entries: &[FileEntry], config: &Config, prefix: &str) {
14 if entries.is_empty() {
15 return;
16 }
17
18 let fields = &config.display.long_format_fields;
19 let widths = calculate_column_widths(entries, fields, config);
20 print_long_entries_with_widths(entries, config, prefix, fields, &widths);
21}
22
23pub fn calculate_column_widths(
24 entries: &[FileEntry],
25 fields: &[String],
26 config: &Config,
27) -> std::collections::HashMap<String, usize> {
28 let mut max_widths: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
29 let modified_values = format_modified_entries(entries, &config.display.datetime_format);
30
31 for field in fields {
32 let width = match field.as_str() {
33 "nlink" => entries
34 .iter()
35 .map(|e| e.nlink.to_string().len())
36 .max()
37 .unwrap_or(0),
38 "owner" => entries.iter().map(|e| e.owner.len()).max().unwrap_or(0),
39 "group" => entries.iter().map(|e| e.group.len()).max().unwrap_or(0),
40 "size" => entries
41 .iter()
42 .map(|e| e.format_size().len())
43 .max()
44 .unwrap_or(0),
45 "modified" => modified_values
46 .iter()
47 .map(|value| UnicodeWidthStr::width(value.as_str()))
48 .max()
49 .unwrap_or(0),
50 "icon" => entries
51 .iter()
52 .map(|e| UnicodeWidthStr::width(e.get_icon_custom(&config.icons).as_str()))
53 .max()
54 .unwrap_or(0),
55 "filename" => entries
56 .iter()
57 .map(|e| UnicodeWidthStr::width(e.path.to_string_lossy().as_ref()))
58 .max()
59 .unwrap_or(0),
60 "permissions" => entries
61 .iter()
62 .map(|e| e.format_permissions().len())
63 .max()
64 .unwrap_or(0),
65 _ => 0,
66 };
67 let title_width = if config.display.long_format_titles {
68 UnicodeWidthStr::width(column_title(field))
69 } else {
70 0
71 };
72 max_widths.insert(field.clone(), width.max(title_width));
73 }
74
75 max_widths
76}
77
78pub fn calculate_column_widths_with_filename_prefixes(
79 entries: &[FileEntry],
80 filename_prefixes: &[String],
81 fields: &[String],
82 config: &Config,
83) -> std::collections::HashMap<String, usize> {
84 let mut entries_with_prefixes = entries.to_vec();
85
86 for (entry, filename_prefix) in entries_with_prefixes.iter_mut().zip(filename_prefixes) {
87 entry.path = format!("{filename_prefix}{}", entry.path.to_string_lossy()).into();
88 }
89
90 calculate_column_widths(&entries_with_prefixes, fields, config)
91}
92
93pub fn print_long_entries_with_widths(
94 entries: &[FileEntry],
95 config: &Config,
96 prefix: &str,
97 fields: &[String],
98 widths: &std::collections::HashMap<String, usize>,
99) {
100 if config.display.long_format_titles {
101 print_long_titles(config, prefix, fields, widths);
102 }
103 print_long_entries_with_optional_filename_prefixes(
104 entries, config, prefix, fields, widths, None,
105 );
106}
107
108pub fn print_long_entries_with_filename_prefixes(
109 entries: &[FileEntry],
110 filename_prefixes: &[String],
111 config: &Config,
112 fields: &[String],
113 widths: &std::collections::HashMap<String, usize>,
114) {
115 if config.display.long_format_titles {
116 print_long_titles(config, "", fields, widths);
117 }
118 print_long_entries_with_optional_filename_prefixes(
119 entries,
120 config,
121 "",
122 fields,
123 widths,
124 Some(filename_prefixes),
125 );
126}
127
128fn print_long_entries_with_optional_filename_prefixes(
129 entries: &[FileEntry],
130 config: &Config,
131 prefix: &str,
132 fields: &[String],
133 widths: &std::collections::HashMap<String, usize>,
134 filename_prefixes: Option<&[String]>,
135) {
136 let modified_values = format_modified_entries(entries, &config.display.datetime_format);
137
138 for (entry_index, entry) in entries.iter().enumerate() {
140 let mut output_parts: Vec<String> = Vec::new();
141
142 for (idx, field) in fields.iter().enumerate() {
143 let part = match field.as_str() {
144 "permissions" => {
145 let width = widths.get("permissions").copied().unwrap_or(0);
146 let permissions = entry.format_permissions();
147 if idx < fields.len() - 1 {
148 pad_to_display_width(permissions, width)
149 } else {
150 permissions
151 }
152 }
153 "nlink" => {
154 let width = widths.get("nlink").copied().unwrap_or(0);
155 format!("{:>width$}", entry.nlink.to_string(), width = width)
156 }
157 "owner" => {
158 let width = widths.get("owner").copied().unwrap_or(0);
159 format!("{:<width$}", entry.owner, width = width)
160 }
161 "group" => {
162 let width = widths.get("group").copied().unwrap_or(0);
163 format!("{:<width$}", entry.group, width = width)
164 }
165 "size" => {
166 let width = widths.get("size").copied().unwrap_or(0);
167 format!("{:>width$}", entry.format_size(), width = width)
168 }
169 "modified" => {
170 let width = widths.get("modified").copied().unwrap_or(0);
171 let modified = &modified_values[entry_index];
172 if idx < fields.len() - 1 {
173 pad_to_display_width(modified.to_string(), width)
174 } else {
175 modified.to_string()
176 }
177 }
178 "icon" => {
179 let icon = entry.get_icon_custom(&config.icons);
180 let icon_color = entry.get_icon_color(&config.icons.colors);
181 let width = widths.get("icon").copied().unwrap_or(0);
182 let padded = if idx < fields.len() - 1 {
183 pad_to_display_width(icon, width)
184 } else {
185 icon
186 };
187 format!("{}", padded.color(icon_color))
188 }
189 "filename" => {
190 let filename_str = entry.path.to_string_lossy().to_string();
191 let width = widths.get("filename").copied().unwrap_or(0);
192 let filename_prefix = filename_prefixes
193 .and_then(|prefixes| prefixes.get(entry_index))
194 .map(String::as_str)
195 .unwrap_or("");
196
197 let padding = if idx < fields.len() - 1 {
198 width.saturating_sub(
199 UnicodeWidthStr::width(filename_prefix)
200 + UnicodeWidthStr::width(filename_str.as_str()),
201 )
202 } else {
203 0
204 };
205 let padded = format!("{filename_str}{}", " ".repeat(padding));
206
207 let filename_colored = match entry.get_file_type() {
208 FileType::Directory | FileType::Executable => {
209 padded.color(entry.get_color(&config.colors)).bold()
210 }
211 FileType::RegularFile => padded.color(entry.get_color(&config.colors)),
212 };
213 format!("{filename_prefix}{filename_colored}")
214 }
215 _ => String::new(),
216 };
217 output_parts.push(part);
218 }
219
220 let visible_parts: Vec<&str> = output_parts
221 .iter()
222 .map(|part| part.as_str())
223 .filter(|part| !part.is_empty())
224 .collect();
225 println!("{}{}", prefix, visible_parts.join(" "));
226 }
227}
228
229fn format_modified_entries(entries: &[FileEntry], datetime_format: &str) -> Vec<String> {
230 let parts: Vec<Vec<DateTimePart>> = entries
231 .iter()
232 .map(|entry| entry.format_modified_parts(datetime_format))
233 .collect();
234 let mut widths = vec![0; parts.iter().map(Vec::len).max().unwrap_or(0)];
235
236 for entry_parts in &parts {
237 for (index, part) in entry_parts.iter().enumerate() {
238 if part.alignment == DateTimePartAlignment::None {
239 continue;
240 }
241
242 let width = UnicodeWidthStr::width(part.value.as_str());
243 widths[index] = widths[index].max(width);
244 }
245 }
246
247 parts
248 .into_iter()
249 .map(|entry_parts| {
250 entry_parts
251 .iter()
252 .enumerate()
253 .map(|(index, part)| format_datetime_part(part, widths[index]))
254 .collect()
255 })
256 .collect()
257}
258
259fn format_datetime_part(part: &DateTimePart, width: usize) -> String {
260 match part.alignment {
261 DateTimePartAlignment::Left => pad_to_display_width(part.value.clone(), width),
262 DateTimePartAlignment::Right => format!(
263 "{}{}",
264 " ".repeat(width.saturating_sub(UnicodeWidthStr::width(part.value.as_str()))),
265 part.value
266 ),
267 DateTimePartAlignment::None => part.value.clone(),
268 }
269}
270
271fn print_long_titles(
272 config: &Config,
273 prefix: &str,
274 fields: &[String],
275 widths: &std::collections::HashMap<String, usize>,
276) {
277 let titles: Vec<String> = fields
278 .iter()
279 .enumerate()
280 .map(|(index, field)| {
281 let title = column_title(field);
282 let width = widths.get(field).copied().unwrap_or(0);
283 let padded = if index < fields.len() - 1 {
284 pad_to_display_width(title.to_string(), width)
285 } else {
286 title.to_string()
287 };
288
289 format!(
290 "{}",
291 padded.color(config.display.get_long_format_title_color())
292 )
293 })
294 .collect();
295
296 println!("{}{}", prefix, titles.join(" "));
297}
298
299fn column_title(field: &str) -> &str {
300 match field {
301 "permissions" => "Permissions",
302 "nlink" => "Links",
303 "owner" => "Owner",
304 "group" => "Group",
305 "size" => "Size",
306 "modified" => "Modified",
307 "icon" => "Icon",
308 "filename" => "Name",
309 _ => field,
310 }
311}
312
313fn pad_to_display_width(value: String, width: usize) -> String {
314 let padding = width.saturating_sub(UnicodeWidthStr::width(value.as_str()));
315 format!("{value}{}", " ".repeat(padding))
316}