This repository has been archived by the owner on Oct 16, 2020. It is now read-only.
/
MenuItemBuilders.cs
569 lines (498 loc) · 19 KB
/
MenuItemBuilders.cs
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
// <version>$Revision$</version>
// </file>
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using ICSharpCode.Core;
using ICSharpCode.Core.Presentation;
using ICSharpCode.SharpDevelop.Gui;
using ICSharpCode.SharpDevelop.Internal.ExternalTool;
using ICSharpCode.SharpDevelop.Project;
using ICSharpCode.SharpDevelop.Util;
using SDCommandManager=ICSharpCode.Core.Presentation.CommandManager;
namespace ICSharpCode.SharpDevelop.Commands
{
public class NavigationHistoryMenuBuilder : IMenuItemBuilder
{
// TODO: refactor BuildSubmenu to add a choice between flat and perfile, eventually per class/method sorting of the list
/*ToolStripItem[] BuildMenuFlat(ICollection<INavigationPoint> points, int additionalItems)
{
ToolStripItem[] items = new ToolStripItem[points.Count+additionalItems];
MenuCommand cmd = null;
INavigationPoint p = null;
List<INavigationPoint> list = new List<INavigationPoint>(points);
int n = points.Count-1; // the last point
int i = 0;
while (i<points.Count) {
p = list[n-i];
cmd = new MenuCommand(p.Description, new EventHandler(NavigateTo));
cmd.Tag = p;
// if (p == NavigationService.CurrentPosition) {
// cmd.Text = "*** "+cmd.Text;
// }
items[i++] = cmd;
}
return items;
}*/
List<FrameworkElement> BuildMenuByFile(ICollection<INavigationPoint> points)
{
List<FrameworkElement> items = new List<FrameworkElement>();
Dictionary<string, List<INavigationPoint>> files =
new Dictionary<string, List<INavigationPoint>>();
List<string> fileNames = new List<string>();
foreach (INavigationPoint p in points) {
if (p.FileName==null) {
throw new ApplicationException("should not get here!");
}
if (!fileNames.Contains(p.FileName)) {
fileNames.Add(p.FileName);
files.Add(p.FileName, new List<INavigationPoint>());
}
if (!files[p.FileName].Contains(p)) {
files[p.FileName].Add(p);
}
}
fileNames.Sort();
MenuItem containerItem = null;
MenuItem cmd = null;
foreach (string fname in fileNames) {
// create a menu bucket
containerItem = new MenuItem();
containerItem.Header = System.IO.Path.GetFileName(fname);
containerItem.ToolTip = fname;
// sort and populate the bucket's contents
// files[fname].Sort();
foreach(INavigationPoint p in files[fname]) {
cmd = new MenuItem();
cmd.Header = p.Description;
cmd.Click += NavigateTo;
cmd.Tag = p;
containerItem.Items.Add(cmd);
}
// if there's only one nested item, add it
// to the result directly, ignoring the bucket
// if (containerItem.DropDownItems.Count==1) {
// items[i] = containerItem.DropDownItems[0];
// items[i].Text = ((INavigationPoint)items[i].Tag).FullDescription;
// i++;
// } else {
// // add the bucket to the result
// items[i++] = containerItem;
// }
// add the bucket to the result
items.Add(containerItem);
}
return items;
}
public ICollection BuildItems(Codon codon, object owner)
{
if (NavigationService.CanNavigateBack || NavigationService.CanNavigateForwards) {
ICollection<INavigationPoint> points = NavigationService.Points;
//ToolStripItem[] items = BuildMenuFlat(points, numberOfAdditionalItems);
var result = BuildMenuByFile(points);
// additional item 1
result.Add(new Separator());
// additional item 2
MenuItem clearHistory = new MenuItem();
clearHistory.Header = StringParser.Parse("${res:XML.MainMenu.Navigation.ClearHistory}");
clearHistory.Click += delegate { NavigationService.ClearHistory(); };
result.Add(clearHistory);
return result;
}
// default is to disable the dropdown feature...
return null;
}
public void NavigateTo(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
NavigationService.Go((INavigationPoint)item.Tag);
}
}
public class RecentFilesMenuBuilder : IMenuItemBuilder
{
public ICollection BuildItems(Codon codon, object owner)
{
RecentOpen recentOpen = FileService.RecentOpen;
if (recentOpen.RecentFile.Count > 0) {
var items = new System.Windows.Controls.MenuItem[recentOpen.RecentFile.Count];
for (int i = 0; i < recentOpen.RecentFile.Count; ++i) {
// variable inside loop, so that anonymous method refers to correct recent file
string recentFile = recentOpen.RecentFile[i];
string accelaratorKeyPrefix = i < 10 ? "_" + ((i + 1) % 10) + " " : "";
items[i] = new System.Windows.Controls.MenuItem() {
Header = accelaratorKeyPrefix + recentFile
};
items[i].Click += delegate {
FileService.OpenFile(recentFile);
};
}
return items;
} else {
return new [] { new System.Windows.Controls.MenuItem {
Header = StringParser.Parse("${res:Dialog.Componnents.RichMenuItem.NoRecentFilesString}"),
IsEnabled = false
} };
}
}
}
public class RecentProjectsMenuBuilder : IMenuItemBuilder
{
public ICollection BuildItems(Codon codon, object owner)
{
RecentOpen recentOpen = FileService.RecentOpen;
if (recentOpen.RecentProject.Count > 0) {
var items = new System.Windows.Controls.MenuItem[recentOpen.RecentProject.Count];
for (int i = 0; i < recentOpen.RecentProject.Count; ++i) {
// variable inside loop, so that anonymous method refers to correct recent file
string recentProject = recentOpen.RecentProject[i];
string accelaratorKeyPrefix = i < 10 ? "_" + ((i + 1) % 10) + " " : "";
items[i] = new System.Windows.Controls.MenuItem() {
Header = accelaratorKeyPrefix + recentProject
};
items[i].Click += delegate {
ProjectService.LoadSolution(recentProject);
};
}
return items;
} else {
return new [] { new System.Windows.Controls.MenuItem {
Header = StringParser.Parse("${res:Dialog.Componnents.RichMenuItem.NoRecentProjectsString}"),
IsEnabled = false
} };
}
}
}
public class ToolMenuBuilder : IMenuItemBuilder
{
private static InputBindingCategory externalToolsCategory;
static ToolMenuBuilder()
{
var categoryName = StringParser.Parse("External tools");
externalToolsCategory = new InputBindingCategory("/MainMenu/Tools/ExternalTools", categoryName);
ICSharpCode.Core.Presentation.CommandManager.RegisterInputBindingCategory(externalToolsCategory);
}
private bool bindingsAssigned = false;
public ICollection BuildItems(Codon codon, object owner)
{
var items = new System.Windows.Controls.MenuItem[ToolLoader.Tool.Count];
for (int i = 0; i < ToolLoader.Tool.Count; ++i) {
ExternalTool tool = ToolLoader.Tool[i];
items[i] = new System.Windows.Controls.MenuItem();
var routedCommandName = "SDToolsCommands.RunExternalTool_" + tool.ToString();
var routedCommandText = MenuService.ConvertLabel(StringParser.Parse(tool.ToString()));
if(!bindingsAssigned) {
var addIn = AddInTree.AddIns.FirstOrDefault(a => a.Name == "SharpDevelop");
// Dynamicaly create routed UI command to loaded pad and bindings for it
SDCommandManager.RegisterRoutedUICommand(routedCommandName, routedCommandText);
var commandBindingInfo = new CommandBindingInfo();
commandBindingInfo.OwnerTypeName = SDCommandManager.DefaultOwnerTypeName;
commandBindingInfo.RoutedCommandName = routedCommandName;
commandBindingInfo.CanExecuteEventHandler = delegate(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; };
commandBindingInfo.ExecutedEventHandler = delegate { RunTool(tool); };
SDCommandManager.RegisterCommandBindingInfo(commandBindingInfo);
var inputBindingInfo = new InputBindingInfo();
inputBindingInfo.OwnerTypeName = SDCommandManager.DefaultOwnerTypeName;
inputBindingInfo.RoutedCommandName = routedCommandName;
inputBindingInfo.Categories.Add(externalToolsCategory);
SDCommandManager.RegisterInputBindingInfo(inputBindingInfo);
}
var gesturesTemplate = BindingInfoTemplate.Create(null, SDCommandManager.DefaultOwnerTypeName, routedCommandName);
var updatedGestures = SDCommandManager.FindInputGestures(gesturesTemplate);
var updatedGesturesText = (string)new InputGestureCollectionConverter().ConvertToInvariantString(updatedGestures);
items[i].InputGestureText = updatedGesturesText;
items[i].Command = SDCommandManager.GetRoutedUICommand(routedCommandName);
items[i].Header = StringParser.Parse(tool.ToString());
}
bindingsAssigned = true;
return items;
}
void RunTool(ExternalTool tool)
{
// Set these to somewhat useful values in case StingParser.Parse() passes when being called on one of them.
string command = tool.Command;
string args = tool.Arguments;
// This needs it's own try/catch because if parsing these messages fail, the catch block after
// the second try would also throw because MessageService.ShowError() calls StringParser.Parse()
try {
command = StringParser.Parse(tool.Command);
args = StringParser.Parse(tool.Arguments);
} catch (Exception ex) {
MessageService.ShowError("${res:XML.MainMenu.ToolMenu.ExternalTools.ExecutionFailed} '" + ex.Message);
return;
}
if (tool.PromptForArguments) {
args = MessageService.ShowInputBox(tool.MenuCommand, "${res:XML.MainMenu.ToolMenu.ExternalTools.EnterArguments}", args);
if (args == null)
return;
}
try {
if (tool.UseOutputPad) {
ProcessRunner processRunner = new ProcessRunner();
processRunner.LogStandardOutputAndError = false;
processRunner.ProcessExited += ProcessExitEvent;
processRunner.OutputLineReceived += process_OutputLineReceived;
processRunner.ErrorLineReceived += process_OutputLineReceived;
processRunner.WorkingDirectory = StringParser.Parse(tool.InitialDirectory);
if (args == null || args.Length == 0 || args.Trim('"', ' ').Length == 0) {
processRunner.Start(command);
} else {
processRunner.Start(command, args);
}
} else {
ProcessStartInfo startinfo;
if (args == null || args.Length == 0 || args.Trim('"', ' ').Length == 0) {
startinfo = new ProcessStartInfo(command);
} else {
startinfo = new ProcessStartInfo(command, args);
}
startinfo.WorkingDirectory = StringParser.Parse(tool.InitialDirectory);
Process process = new Process();
process.StartInfo = startinfo;
process.Start();
}
} catch (Exception ex) {
MessageService.ShowError("${res:XML.MainMenu.ToolMenu.ExternalTools.ExecutionFailed} '" + command + " " + args + "'\n" + ex.Message);
}
}
void ProcessExitEvent(object sender, EventArgs e)
{
WorkbenchSingleton.SafeThreadAsyncCall(
delegate {
ProcessRunner p = (ProcessRunner)sender;
TaskService.BuildMessageViewCategory.AppendLine(StringParser.Parse("${res:XML.MainMenu.ToolMenu.ExternalTools.ExitedWithCode} " + p.ExitCode));
p.Dispose();
});
}
void process_OutputLineReceived(object sender, LineReceivedEventArgs e)
{
TaskService.BuildMessageViewCategory.AppendLine(e.Line);
}
}
public class OpenContentsMenuBuilder : IMenuItemBuilder
{
public ICollection BuildItems(Codon codon, object owner)
{
int windowCount = WorkbenchSingleton.Workbench.WorkbenchWindowCollection.Count;
if (windowCount == 0) {
return new object[] {};
}
var items = new object[windowCount + 1];
items[0] = new System.Windows.Controls.Separator();
for (int i = 0; i < windowCount; ++i) {
IWorkbenchWindow window = WorkbenchSingleton.Workbench.WorkbenchWindowCollection[i];
var item = new System.Windows.Controls.MenuItem() {
IsChecked = WorkbenchSingleton.Workbench.ActiveWorkbenchWindow == window,
IsCheckable = true,
Header = StringParser.Parse(window.Title)
};
item.Click += delegate {
window.SelectWindow();
};
items[i + 1] = item;
}
return items;
}
}
// public class IncludeFilesBuilder : ISubmenuBuilder
// {
// public ProjectBrowserView browser;
//
// MyMenuItem includeInCompileItem;
// MyMenuItem includeInDeployItem;
//
// class MyMenuItem : MenuCheckBox
// {
// IncludeFilesBuilder builder;
//
// public MyMenuItem(IncludeFilesBuilder builder, string name, EventHandler handler) : base(null, null, name)
// {
// base.Click += handler;
// this.builder = builder;
// }
//
// public override void UpdateStatus()
// {
// base.UpdateStatus();
// if (builder == null) {
// return;
// }
// AbstractBrowserNode node = builder.browser.SelectedNode as AbstractBrowserNode;
//
// if (node == null) {
// return;
// }
//
// ProjectFile finfo = node.UserData as ProjectFile;
// if (finfo == null) {
// builder.includeInCompileItem.Enabled = builder.includeInCompileItem.Enabled = false;
// } else {
// if (!builder.includeInCompileItem.Enabled) {
// builder.includeInCompileItem.Enabled = builder.includeInCompileItem.Enabled = true;
// }
// builder.includeInCompileItem.Checked = finfo.BuildAction == BuildAction.Compile;
// builder.includeInDeployItem.Checked = !node.Project.DeployInformation.IsFileExcluded(finfo.Name);
// }
// }
// }
//
// public ToolStripItem[] BuildSubmenu(Codon codon, object owner)
// {
// browser = (ProjectBrowserView)owner;
// includeInCompileItem = new MyMenuItem(this, "${res:ProjectComponent.ContextMenu.IncludeMenu.InCompile}", new EventHandler(ChangeCompileInclude));
// includeInDeployItem = new MyMenuItem(this, "${res:ProjectComponent.ContextMenu.IncludeMenu.InDeploy}", new EventHandler(ChangeDeployInclude));
//
// return new ToolStripItem[] {
// includeInCompileItem,
// includeInDeployItem
// };
//
// }
// void ChangeCompileInclude(object sender, EventArgs e)
// {
// AbstractBrowserNode node = browser.SelectedNode as AbstractBrowserNode;
//
// if (node == null) {
// return;
// }
//
// ProjectFile finfo = node.UserData as ProjectFile;
// if (finfo != null) {
// if (finfo.BuildAction == BuildAction.Compile) {
// finfo.BuildAction = BuildAction.Nothing;
// } else {
// finfo.BuildAction = BuildAction.Compile;
// }
// }
//
// ProjectService.SaveCombine();
// }
//
// void ChangeDeployInclude(object sender, EventArgs e)
// {
// AbstractBrowserNode node = browser.SelectedNode as AbstractBrowserNode;
//
// if (node == null) {
// return;
// }
//
// ProjectFile finfo = node.UserData as ProjectFile;
// if (finfo != null) {
// if (node.Project.DeployInformation.IsFileExcluded(finfo.Name)) {
// node.Project.DeployInformation.RemoveExcludedFile(finfo.Name);
// } else {
// node.Project.DeployInformation.AddExcludedFile(finfo.Name);
// }
// }
//
// ProjectService.SaveCombine();
// }
// }
public class ToolsViewMenuBuilder : ViewMenuBuilder
{
protected override string Category {
get {
return "Tools";
}
}
}
public class MainViewMenuBuilder : ViewMenuBuilder
{
protected override string Category {
get {
return "Main";
}
}
}
public class DebugViewMenuBuilder : ViewMenuBuilder
{
protected override string Category {
get {
return "Debugger";
}
}
}
public abstract class ViewMenuBuilder : IMenuItemBuilder
{
class BringPadToFrontCommand : System.Windows.Input.ICommand
{
PadDescriptor padDescriptor;
public BringPadToFrontCommand(PadDescriptor padDescriptor)
{
this.padDescriptor = padDescriptor;
}
public event EventHandler CanExecuteChanged { add {} remove {} }
public void Execute(object parameter)
{
padDescriptor.BringPadToFront();
}
public bool CanExecute(object parameter)
{
return true;
}
}
protected abstract string Category {
get;
}
public List<string> bindingsAssigned = new List<string>();
public ICollection BuildItems(Codon codon, object owner)
{
ArrayList list = new ArrayList();
foreach (PadDescriptor padContent in WorkbenchSingleton.Workbench.PadContentCollection) {
if (padContent.Category == Category) {
var item = new System.Windows.Controls.MenuItem();
item.Header = ICSharpCode.Core.Presentation.MenuService.ConvertLabel(StringParser.Parse(padContent.Title));
if (!string.IsNullOrEmpty(padContent.Icon)) {
item.Icon = PresentationResourceService.GetPixelSnappedImage(padContent.Icon);
}
var routedCommandName = "SDViewCommands.ShowView_" + padContent.Class;
var routedCommandText = MenuService.ConvertLabel(StringParser.Parse(padContent.Title));
// TODO: fix this hack
if(!bindingsAssigned.Contains(routedCommandName)) {
var addIn = AddInTree.AddIns.FirstOrDefault(a => a.Name == "SharpDevelop");
// Dynamicaly create routed UI command to loaded pad and bindings for it
SDCommandManager.RegisterRoutedUICommand(routedCommandName, routedCommandText);
SDCommandManager.LoadCommand(routedCommandName, new BringPadToFrontCommand(padContent));
var commandBindingInfo = new CommandBindingInfo();
commandBindingInfo.CommandTypeName = routedCommandName;
commandBindingInfo.OwnerTypeName = SDCommandManager.DefaultOwnerTypeName;
commandBindingInfo.RoutedCommandName = routedCommandName;
commandBindingInfo.AddIn = addIn;
SDCommandManager.RegisterCommandBindingInfo(commandBindingInfo);
var gestures = (InputGestureCollection)new InputGestureCollectionConverter().ConvertFromString(padContent.Shortcut);
var inputBindingInfo = new InputBindingInfo();
inputBindingInfo.OwnerTypeName = SDCommandManager.DefaultOwnerTypeName;
inputBindingInfo.RoutedCommandName = routedCommandName;
inputBindingInfo.DefaultGestures.AddRange(gestures);
var categoryPath = "/MainMenu/View" + (Category == padContent.Category && padContent.Category != "Main" ? "/" + padContent.Class : "");
var category = ICSharpCode.Core.Presentation.CommandManager.GetInputBindingCategory(categoryPath, false);
if(category == null) {
category = new InputBindingCategory(categoryPath, padContent.Category);
ICSharpCode.Core.Presentation.CommandManager.RegisterInputBindingCategory(category);
}
inputBindingInfo.Categories.Add(category);
inputBindingInfo.AddIn = addIn;
SDCommandManager.RegisterInputBindingInfo(inputBindingInfo);
bindingsAssigned.Add(routedCommandName);
}
item.Command = SDCommandManager.GetRoutedUICommand(routedCommandName);
var gesturesTemplate = BindingInfoTemplate.Create(null, SDCommandManager.DefaultOwnerTypeName, routedCommandName);
var updatedGestures = SDCommandManager.FindInputGestures(gesturesTemplate);
var updatedGesturesText = (string)new InputGestureCollectionConverter().ConvertToInvariantString(updatedGestures);
item.InputGestureText = updatedGesturesText;
list.Add(item);
}
}
return list;
}
}
}