summaryrefslogtreecommitdiff
path: root/shared/util.cpp
blob: ab0b5a44fc24b29f57ab2702a3d0277a0b1f98a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// **************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: http://www.gnu.org/licenses/gpl.html       *
// * Copyright (C) 2008-2011 ZenJu (zhnmju123 AT gmx.de)                    *
// **************************************************************************
//
#include "util.h"
#include <wx/scrolwin.h>
#include <wx/textctrl.h>
#include <wx/combobox.h>
#include <wx/filepicker.h>
#include "i18n.h"
#include "file_handling.h"
#include "string_conv.h"
#include <stdexcept>
#include "last_error.h"
#include "check_exist.h"
#include "assert_static.h"
#include "system_constants.h"
#include "global_func.h"


#ifdef FFS_WIN
#include <wx/msw/wrapwin.h> //includes "windows.h"
#endif

wxString zen::extractJobName(const wxString& configFilename)
{
    using namespace common;

    const wxString shortName = configFilename.AfterLast(FILE_NAME_SEPARATOR); //returns the whole string if seperator not found
    const wxString jobName = shortName.BeforeLast(wxChar('.')); //returns empty string if seperator not found
    return jobName.IsEmpty() ? shortName : jobName;
}


wxString zen::formatFilesizeToShortString(zen::UInt64 size)
{
    if (to<zen::Int64>(size) < 0) return _("Error");

    if (size <= 999U)
    {
        wxString output = _P("1 Byte", "%x Bytes", to<int>(size));
        output.Replace(wxT("%x"), zen::toStringSep(size)); //no decimal places in case of bytes
        return output;
    }
    else
    {
        double filesize = to<double>(size);

        filesize /= 1024;
        wxString output = _("%x KB");
        if (filesize > 999)
        {
            filesize /= 1024;
            output = _("%x MB");
            if (filesize > 999)
            {
                filesize /= 1024;
                output = _("%x GB");
                if (filesize > 999)
                {
                    filesize /= 1024;
                    output = _("%x TB");
                    if (filesize > 999)
                    {
                        filesize /= 1024;
                        output = _("%x PB");
                    }
                }
            }
        }
        //print just three significant digits: 0,01 | 0,11 | 1,11 | 11,1 | 111
        const size_t leadDigitCount = common::getDigitCount(static_cast<size_t>(filesize)); //number of digits before decimal point
        if (leadDigitCount == 0 || leadDigitCount > 3)
            return _("Error");

        output.Replace(wxT("%x"), wxString::Format(wxT("%.*f"), static_cast<int>(3 - leadDigitCount), filesize));
        return output;
    }
}


wxString zen::formatPercentage(zen::Int64 dividend, zen::Int64 divisor)
{
    const double ratio = divisor != 0 ? to<double>(dividend) * 100.0 / to<double>(divisor) : 0;
    wxString output = _("%x%");
    output.Replace(wxT("%x"), wxString::Format(wxT("%3.2f"), ratio), false);
    return output;
}


wxString ffs_Impl::includeNumberSeparator(const wxString& number)
{
    wxString output(number);
    for (size_t i = output.size(); i > 3; i -= 3)
        output.insert(i - 3, zen::getThousandsSeparator());

    return output;
}


void zen::scrollToBottom(wxScrolledWindow* scrWindow)
{
    int height = 0;
    scrWindow->GetClientSize(NULL, &height);

    int pixelPerLine = 0;
    scrWindow->GetScrollPixelsPerUnit(NULL, &pixelPerLine);

    if (height > 0 && pixelPerLine > 0)
    {
        const int scrollLinesTotal    = scrWindow->GetScrollLines(wxVERTICAL);
        const int scrollLinesOnScreen = height / pixelPerLine;
        const int scrollPosBottom     = scrollLinesTotal - scrollLinesOnScreen;

        if (0 <= scrollPosBottom)
            scrWindow->Scroll(0, scrollPosBottom);
    }
}


namespace
{
#ifdef FFS_WIN
bool isVistaOrLater()
{
    OSVERSIONINFO osvi = {};
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

    //symbolic links are supported starting with Vista
    if (::GetVersionEx(&osvi))
        return osvi.dwMajorVersion > 5; //XP has majorVersion == 5, minorVersion == 1; Vista majorVersion == 6, dwMinorVersion == 0
    //overview: http://msdn.microsoft.com/en-us/library/ms724834(VS.85).aspx
    return false;
}
#endif
}


