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

GnomePlatform.cs « GnomePlatform « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 556db7f7c910bb1bfd2d269f9f3f01eaa882d2f1 (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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//
// GnomePlatform.cs
//
// Author:
//   Geoff Norton  <gnorton@novell.com>
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using Gnome;
using MonoDevelop.Ide.Desktop;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core;

namespace MonoDevelop.Platform
{
	public class GnomePlatform : PlatformService
	{
		static bool useGio;

		Gnome.ThumbnailFactory thumbnailFactory = new Gnome.ThumbnailFactory (Gnome.ThumbnailSize.Normal);

		static GnomePlatform ()
		{
			try {
				Gio.GetDefaultForType ("text/plain");
				useGio = true;
			} catch (Exception ex) {
				Console.WriteLine (ex);
			}
			//apparently Gnome.Icon needs GnomeVFS initialized even when we're using GIO.
			Gnome.Vfs.Vfs.Initialize ();
		}
		
		DesktopApplication GetGnomeVfsDefaultApplication (string mimeType)
		{
			var app = Gnome.Vfs.Mime.GetDefaultApplication (mimeType);
			if (app != null)
				return (DesktopApplication) Marshal.PtrToStructure (app.Handle, typeof(DesktopApplication));
			else
				return null;
		}
		
		IEnumerable<DesktopApplication> GetGnomeVfsApplications (string mimeType)
		{
			var def = GetGnomeVfsDefaultApplication (mimeType);
			var list = new List<DesktopApplication> ();
			var apps = Gnome.Vfs.Mime.GetAllApplications (mimeType);
			foreach (var app in apps) {
				var dap = (GnomeVfsApp) Marshal.PtrToStructure (app.Handle, typeof(GnomeVfsApp));
				if (!string.IsNullOrEmpty (dap.Command) && !string.IsNullOrEmpty (dap.DisplayName) && !dap.Command.Contains ("monodevelop ")) {
					var isDefault = def != null && def.Id == dap.Command;
					list.Add (new GnomeDesktopApplication (dap.Command, dap.DisplayName, isDefault));
				}
			}
			return list;
		}
		
		public override IEnumerable<DesktopApplication> GetApplications (string filename)
		{
			var mimeType = GetMimeTypeForUri (filename);
			return GetApplicationsForMimeType (mimeType);
		}

		IEnumerable<DesktopApplication> GetApplicationsForMimeType (string mimeType)
		{
			if (useGio)
				return Gio.GetAllForType (mimeType);
			else
				return GetGnomeVfsApplications (mimeType);
		}
		
		struct GnomeVfsApp {
			public string Id, DisplayName, Command;
		}

		protected override string OnGetMimeTypeDescription (string mt)
		{
			if (useGio)
				return Gio.GetMimeTypeDescription (mt);
			else
				return Gnome.Vfs.Mime.GetDescription (mt);
		}

		protected override string OnGetMimeTypeForUri (string uri)
		{
			if (uri == null)
				return null;
			
			if (useGio) {
				string mt = Gio.GetMimeTypeForUri (uri);
				if (mt != null)
					return mt;
			}
			return Gnome.Vfs.MimeType.GetMimeTypeForUri (ConvertFileNameToVFS (uri));
		}
		
		protected override bool OnGetMimeTypeIsText (string mimeType)
		{
			// If gedit can open the file, this editor also can do it
			foreach (DesktopApplication app in GetApplicationsForMimeType (mimeType))
				if (app.Id == "gedit")
					return true;
			return base.OnGetMimeTypeIsText (mimeType);
		}


		public override void ShowUrl (string url)
		{
			Gnome.Url.Show (url);
		}
		
		public override string DefaultMonospaceFont {
			get {
				try {
					return (string) (new GConf.Client ().Get ("/desktop/gnome/interface/monospace_font_name"));
				} catch (Exception) {
					return "Monospace 11";
				}
			}
		}
		
		public override string Name {
			get { return "Gnome"; }
		}

		protected override string OnGetIconIdForFile (string filename)
		{
			if (filename == "Documentation") {
				return "gnome-fs-regular";
			} 
			if (System.IO.Directory.Exists (filename)) {
				return "gnome-fs-directory";
			} else if (System.IO.File.Exists (filename)) {
				filename = EscapeFileName (filename);
				if (filename == null)
					return "gnome-fs-regular";
				
				string icon = null;
				Gnome.IconLookupResultFlags result;
				try {
					icon = Gnome.Icon.LookupSync (IconTheme.Default, thumbnailFactory, filename, null, 
					                              Gnome.IconLookupFlags.None, out result);
				} catch {}
				if (icon != null && icon.Length > 0)
					return icon;
			}			
			return "gnome-fs-regular";
			
		}
		
		protected override Xwt.Drawing.Image OnGetIconForFile (string filename)
		{
			string icon = OnGetIconIdForFile (filename);
			return GetIconForType (icon);
		}
		
		string EscapeFileName (string filename)
		{
			foreach (char c in filename) {
				// FIXME: This is a temporary workaround. In some systems, files with
				// accented characters make LookupSync crash. Still trying to find out why.
				if ((int)c < 32 || (int)c > 127)
					return null;
			}
			return ConvertFileNameToVFS (filename);
		}
		
		static string ConvertFileNameToVFS (string fileName)
		{
			string result = fileName;
			result = result.Replace ("%", "%25");
			result = result.Replace ("#", "%23");
			result = result.Replace ("?", "%3F");
			return result;
		}
		
		
		delegate string TerminalRunnerHandler (string command, string args, string dir, string title, bool pause);
		delegate string TerminalOpenFolderRunnerHandler (string dir);

		string terminal_command;
		bool terminal_probed;
		TerminalRunnerHandler runner;
		TerminalOpenFolderRunnerHandler openDirectoryRunner;
		
		public override ProcessAsyncOperation StartConsoleProcess (string command, string arguments, string workingDirectory,
		                                                            IDictionary<string, string> environmentVariables, 
		                                                            string title, bool pauseWhenFinished)
		{
			ProbeTerminal ();
			
			string exec = runner (command, arguments, workingDirectory, title, pauseWhenFinished);
			var psi = new ProcessStartInfo (terminal_command, exec) {
				CreateNoWindow = true,
				UseShellExecute = false,
			};
			foreach (var env in environmentVariables)
				psi.EnvironmentVariables [env.Key] = env.Value;
			
			ProcessWrapper proc = new ProcessWrapper ();
			proc.StartInfo = psi;
			proc.Start ();
			return proc;
		}
		
#region Terminal runner implementations
		
		private static string GnomeTerminalRunner (string command, string args, string dir, string title, bool pause)
		{
			string extra_commands = pause 
				? BashPause.Replace ("'", "\\\"")
				: String.Empty;
			
			return String.Format (@" --disable-factory --title ""{4}"" -e ""bash -c 'cd {3} ; {0} {1} ; {2}'""",
				command,
				EscapeArgs (args),
				extra_commands,
				EscapeDir (dir),
				title);
		}
		
		private static string XtermRunner (string command, string args, string dir, string title, bool pause)
		{
			string extra_commands = pause 
				? BashPause
				: String.Empty;
			
			return String.Format (@" -title ""{4}"" -e bash -c ""cd {3} ; '{0}' {1} ; {2}""",
				command,
				EscapeArgs (args),
				extra_commands,
				EscapeDir (dir),
				title);
		}

		private static string KdeTerminalRunner (string command, string args, string dir, string title, bool pause)
		{
			string extra_commands = pause 
				? BashPause.Replace ("'", "\"")
					: String.Empty;

			return String.Format (@" --nofork --caption ""{4}"" --workdir=""{3}"" -e ""bash"" -c '{0} {1} ; {2}'",
			                      command,
			                      args,
			                      extra_commands,
			                      EscapeDir (dir),
			                      title);
		}

		private static string GnomeTerminalOpenFolderRunner (string dir) {
			return string.Format(@" --working-directory=""{0}""", EscapeDir(dir));
		}

		private static string XtermOpenFolderRunner (string dir) {
			return string.Format(@" -e bash -c ""cd {0}""", EscapeDir(dir));
		}

		private static string KdeTerminalOpenFolderRunner (string dir) {
			return string.Format(@" --nofork --workdir=""{0}""", EscapeDir(dir));
		}

		private static string EscapeArgs (string args)
		{
			return args.Replace ("\\", "\\\\").Replace ("\"", "\\\"");
		}
		
		private static string EscapeDir (string dir)
		{
			return dir.Replace (" ", "\\ ").Replace (";", "\\;");
		}
		
		private static string BashPause {
			get { return @"echo; read -p 'Press any key to continue...' -n1;"; }
		}

#endregion

#region Probing for preferred terminal

		private void ProbeTerminal ()
		{
			if (terminal_probed) {
				return;
			}
			
			terminal_probed = true;
			
			string fallback_terminal = PropertyService.Get ("MonoDevelop.Shell", "xterm");
			string preferred_terminal;
			TerminalRunnerHandler preferred_runner = null;
			TerminalRunnerHandler fallback_runner = XtermRunner;

			TerminalOpenFolderRunnerHandler preferedOpenFolderRunner = null;
			TerminalOpenFolderRunnerHandler fallbackOpenFolderRunner = XtermOpenFolderRunner;

			if (!String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("GNOME_DESKTOP_SESSION_ID"))) {
				preferred_terminal = "gnome-terminal";
				preferred_runner = GnomeTerminalRunner;
				preferedOpenFolderRunner = GnomeTerminalOpenFolderRunner;
			}
			else if (!String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MATE_DESKTOP_SESSION_ID"))) {
				preferred_terminal = "mate-terminal";
				preferred_runner = GnomeTerminalRunner;
				preferedOpenFolderRunner = GnomeTerminalOpenFolderRunner;
			} 
			else if (!String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("KDE_SESSION_VERSION"))) { 
				preferred_terminal = "konsole";
				preferred_runner = KdeTerminalRunner;
				preferedOpenFolderRunner = KdeTerminalOpenFolderRunner;
			}
			else {
				preferred_terminal = fallback_terminal;
				preferred_runner = fallback_runner;
				preferedOpenFolderRunner = fallbackOpenFolderRunner;
			}

			terminal_command = FindExec (preferred_terminal);
			if (terminal_command != null) {
				runner = preferred_runner;
				openDirectoryRunner = preferedOpenFolderRunner;
				return;
			}
			
			terminal_command = FindExec (fallback_terminal);
			runner = fallback_runner;
			openDirectoryRunner = fallbackOpenFolderRunner;
		}

		private string FindExec (string command)
		{
			foreach (string path in GetExecPaths ()) {
				string full_path = Path.Combine (path, command);
				try {
					FileInfo info = new FileInfo (full_path);
					// FIXME: System.IO is super lame, should check for 0755
					if (info.Exists) {
						return full_path;
					}
				} catch {
				}
			}

			return null;
		}

		private string [] GetExecPaths ()
		{
			string path = Environment.GetEnvironmentVariable ("PATH");
			if (String.IsNullOrEmpty (path)) {
				return new string [] { "/bin", "/usr/bin", "/usr/local/bin" };
			}

			// this is super lame, should handle quoting/escaping
			return path.Split (':');
		}

#endregion
				
		public override bool CanOpenTerminal {
			get {
				return true;
			}
		}

		public override void OpenTerminal (FilePath directory, IDictionary<string, string> environmentVariables, string title)
		{
			ProbeTerminal ();
			Runtime.ProcessService.StartProcess (terminal_command, openDirectoryRunner(directory), directory, null);
		}
	}
	
	class GnomeDesktopApplication : DesktopApplication
	{
		public GnomeDesktopApplication (string command, string displayName, bool isDefault) : base (command, displayName, isDefault)
		{
		}
		
		string Command {
			get { return Id; }
		}
		
		public override void Launch (params string[] files)
		{
			// TODO: implement all other cases
			if (Command.IndexOf ("%f") != -1) {
				foreach (string s in files) {
					string cmd = Command.Replace ("%f", "\"" + s + "\"");
					Process.Start (cmd);
				}
			}
			else if (Command.IndexOf ("%F") != -1) {
				string[] fs = new string [files.Length];
				for (int n=0; n<files.Length; n++) {
					fs [n] = "\"" + files [n] + "\"";
				}
				string cmd = Command.Replace ("%F", string.Join (" ", fs));
				Process.Start (cmd);
			} else {
				foreach (string s in files) {
					Process.Start (Command, "\"" + s + "\"");
				}
			}
		}
	}
}