File: System.cpp

package info (click to toggle)
astromenace 1.3.2%2Brepack-5
  • links: PTS, VCS
  • area: contrib
  • in suites: buster
  • size: 4,484 kB
  • sloc: cpp: 61,665; makefile: 26; sh: 19
file content (401 lines) | stat: -rwxr-xr-x 8,129 bytes parent folder | download | duplicates (5)
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/************************************************************************************

	AstroMenace (Hardcore 3D space shooter with spaceship upgrade possibilities)
	Copyright © 2006-2013 Michael Kurinnoy, Viewizard


	AstroMenace is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	AstroMenace is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with AstroMenace. If not, see <http://www.gnu.org/licenses/>.


	Web Site: http://www.viewizard.com/
	Project: http://sourceforge.net/projects/openastromenace/
	E-mail: viewizard@viewizard.com

*************************************************************************************/


#include "System.h"






//------------------------------------------------------------------------------------
// проверка расширения файла
//------------------------------------------------------------------------------------
bool vw_TestFileExtension(const char *name, const char *extension)
{
	if(name==0||extension==0) return false;
	size_t LengthName=strlen(name), LengthString=strlen(extension);
	if(LengthName<LengthString) return false;
	for(int i=LengthName-1;i>=0;i--)
		if(name[i]=='.')
		{
			if(!strcmp(&name[i+1],extension)) return true;
			else return false;
		}
	return false;
}










//------------------------------------------------------------------------------------
// все что ниже, нужно для открытия броузера
//------------------------------------------------------------------------------------








#ifdef WIN32
#include <tchar.h>
#include <shellapi.h>
static LONG GetRegistryKey(HKEY key, LPCTSTR subkey, LPTSTR retdata)
{
	HKEY hkey;
	LONG retval = RegOpenKeyEx(key, subkey, 0, KEY_QUERY_VALUE, &hkey);
	if (retval == ERROR_SUCCESS)
	{
		long datasize = MAX_PATH;
		TCHAR data[MAX_PATH];
		RegQueryValue(hkey, NULL, data, &datasize);
		_tcscpy(retdata,data);
		RegCloseKey(hkey);
	}
	return retval;
}
#endif // WIN32





#if defined(__APPLE__) && defined(__MACH__)

#include <CoreFoundation/CFBundle.h>
#include <ApplicationServices/ApplicationServices.h>

#endif // __APPLE__





// поиск пути для запуска броузера
/*
Build dependencies:
	libc6-dev
Runtime dependencies:
	libc6
*/
#ifdef __unix

#include <stdio.h>
#include <string.h>

#include <dirent.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>


char **get_path(void)
{
	const char *path = getenv("PATH"), *cstr;
	char *null_path, **tokenized_path, *str;
	unsigned int parts = (path[0] != '\0') ? 1 : 0, a;

	null_path = (char *)malloc(strlen(path) + 1);

	for(cstr = path, str = null_path; *cstr; ++cstr, ++str)
	{
		switch(*cstr)
		{
			case ':':
				*str = '\0';
				++parts;
				break;
			default:
				*str = *cstr;
		}
	}
	*str = '\0';

	tokenized_path = (char **)malloc(sizeof(char *) * (parts+1));
	tokenized_path[parts] = NULL;

	for(a = 0, str = null_path; a < parts; ++a)
	{
		tokenized_path[a] = str;

		do { ++str; } while(str[-1]);
	}

	return tokenized_path;
}


int executable_exists_in_path(char **tokenized_path, const char *app_name)
{
	unsigned int a;
	int found = 0;

	for(a = 0; !found && tokenized_path[a]; ++a)
	{
		DIR *dir = opendir(tokenized_path[a]);

		if(dir)
		{
			struct dirent *dirent;

			for(dirent = readdir(dir); dirent != NULL; dirent = readdir(dir))
			{
				if(strcmp(dirent->d_name, app_name) == 0)
				{
					/* We found something with a correct name, is it a proper executable? */
					size_t full_path_length = strlen(tokenized_path[a]) + 1 + strlen(app_name) + 1;
					char *full_path = (char *)malloc(full_path_length);
					struct stat buf;

					snprintf(full_path, full_path_length, "%s/%s", tokenized_path[a], app_name);

					if(stat(full_path, &buf) == 0)
					{
						/* Is is a regular file and is it executable by anyone? */
						if(S_ISREG(buf.st_mode) && (buf.st_mode & S_IXOTH)) found = 1;

						/* FIXME It would be more accurate to test if this user can
						 * execute the file rather than if any user can.
						 */
					}

					free(full_path);
				}
			}

			closedir(dir);
		}
	}

	return found;
}

