Welcome to mirror list, hosted at ThFree Co, Russian Federation.

dirmix.cpp « mix « src « far2l - github.com/elfmz/far2l.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9439a81818e72ef7c94c4ee6ba96ec7f53ec8ae8 (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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/*
dirmix.cpp

Misc functions for working with directories
*/
/*
Copyright (c) 1996 Eugene Roshal
Copyright (c) 2000 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "headers.hpp"


#include "dirmix.hpp"
#include "cvtname.hpp"
#include "message.hpp"
#include "lang.hpp"
#include "ctrlobj.hpp"
#include "filepanels.hpp"
#include "treelist.hpp"
#include "config.hpp"
#include "pathmix.hpp"
#include "strmix.hpp"
#include "interf.hpp"
#include "scantree.hpp"
#include "delete.hpp"
#include <atomic>


BOOL FarChDir(const wchar_t *NewDir, BOOL ChangeDir)
{
	if (!NewDir || !*NewDir)
		return FALSE;

	BOOL rc=FALSE;
	FARString strCurDir;

	{
		if (ChangeDir)
		{
			if (*NewDir=='/') {
				strCurDir = NewDir;
				rc = apiSetCurrentDirectory(strCurDir); // здесь берем корень
			} else {
				apiGetCurrentDirectory(strCurDir);
				ConvertNameToFull(NewDir,strCurDir);
				PrepareDiskPath(strCurDir,false); // TRUE ???
				rc = apiSetCurrentDirectory(strCurDir);				
			}
			if (!rc)
			{
				fprintf(stderr, "FarChDir: FAILED - '%ls'\n", NewDir);
			}
		}
	}

	return rc;
}

/*
  Функция TestFolder возвращает одно состояний тестируемого каталога:

    TSTFLD_NOTFOUND   (2) - нет такого
    TSTFLD_NOTEMPTY   (1) - не пусто
    TSTFLD_EMPTY      (0) - пусто
    TSTFLD_NOTACCESS (-1) - нет доступа
    TSTFLD_ERROR     (-2) - ошибка (кривые параметры или нехватило памяти для выделения промежуточных буферов)
*/
TESTFOLDERCONST TestFolder(const wchar_t *Path)
{
	if (!(Path && *Path)) // проверка на вшивость
		return TSTFLD_ERROR;

	std::string mbPath;
	Wide2MB(Path, mbPath);
	while (mbPath.size() > 1 && mbPath.back() == '/')
		mbPath.resize(mbPath.size() - 1);

	struct stat s{};
	int r = sdc_stat(mbPath.c_str(), &s);
	if (r == -1)
	{
		if (errno == EPERM || errno == EACCES)
			return TSTFLD_NOTACCESS;

		return TSTFLD_NOTFOUND;
	}

	if (!S_ISDIR(s.st_mode)) // not directories are always empty
		return TSTFLD_EMPTY;

	DIR *d = sdc_opendir(mbPath.c_str());
	if (!d) switch (errno)
	{
		case EPERM: case EACCES:
			return TSTFLD_NOTACCESS;

		case ENOMEM: case EMFILE: case ENFILE: case EBADF:
			return TSTFLD_ERROR;

		default:
			return TSTFLD_EMPTY;
	}

	TESTFOLDERCONST out = TSTFLD_EMPTY;
	for (;;)
	{
		struct dirent *de = sdc_readdir(d);
		if (!de) break;
		if (strcmp(de->d_name, ".") && strcmp(de->d_name, ".."))
		{
			out = TSTFLD_NOTEMPTY;
			break;
		}
	}
	sdc_closedir(d);

	return out;
}

/*
   Проверка пути или хост-файла на существование
   Если идет проверка пути (IsHostFile=FALSE), то будет
   предпринята попытка найти ближайший путь. Результат попытки
   возвращается в переданном TestPath.

   Return: 0 - бЯда.
           1 - ОБИ!,
          -1 - Почти что ОБИ, но ProcessPluginEvent вернул TRUE
   TestPath может быть пустым, тогда просто исполним ProcessPluginEvent()

*/
int CheckShortcutFolder(FARString *pTestPath,int IsHostFile, BOOL Silent)
{
	if (pTestPath && !pTestPath->IsEmpty() && apiGetFileAttributes(*pTestPath) == INVALID_FILE_ATTRIBUTES)
	{
		int FoundPath=0;
		FARString strTarget = *pTestPath;
		TruncPathStr(strTarget, ScrX-16);

		if (IsHostFile)
		{
			WINPORT(SetLastError)(ERROR_FILE_NOT_FOUND);

			if (!Silent)
				Message(MSG_WARNING | MSG_ERRORTYPE, 1, Msg::Error, strTarget, Msg::Ok);
		}
		else // попытка найти!
		{
			WINPORT(SetLastError)(ERROR_PATH_NOT_FOUND);

			if (Silent || !Message(MSG_WARNING | MSG_ERRORTYPE, 2, Msg::Error, strTarget, Msg::NeedNearPath, Msg::HYes,Msg::HNo))
			{
				FARString strTestPathTemp = *pTestPath;

				for (;;)
				{
					if (!CutToSlash(strTestPathTemp,true))
						break;

					if (apiGetFileAttributes(strTestPathTemp) != INVALID_FILE_ATTRIBUTES)
					{
						int ChkFld=TestFolder(strTestPathTemp);

						if (ChkFld > TSTFLD_ERROR && ChkFld < TSTFLD_NOTFOUND)
						{
							if (!(pTestPath->At(0) == GOOD_SLASH && pTestPath->At(1) == GOOD_SLASH && !strTestPathTemp.At(1)))
							{
								*pTestPath = strTestPathTemp;

								if (pTestPath->GetLength() == 2) // для случая "C:", иначе попадем в текущий каталог диска C:
									AddEndSlash(*pTestPath);

								FoundPath=1;
							}

							break;
						}
					}
				}
			}
		}

		if (!FoundPath)
			return 0;
	}

	if (CtrlObject->Cp()->ActivePanel->ProcessPluginEvent(FE_CLOSE,nullptr))
		return -1;

	return 1;
}

void CreatePath(FARString &strPath)
{
	wchar_t *ChPtr = strPath.GetBuffer();
//	wchar_t *DirPart = ChPtr;
	BOOL bEnd = FALSE;

	for (;;)
	{
		if (!*ChPtr || IsSlash(*ChPtr))
		{
			if (!*ChPtr)
				bEnd = TRUE;

			*ChPtr = 0;

			if (apiCreateDirectory(strPath, nullptr))
				TreeList::AddTreeName(strPath);

			if (bEnd)
				break;

			*ChPtr = GOOD_SLASH;
//			DirPart = ChPtr+1;
		}

		ChPtr++;
	}

	strPath.ReleaseBuffer();
}

std::string GetHelperPathName(const char *name)
{
 	std::string out = g_strFarPath.GetMB();
	out+= GOOD_SLASH;
	out+= name;

	struct stat s;
	if (stat(out.c_str(), &s) == 0)
		return out;

	if (TranslateInstallPath_Share2Lib(out)) {
		if (stat(out.c_str(), &s) == 0)
			return out;
	}

	fprintf(stderr, "GetHelperPathName('%s') - not found\n", name);
	return out;
}

std::string GetMyScriptQuoted(const char *name)
{
	std::string out = "\"";
	out+= EscapeCmdStr(GetHelperPathName(name));
	out+= "\"";
	return out;
}


void PrepareTemporaryOpenPath(FARString &Path)
{
	Path = InMyTemp("open");

	std::vector<FARString> outdated;

	ScanTree scan_tree(0, 0);
	scan_tree.SetFindPath(Path.CPtr(), L"*", 0);
	FAR_FIND_DATA_EX found_data;
	FARString found_name;
	time_t now = time(nullptr);
	while (scan_tree.GetNextName(&found_data, found_name)) {
		struct timespec ts_mod = {}, ts_change = {};
		WINPORT(FileTimeToLocalFileTime)(&found_data.ftUnixModificationTime, &found_data.ftUnixModificationTime);
		WINPORT(FileTimeToLocalFileTime)(&found_data.ftUnixStatusChangeTime, &found_data.ftUnixStatusChangeTime);
		WINPORT(FileTime_Win32ToUnix)(&found_data.ftUnixModificationTime, &ts_mod);
		WINPORT(FileTime_Win32ToUnix)(&found_data.ftUnixStatusChangeTime, &ts_change);
		time_t delta = std::min(now - ts_mod.tv_sec, now - ts_change.tv_sec);
		if (delta > 60) {//one minute ought be enouht to open anything (c)
			outdated.push_back(found_name);
			fprintf(stderr, "PrepareTemporaryOpenPath: delta=%u for '%ls'\n", 
				(unsigned int)delta, found_name.CPtr());
		}
	};

	for (const auto &p : outdated) {
		DeleteDirTree(p.CPtr());
	}
	apiCreateDirectory(Path, nullptr);
	
	static std::atomic<unsigned short>	s_counter{0};
	char tmp[64]; sprintf(tmp, "%c%u_%u", GOOD_SLASH, (unsigned int)getpid(), (unsigned int)++s_counter);
	
	Path+= tmp;
	apiCreateDirectory(Path, nullptr);
}


FARString DefaultPanelInitialDirectory()
{
	FARString out;
	const std::string &home = GetMyHome();
	if (!home.empty()) {
		out = home;
	} else {
		out = g_strFarPath;
	}
	
	DeleteEndSlash(out);
	return out;
}