DEADSOFTWARE

changed license to GPLv3 only; sorry, no trust to FSF anymore
[d2df-sdl.git] / src / shared / envvars.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE a_modes.inc}
16 {.$MODE OBJFPC}
17 unit envvars;
19 interface
21 uses SysUtils, CTypes;
23 function SetEnvVar(const VarName: AnsiString; const VarVal: AnsiString): Boolean;
24 function GetUserName: String;
26 implementation
28 uses
29 {$IFDEF WINDOWS}
30 Windows,
31 {$ENDIF}
32 utils;
35 {$IFDEF WINDOWS}
36 function setenv(const VarStr: PChar; const VarVal: PChar; Repl: cint): cint;
37 begin
38 if (SetEnvironmentVariable(VarStr, VarVal)) then
39 Result := 0
40 else
41 Result := -1;
42 end;
43 {$ELSE}
44 {$LINKLIB c}
45 const clib = 'c';
46 function setenv(const VarStr: PChar; const VarVal: PChar; Repl: cint): cint;
47 cdecl; external clib name 'setenv';
48 {$ENDIF}
50 function SetEnvVar(const VarName: AnsiString; const VarVal: AnsiString): Boolean;
51 begin
52 Result := (setenv(PChar(VarName), PChar(VarVal), 1) = 0);
53 end;
55 (* Get system username already in cp1251 *)
56 function GetUserName: AnsiString;
57 var i: Integer;
58 begin
59 {$IF DEFINED(WINDOWS)}
60 Result := utf2win(UTF8String(SysUtils.GetEnvironmentVariable(WideString('USERNAME'))));
61 {$ELSEIF DEFINED(UNIX)}
62 Result := utf2win(SysUtils.GetEnvironmentVariable('USER'));
63 {$ELSE}
64 Result := '';
65 {$ENDIF}
66 (* invalidate username with non-cp1251 symbols *)
67 i := Low(Result);
68 while i <= High(Result) do
69 begin
70 if Result[i] = '?' then
71 Result := '';
72 Inc(i)
73 end
74 end;
76 end.