| 117 | } |
| 118 | |
| 119 | QString StringUtils::truncateUrlHumanFriendly(QUrl& url, int max_len, bool hard_limit) |
| 120 | { |
| 121 | auto display_options = QUrl::RemoveUserInfo | QUrl::RemoveFragment | QUrl::NormalizePathSegments; |
| 122 | auto str_url = url.toDisplayString(display_options); |
| 123 | |
| 124 | if (str_url.length() <= max_len) |
| 125 | return str_url; |
| 126 | |
| 127 | auto url_path_parts = url.path().split('/'); |
| 128 | QString last_path_segment = url_path_parts.takeLast(); |
| 129 | |
| 130 | if (url_path_parts.size() >= 1 && url_path_parts.first().isEmpty()) |
| 131 | url_path_parts.removeFirst(); // drop empty first segment (from leading / ) |
| 132 | |
| 133 | if (url_path_parts.size() >= 1) |
| 134 | url_path_parts.removeLast(); // drop the next to last path segment |
| 135 | |
| 136 | auto url_template = QStringLiteral("%1://%2/%3%4"); |
| 137 | |
| 138 | auto url_compact = url_path_parts.isEmpty() |
| 139 | ? url_template.arg(url.scheme(), url.host(), QStringList({ "...", last_path_segment }).join('/'), url.query()) |
| 140 | : url_template.arg(url.scheme(), url.host(), |
| 141 | QStringList({ url_path_parts.join('/'), "...", last_path_segment }).join('/'), url.query()); |
| 142 | |
| 143 | // remove url parts one by one if it's still too long |
| 144 | while (url_compact.length() > max_len && url_path_parts.size() >= 1) { |
| 145 | url_path_parts.removeLast(); // drop the next to last path segment |
| 146 | url_compact = url_path_parts.isEmpty() |
| 147 | ? url_template.arg(url.scheme(), url.host(), QStringList({ "...", last_path_segment }).join('/'), url.query()) |
| 148 | : url_template.arg(url.scheme(), url.host(), |
| 149 | QStringList({ url_path_parts.join('/'), "...", last_path_segment }).join('/'), url.query()); |
| 150 | } |
| 151 | |
| 152 | if ((url_compact.length() >= max_len) && hard_limit) { |
| 153 | // still too long, truncate normally |
| 154 | url_compact = QString(str_url); |
| 155 | auto to_remove = url_compact.length() - max_len + 3; |
| 156 | url_compact.remove(url_compact.length() - to_remove - 1, to_remove); |
| 157 | url_compact.append("..."); |
| 158 | } |
| 159 | |
| 160 | return url_compact; |
| 161 | } |
| 162 | |
| 163 | static const QStringList s_units_si{ "KB", "MB", "GB", "TB" }; |
| 164 | static const QStringList s_units_kibi{ "KiB", "MiB", "GiB", "TiB" }; |