wxString zen::utcTimeToLocalString(zen::Int64 utcTime)
{
#ifdef FFS_WIN
    //convert ansi C time to FILETIME
    zen::UInt64 fileTimeLong = to<zen::UInt64>(utcTime + //may be < 0
                                               zen::Int64(3054539008UL, 2)); //timeshift between ansi C time and FILETIME in seconds == 11644473600s
    fileTimeLong *= 10000000U;

    FILETIME lastWriteTimeUtc = {};
    lastWriteTimeUtc.dwLowDateTime  = fileTimeLong.getLo();
    lastWriteTimeUtc.dwHighDateTime = fileTimeLong.getHi();

    //dates less than a few (let's say 13) hours after 1.1.1601 cause conversion errors in ::SystemTimeToTzSpecificLocalTime() if timezone is subtracted!
    if (lastWriteTimeUtc.dwHighDateTime < 110)
        return _("Error");

    SYSTEMTIME systemTimeLocal = {};

    static const bool useNewLocalTimeCalculation = isVistaOrLater();
    if (useNewLocalTimeCalculation) //use DST setting from source date (like in Windows 7, see http://msdn.microsoft.com/en-us/library/ms724277(VS.85).aspx)
    {
        if (lastWriteTimeUtc.dwHighDateTime >= 0x80000000)
            return _("Error");

        SYSTEMTIME systemTimeUtc = {};
        if (!::FileTimeToSystemTime(
                &lastWriteTimeUtc, //__in   const FILETIME *lpFileTime,
                &systemTimeUtc))   //__out  LPSYSTEMTIME lpSystemTime
            throw std::runtime_error(std::string((wxString(_("Conversion error:")) + wxT(" FILETIME -> SYSTEMTIME: ") +
                                                  wxT("(") + wxT("UTC [s]: ") + toString<wxString>(utcTime) + wxT(" ") +
                                                  wxT("UTC FILETIME: ")  + toString<wxString>(fileTimeLong) + wxT(") ") +
                                                  wxT("\n\n") + getLastErrorFormatted()).ToAscii()));

        if (!::SystemTimeToTzSpecificLocalTime(
                NULL,              //__in_opt  LPTIME_ZONE_INFORMATION lpTimeZone,
                &systemTimeUtc,    //__in      LPSYSTEMTIME lpUniversalTime,
                &systemTimeLocal)) //__out     LPSYSTEMTIME lpLocalTime
            throw std::runtime_error(std::string((wxString(_("Conversion error:")) + wxT(" SYSTEMTIME -> local SYSTEMTIME: ") +
                                                  wxT("(") + wxT("UTC [s]: ") + toString<wxString>(utcTime) + wxT("\n") +
                                                  wxT("UTC System time: ") +
                                                  toString<wxString>(systemTimeUtc.wYear)   + wxT(" ") +
                                                  toString<wxString>(systemTimeUtc.wMonth)  + wxT(" ") +
                                                  toString<wxString>(systemTimeUtc.wDay)    + wxT(" ") +
                                                  toString<wxString>(systemTimeUtc.wHour)   + wxT(" ") +
                                                  toString<wxString>(systemTimeUtc.wMinute) + wxT(" ") +
                                                  toString<wxString>(systemTimeUtc.wSecond) + wxT(")") +
                                                  wxT("\n\n") + getLastErrorFormatted()).ToAscii()));
    }
    else //use DST setting (like in Windows 2000 and XP)
    {
        FILETIME fileTimeLocal = {};
        if (!::FileTimeToLocalFileTime( //convert to local time
                &lastWriteTimeUtc,  //pointer to UTC file time to convert
                &fileTimeLocal))    //pointer to converted file time
            throw std::runtime_error(std::string((wxString(_("Conversion error:")) + wxT(" FILETIME -> local FILETIME: ") +
                                                  wxT("(") + wxT("UTC [s]: ") + toString<wxString>(utcTime) + wxT(" ") +
                                                  wxT("UTC FILETIME: ")  + toString<wxString>(fileTimeLong) + wxT(") ") +
                                                  wxT("\n\n") + getLastErrorFormatted()).ToAscii()));

        if (fileTimeLocal.dwHighDateTime >= 0x80000000)
            return _("Error");  //this actually CAN happen if UTC time is just below this border and ::FileTimeToLocalFileTime() adds 2 hours due to DST or whatever!
        //Testcase (UTC): dateHigh = 2147483647 (=0x7fffffff) -> year 30000
        //                dateLow  = 4294967295

        if (!::FileTimeToSystemTime(&fileTimeLocal,  //pointer to file time to convert
                                    &systemTimeLocal)) //pointer to structure to receive system time
            throw std::runtime_error(std::string((wxString(_("Conversion error:")) + wxT(" local FILETIME -> local SYSTEMTIME: ") +
                                                  wxT("(") + wxT("UTC [s]: ") + toString<wxString>(utcTime) + wxT(" ") +
                                                  wxT("local FILETIME: ")  +
                                                  wxT("High: ") + toString<wxString>(fileTimeLocal.dwHighDateTime) +
                                                  wxT("Low: ") + toString<wxString>(fileTimeLocal.dwLowDateTime) + wxT(") ") +
                                                  wxT("\n\n") + getLastErrorFormatted()).ToAscii()));
    }

    const wxDateTime localTime(systemTimeLocal.wDay,
                               wxDateTime::Month(systemTimeLocal.wMonth - 1),
                               systemTimeLocal.wYear,
                               systemTimeLocal.wHour,
                               systemTimeLocal.wMinute,
                               systemTimeLocal.wSecond);

#elif defined FFS_LINUX
    const time_t fileTime = to<time_t>(utcTime);
    const tm* timeinfo = ::localtime(&fileTime); //convert to local time

    /*
        char buffer[50];
        ::strftime(buffer, 50, "%Y-%m-%d  %H:%M:%S", timeinfo);
        return zToWx(buffer);
    */
    const wxDateTime localTime(timeinfo->tm_mday,
                               wxDateTime::Month(timeinfo->tm_mon),
                               1900 + timeinfo->tm_year,
                               timeinfo->tm_hour,
                               timeinfo->tm_min,
                               timeinfo->tm_sec);
#endif

    return localTime.FormatDate() + wxT("  ") + localTime.FormatTime();
}
bgstack15