Add '--quiet' comand line option to suppress some output
[ncmpcpp.git] / src / utility / wide_string.cpp
blob381f2f99e5d31a26e09a61f824e200879b50f2b7
1 /***************************************************************************
2 * Copyright (C) 2008-2017 by Andrzej Rybczak *
3 * electricityispower@gmail.com *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include <cassert>
22 #include "utility/wide_string.h"
24 size_t wideLength(const std::wstring &ws)
26 size_t result = 0;
27 for (const auto &wc : ws)
29 int len = wcwidth(wc);
30 if (len < 0)
31 ++result;
32 else
33 result += len;
35 return result;
38 void wideCut(std::wstring &ws, size_t max_length)
40 size_t i = 0;
41 int remained_len = max_length;
42 for (; i < ws.length(); ++i)
44 remained_len -= std::max(wcwidth(ws[i]), 1);
45 if (remained_len < 0)
47 ws.resize(i);
48 break;
53 std::wstring wideShorten(const std::wstring &ws, size_t max_length)
55 std::wstring result;
56 if (wideLength(ws) > max_length)
58 const size_t half_max = max_length/2 - 1;
59 size_t len = 0;
60 // get beginning of string
61 for (auto it = ws.begin(); it != ws.end(); ++it)
63 len += wcwidth(*it);
64 if (len > half_max)
65 break;
66 result += *it;
68 len = 0;
69 std::wstring end;
70 // get end of string in reverse order
71 for (auto it = ws.rbegin(); it != ws.rend(); ++it)
73 len += wcwidth(*it);
74 if (len > half_max)
75 break;
76 end += *it;
78 // apply end of string to its beginning
79 result += L"..";
80 result.append(end.rbegin(), end.rend());
82 else
83 result = ws;
84 return result;