char **get_browsers(void)
{

	static const char *browser_list[] =
	{
		"xdg-open", // первое ставим именно xdg-open
		"firefox",
		"opera",
		"chrome",
		"konqueror",
		"chromium",
		"epiphany",
		"midori",
		"dillo",
		"rekonq"
	};
	char **tokenized_path = get_path(), **browsers = NULL;


	if(!browsers)
	{
		unsigned int a, b, browser_list_count = sizeof(browser_list)/sizeof(browser_list[0]);

		browsers = (char **)calloc(browser_list_count, sizeof(char *));

		for(a = b = 0; a < browser_list_count; ++a)
		{
			if(executable_exists_in_path(tokenized_path, browser_list[a]))
				browsers[b++] = strdup(browser_list[a]);
		}

		if(b == 0)
		{
			free(browsers);
			browsers = NULL;
		}
	}

	free(tokenized_path[0]);
	free(tokenized_path);

	return browsers;
}

#endif// __unix




























// открываем браузер
bool vw_OpenBrouser(const char *url)
{
#ifdef WIN32

	HINSTANCE result;
	result = ShellExecute(NULL, _T("open"), url, NULL,NULL, SW_NORMAL);
	if ((UINT)result > HINSTANCE_ERROR) return true;

	// если не получилось, делаем по второму сценарию
	TCHAR key[MAX_PATH + MAX_PATH];
	if (GetRegistryKey(HKEY_CLASSES_ROOT, _T(".htm"), key) == ERROR_SUCCESS)
	{
		lstrcat(key, _T("\\shell\\open\\command"));

		if (GetRegistryKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS)
		{
			TCHAR *pos;
			pos = _tcsstr(key, _T("\"%1\""));
			if (pos == NULL)
			{                     // No quotes found
				pos = strstr(key, _T("%1"));       // Check for %1, without quotes
				if (pos == NULL)                   // No parameter at all...
					pos = key+_tcslen(key)-1;
				else
					*pos = _T('\0');                   // Remove the parameter
			}
			else
				*pos = _T('\0');                       // Remove the parameter

			lstrcat(pos, _T(" "));
			lstrcat(pos, url);
			result = (HINSTANCE) WinExec(key,SW_NORMAL);
		}
	}
	else
		return false;

#endif // WIN32
#if defined(__APPLE__) && defined(__MACH__)

	CFURLRef openurl = CFURLCreateWithBytes (
				NULL,						// allocator
				(BYTE*)url,					// URLBytes
				strlen(url),				// length
				kCFStringEncodingASCII,		// encoding
				NULL);						// baseURL
	LSOpenCFURLRef(openurl,0);
	CFRelease(openurl);

#endif // __APPLE__
#ifdef __unix

	char **browsers = get_browsers();
	unsigned int a = 0;


	if(browsers)
    {
    	// не перебираем!!! берем первый броузер
    	a = 0;

		// проверка, если установлен 93 дисплей - это компиз... открываем в 0-м
		char *value = getenv("DISPLAY");
		bool NeedSetDisplay = false;
		if (value != 0)
		{
			char *display = new char[strlen(value)+1];
			display = strdup(value);
			if (!strcmp(display, ":93"))
			{
				NeedSetDisplay = true;
				printf("DISPLAY=%s \n", display);
			}
			delete [] display;
		}


        printf("%u:\t%s\n", a, browsers[a]);

        char GotoUrl[1024];

        if (NeedSetDisplay)
			sprintf(GotoUrl,"DISPLAY=:0 %s %s",browsers[a], url);
		else
			sprintf(GotoUrl,"%s %s",browsers[a], url);



        int x;
        x = fork();

		switch(x)
		{
			case -1:
				printf("error, unable to fork process!\n");
				break;
			case 0:
				execl(getenv("SHELL"), "sh", "-c", GotoUrl, (char *)0);
				// should not be reached
				printf("Error executing process!\n");
				break;
		}
	}
	else
	{
		printf("Could not open Web page. Please, visit %s\n", url);
		return false;
	}


	if(browsers)
	{
		for(a = 0; browsers[a]; ++a)
			free(browsers[a]);
		free(browsers);
	}

#endif // unix


	return true;
}