diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs index 0ea7f499351..375777f11c0 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/CommandSet.cs @@ -61,15 +61,11 @@ public CommandSet(ISite site) this.site = site; _eventService = site.GetRequiredService(); + _eventService.EventHandlerChanged += OnEventHandlerChanged; - _eventService.EventHandlerChanged += new EventHandler(OnEventHandlerChanged); - - IDesignerHost? host = site.GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); - - if (host is not null) + if (site.TryGetService(out IDesignerHost? host)) { - host.Activated += new EventHandler(UpdateClipboardItems); + host.Activated += UpdateClipboardItems; } _statusCommandUI = new StatusCommandUI(site); @@ -77,7 +73,6 @@ public CommandSet(ISite site) _uiService = site.GetService(); // Establish our set of commands - // _commandSet = [ // Editing commands @@ -367,27 +362,25 @@ public virtual void Dispose() if (SelectionService is not null) { - SelectionService.SelectionChanged -= new EventHandler(OnSelectionChanged); + SelectionService.SelectionChanged -= OnSelectionChanged; SelectionService = null; } if (_eventService is not null) { - _eventService.EventHandlerChanged -= new EventHandler(OnEventHandlerChanged); + _eventService.EventHandlerChanged -= OnEventHandlerChanged; _eventService = null!; } - IDesignerHost? host = site.GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); - if (host is not null) + if (site.TryGetService(out IDesignerHost? host)) { - host.Activated -= new EventHandler(UpdateClipboardItems); + host.Activated -= UpdateClipboardItems; } if (_snapLineTimer is not null) { _snapLineTimer.Stop(); - _snapLineTimer.Tick -= new EventHandler(OnSnapLineTimerExpire); + _snapLineTimer.Tick -= OnSnapLineTimerExpire; _snapLineTimer = null; } @@ -986,14 +979,10 @@ protected void OnMenuAlignByPrimary(object? sender, EventArgs e) Cursor.Current = Cursors.WaitCursor; // Now loop through each of the components. - // ICollection comps = SelectionService.GetSelectedComponents(); - // Inform the designer that we are about to monkey with a ton - // of properties. - // + // Inform the designer that we are about to monkey with a ton of properties. IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); DesignerTransaction? trans = null; try { @@ -1008,7 +997,7 @@ protected void OnMenuAlignByPrimary(object? sender, EventArgs e) continue; } - if (host is not null && host.GetDesigner(comp) is not ControlDesigner) + if (host?.GetDesigner(comp) is not ControlDesigner) { continue; } @@ -1020,7 +1009,6 @@ protected void OnMenuAlignByPrimary(object? sender, EventArgs e) PropertyDescriptor? lockProp = props["Locked"]; // Skip all components that are locked - // if (lockProp is not null) { if ((bool)lockProp.GetValue(comp)!) @@ -1028,19 +1016,16 @@ protected void OnMenuAlignByPrimary(object? sender, EventArgs e) } // Skip all components that don't have a location property - // if (locProp is null || locProp.IsReadOnly) { continue; } - // Skip all components that don't have size if we're - // doing a size operation. - // - if (id.Equals(StandardCommands.AlignBottom) || - id.Equals(StandardCommands.AlignHorizontalCenters) || - id.Equals(StandardCommands.AlignVerticalCenters) || - id.Equals(StandardCommands.AlignRight)) + // Skip all components that don't have size if we're doing a size operation. + if (id.Equals(StandardCommands.AlignBottom) + || id.Equals(StandardCommands.AlignHorizontalCenters) + || id.Equals(StandardCommands.AlignVerticalCenters) + || id.Equals(StandardCommands.AlignRight)) { if (sizeProp is null || sizeProp.IsReadOnly) { @@ -1143,7 +1128,6 @@ protected void OnMenuAlignToGrid(object? sender, EventArgs e) ICollection selectedComponents = SelectionService.GetSelectedComponents(); IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); DesignerTransaction? trans = null; try @@ -1169,7 +1153,8 @@ protected void OnMenuAlignToGrid(object? sender, EventArgs e) } bool firstTry = true; - // for each component, we round to the nearest snap offset for x and y + + // For each component, we round to the nearest snap offset for x and y. foreach (IComponent comp in selectedComponents) { // first check to see if the component is locked, if so - don't move it... @@ -1266,7 +1251,6 @@ protected void OnMenuCenterSelection(object? sender, EventArgs e) Control? viewParent = null; IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); DesignerTransaction? trans = null; try @@ -1280,8 +1264,6 @@ protected void OnMenuCenterSelection(object? sender, EventArgs e) trans = host.CreateTransaction(batchString); } - // subhag calculate the union REctangle : ASURT 67753 - // int top = int.MaxValue; int left = int.MaxValue; int right = int.MinValue; @@ -1297,14 +1279,12 @@ protected void OnMenuCenterSelection(object? sender, EventArgs e) PropertyDescriptor? sizeProp = props["Size"]; // Skip all components that don't have location and size properties - // if (locProp is null || sizeProp is null || locProp.IsReadOnly || sizeProp.IsReadOnly) { continue; } - // Also, skip all locked components... - // + // Also, skip all locked components. PropertyDescriptor? lockProp = props["Locked"]; if (lockProp is not null && (bool)lockProp.GetValue(comp)!) { @@ -1598,254 +1578,239 @@ protected void OnMenuCut(object? sender, EventArgs e) /// protected void OnMenuDelete(object? sender, EventArgs e) { + if (site is null || SelectionService is null || !TryGetService(out IDesignerHost? host)) + { + return; + } + Cursor? oldCursor = Cursor.Current; try { Cursor.Current = Cursors.WaitCursor; - if (site is not null) - { - IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); - if (SelectionService is null) - { - return; - } + IComponentChangeService? changeService = GetService(); - if (host is not null) - { - IComponentChangeService? changeService = GetService(); + ICollection comps = SelectionService.GetSelectedComponents(); + string desc = string.Format(SR.CommandSetDelete, comps.Count); - ICollection comps = SelectionService.GetSelectedComponents(); - string desc = string.Format(SR.CommandSetDelete, comps.Count); + DesignerTransaction? trans = null; + IComponent? commonParent = null; + bool commonParentSet = false; + List designerList = []; - DesignerTransaction? trans = null; - IComponent? commonParent = null; - bool commonParentSet = false; - List designerList = []; - try + try + { + trans = host.CreateTransaction(desc); + SelectionService.SetSelectedComponents(Array.Empty(), SelectionTypes.Replace); + foreach (object obj in comps) + { + if (obj is not IComponent comp || comp.Site is null) { - trans = host.CreateTransaction(desc); - SelectionService.SetSelectedComponents(Array.Empty(), SelectionTypes.Replace); - foreach (object obj in comps) + continue; + } + + // Perf: Suspend ComponentChanging Events on parent for bulk changes to avoid unnecessary + // serialization\deserialization for undo. + if (obj is Control c) + { + Control? parent = c.Parent; + if (parent is not null) { - if (obj is not IComponent comp || comp.Site is null) + if (host.GetDesigner(parent) is ParentControlDesigner designer + && !designerList.Contains(designer)) { - continue; + designer.SuspendChangingEvents(); + designerList.Add(designer); + designer.ForceComponentChanging(); } + } + } + } + + foreach (object obj in comps) + { + // If it's not a component, we can't delete it. It also may have already been deleted + // as part of a parent operation, so we skip it. + if (obj is not IComponent c || c.Site is null) + { + continue; + } + + // We should never delete the base component. + if (obj == host.RootComponent) + { + continue; + } - // Perf: We suspend Component Changing Events on parent for bulk changes to avoid unnecessary serialization\deserialization for undo - // see bug 488115 - if (obj is Control c) + if (!commonParentSet) + { + if (obj is Control control) + { + commonParent = control.Parent; + } + else + { + // If this is not a Control, see if we can get an ITreeDesigner from it, + // and figure out the Component from that. + if (host.GetDesigner((IComponent)obj) is ITreeDesigner designer) { - Control? parent = c.Parent; - if (parent is not null) + IDesigner? parentDesigner = designer.Parent; + if (parentDesigner is not null) { - if (host.GetDesigner(parent) is ParentControlDesigner designer - && !designerList.Contains(designer)) - { - designer.SuspendChangingEvents(); - designerList.Add(designer); - designer.ForceComponentChanging(); - } + commonParent = parentDesigner.Component; } } } - foreach (object obj in comps) + commonParentSet = (commonParent is not null); + } + else if (commonParent is not null) + { + if (obj is Control selectedControl && commonParent is Control controlCommonParent) { - // If it's not a component, we can't delete it. It also may have already been deleted - // as part of a parent operation, so we skip it. - // - if (obj is not IComponent c || c.Site is null) + if (selectedControl.Parent != controlCommonParent && !controlCommonParent.Contains(selectedControl)) { - continue; - } - - // We should never delete the base component. - // - if (obj == host.RootComponent) - { - continue; - } - - if (!commonParentSet) - { - if (obj is Control control) + // look for internal parenting + if (selectedControl == controlCommonParent || selectedControl.Contains(controlCommonParent)) { - commonParent = control.Parent; + commonParent = selectedControl.Parent; } else { - // if this is not a Control, see if we can get an ITreeDesigner from it, - // and figure out the Component from that. - // - if (host.GetDesigner((IComponent)obj) is ITreeDesigner designer) + Control? parent = controlCommonParent; + // start walking up until we find a common parent + while (parent is not null && !parent.Contains(selectedControl)) { - IDesigner? parentDesigner = designer.Parent; - if (parentDesigner is not null) - { - commonParent = parentDesigner.Component; - } + parent = parent.Parent; } - } - commonParentSet = (commonParent is not null); + commonParent = parent; + } } - else if (commonParent is not null) + } + else + { + // For these we aren't as thorough as we are with the Control-based ones. + // we just walk up the chain until we find that parent or the root component. + if (host.GetDesigner(c) is ITreeDesigner designer && host.GetDesigner(commonParent) is ITreeDesigner commonParentDesigner && designer.Parent != commonParentDesigner) { - if (obj is Control selectedControl && commonParent is Control controlCommonParent) + // Walk the chain of designers from the current parent designer + // up to the root component, and for the current component designer. + static List GetDesignerChain(ITreeDesigner designer) { - if (selectedControl.Parent != controlCommonParent && !controlCommonParent.Contains(selectedControl)) + List designerChain = []; + while (designer.Parent is ITreeDesigner parent) { - // look for internal parenting - if (selectedControl == controlCommonParent || selectedControl.Contains(controlCommonParent)) - { - commonParent = selectedControl.Parent; - } - else - { - Control? parent = controlCommonParent; - // start walking up until we find a common parent - while (parent is not null && !parent.Contains(selectedControl)) - { - parent = parent.Parent; - } - - commonParent = parent; - } + designerChain.Add(parent); + designer = parent; } + + return designerChain; } - else - { - // for these we aren't as thorough as we are with the Control-based ones. - // we just walk up the chain until we find that parent or the root component. - // - if (host.GetDesigner(c) is ITreeDesigner designer && host.GetDesigner(commonParent) is ITreeDesigner commonParentDesigner && designer.Parent != commonParentDesigner) - { - // walk the chain of designers from the current parent designer - // up to the root component, and for the current component designer. - // - static List GetDesignerChain(ITreeDesigner designer) - { - List designerChain = []; - while (designer.Parent is ITreeDesigner parent) - { - designerChain.Add(parent); - designer = parent; - } - - return designerChain; - } - List designerChain = GetDesignerChain(designer); - List parentDesignerChain = GetDesignerChain(commonParentDesigner); + List designerChain = GetDesignerChain(designer); + List parentDesignerChain = GetDesignerChain(commonParentDesigner); - // now that we've got the trees built up, start comparing them from the ends to see where - // they diverge. - // - List shorterList = designerChain.Count < parentDesignerChain.Count ? designerChain : parentDesignerChain; - List longerList = (shorterList == designerChain ? parentDesignerChain : designerChain); - ITreeDesigner? commonDesigner = null; + // Now that we've got the trees built up, start comparing them from the ends to see where + // they diverge. + List shorterList = designerChain.Count < parentDesignerChain.Count ? designerChain : parentDesignerChain; + List longerList = (shorterList == designerChain ? parentDesignerChain : designerChain); + ITreeDesigner? commonDesigner = null; - if (shorterList.Count > 0 && longerList.Count > 0) + if (shorterList.Count > 0 && longerList.Count > 0) + { + int shortIndex = Math.Max(0, shorterList.Count - 1); + int longIndex = Math.Max(0, longerList.Count - 1); + while (shortIndex >= 0 && longIndex >= 0) + { + if (shorterList[shortIndex] != longerList[longIndex]) { - int shortIndex = Math.Max(0, shorterList.Count - 1); - int longIndex = Math.Max(0, longerList.Count - 1); - while (shortIndex >= 0 && longIndex >= 0) - { - if (shorterList[shortIndex] != longerList[longIndex]) - { - break; - } - - commonDesigner = shorterList[shortIndex]; - shortIndex--; - longIndex--; - } + break; } - // alright, what have we got? - commonParent = commonDesigner?.Component; + commonDesigner = shorterList[shortIndex]; + shortIndex--; + longIndex--; } } - } - if (changeService is not null) - { - List al = []; - GetAssociatedComponents(c, host, al); - foreach (IComponent comp in al) - { - changeService.OnComponentChanging(comp, null); - } + // alright, what have we got? + commonParent = commonDesigner?.Component; } - - host.DestroyComponent((IComponent)obj); } } - finally - { - trans?.Commit(); - foreach (ParentControlDesigner des in designerList) - { - des.ResumeChangingEvents(); - } - } - - if (commonParent is not null && SelectionService.PrimarySelection is null) + if (changeService is not null) { - if (host.GetDesigner(commonParent) is ITreeDesigner { Children: not null } commonParentDesigner) + List al = []; + GetAssociatedComponents(c, host, al); + foreach (IComponent comp in al) { - // choose the first child of the common parent if it has any. - // - foreach (IDesigner designer in commonParentDesigner.Children) - { - IComponent component = designer.Component; - if (component.Site is not null) - { - commonParent = component; - break; - } - } + changeService.OnComponentChanging(comp, null); } - else if (commonParent is Control controlCommonParent) - { - // if we have a common parent, select it's first child - // - if (controlCommonParent.Controls.Count > 0) - { - Control? parent = controlCommonParent.Controls[0]; + } - // 126240 -- make sure we've got a sited thing. - // - while (parent is not null && parent.Site is null) - { - parent = parent.Parent; - } + host.DestroyComponent((IComponent)obj); + } + } + finally + { + trans?.Commit(); - commonParent = parent; - } - } + foreach (ParentControlDesigner des in designerList) + { + des.ResumeChangingEvents(); + } + } - if (commonParent is not null) - { - SelectionService.SetSelectedComponents(new object[] { commonParent }, SelectionTypes.Replace); - } - else + if (commonParent is not null && SelectionService.PrimarySelection is null) + { + if (host.GetDesigner(commonParent) is ITreeDesigner { Children: not null } commonParentDesigner) + { + // Choose the first child of the common parent if it has any. + foreach (IDesigner designer in commonParentDesigner.Children) + { + IComponent component = designer.Component; + if (component.Site is not null) { - SelectionService.SetSelectedComponents(new object[] { host.RootComponent }, SelectionTypes.Replace); + commonParent = component; + break; } } - else + } + else if (commonParent is Control controlCommonParent) + { + // If we have a common parent, select it's first child. + if (controlCommonParent.Controls.Count > 0) { - if (SelectionService.PrimarySelection is null) + Control? parent = controlCommonParent.Controls[0]; + + // 126240 -- make sure we've got a sited thing. + // + while (parent is not null && parent.Site is null) { - SelectionService.SetSelectedComponents(new object[] { host.RootComponent }, SelectionTypes.Replace); + parent = parent.Parent; } + + commonParent = parent; } } + + if (commonParent is not null) + { + SelectionService.SetSelectedComponents(new object[] { commonParent }, SelectionTypes.Replace); + } + else + { + SelectionService.SetSelectedComponents(new object[] { host.RootComponent }, SelectionTypes.Replace); + } + } + else + { + if (SelectionService.PrimarySelection is null) + { + SelectionService.SetSelectedComponents(new object[] { host.RootComponent }, SelectionTypes.Replace); + } } } finally @@ -1871,10 +1836,10 @@ protected void OnMenuPaste(object? sender, EventArgs e) // Refer VsWhidbey : 477583 ICollection? associatedCompsOfFailedControl = null; - IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); - if (host is null) - return; // nothing we can do here! + if (!TryGetService(out IDesignerHost? host)) + { + return; + } bool clipboardOperationSuccessful = ExecuteSafely(Clipboard.GetDataObject, false, out IDataObject? dataObj); @@ -2223,47 +2188,40 @@ protected void OnMenuPaste(object? sender, EventArgs e) /// protected void OnMenuSelectAll(object? sender, EventArgs e) { + if (site is null || SelectionService is null || !TryGetService(out IDesignerHost? host)) + { + Debug.Assert(SelectionService is not null, "We need the SelectionService, but we can't find it!"); + return; + } + Cursor? oldCursor = Cursor.Current; try { Cursor.Current = Cursors.WaitCursor; - if (site is not null) - { - Debug.Assert(SelectionService is not null, "We need the SelectionService, but we can't find it!"); - if (SelectionService is null) - { - return; - } - IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); + ComponentCollection components = host.Container.Components; + IComponent[] selComps; - if (host is not null) + if (components is null || components.Count == 0) + { + selComps = []; + } + else + { + selComps = new IComponent[components.Count - 1]; + IComponent baseComp = host.RootComponent; + + int j = 0; + foreach (IComponent comp in components) { - ComponentCollection components = host.Container.Components; - IComponent[] selComps; - if (components is null || components.Count == 0) - { - selComps = []; - } - else + if (baseComp != comp) { - selComps = new IComponent[components.Count - 1]; - IComponent baseComp = host.RootComponent; - - int j = 0; - foreach (IComponent comp in components) - { - if (baseComp != comp) - { - selComps[j++] = comp; - } - } + selComps[j++] = comp; } - - SelectionService.SetSelectedComponents(selComps, SelectionTypes.Replace); } } + + SelectionService.SetSelectedComponents(selComps, SelectionTypes.Replace); } finally { @@ -2276,37 +2234,33 @@ protected void OnMenuSelectAll(object? sender, EventArgs e) /// protected void OnMenuShowGrid(object? sender, EventArgs e) { - if (site is not null) + if (site is null || !TryGetService(out IDesignerHost? host)) { - IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); + return; + } - if (host is not null) - { - DesignerTransaction? trans = null; + DesignerTransaction? trans = null; - try - { - trans = host.CreateTransaction(); + try + { + trans = host.CreateTransaction(); - IComponent baseComponent = host.RootComponent; - if (baseComponent is Control) - { - PropertyDescriptor? prop = GetProperty(baseComponent, "DrawGrid"); - if (prop is not null) - { - bool drawGrid = (bool)prop.GetValue(baseComponent)!; - prop.SetValue(baseComponent, !drawGrid); - ((MenuCommand)sender!).Checked = !drawGrid; - } - } - } - finally + IComponent baseComponent = host.RootComponent; + if (baseComponent is Control) + { + PropertyDescriptor? prop = GetProperty(baseComponent, "DrawGrid"); + if (prop is not null) { - trans?.Commit(); + bool drawGrid = (bool)prop.GetValue(baseComponent)!; + prop.SetValue(baseComponent, !drawGrid); + ((MenuCommand)sender!).Checked = !drawGrid; } } } + finally + { + trans?.Commit(); + } } /// @@ -2355,7 +2309,6 @@ protected void OnMenuSizingCommand(object? sender, EventArgs e) Debug.Assert(selectedObjects is not null, "queryStatus should have disabled this"); IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); DesignerTransaction? trans = null; try @@ -2423,7 +2376,6 @@ protected void OnMenuSizeToGrid(object? sender, EventArgs e) Cursor? oldCursor = Cursor.Current; IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); DesignerTransaction? trans = null; try @@ -2562,7 +2514,6 @@ protected void OnMenuSpacingCommand(object? sender, EventArgs e) Cursor? oldCursor = Cursor.Current; IDesignerHost? host = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); try { @@ -3034,29 +2985,25 @@ protected void OnStatusCopy(object? sender, EventArgs e) MenuCommand cmd = (MenuCommand)sender!; bool enable = false; - if (!_selectionInherited && TryGetService(out IDesignerHost? host) && !host.Loading) + if (!_selectionInherited + && TryGetService(out IDesignerHost? host) + && !host.Loading + && TryGetService(out ISelectionService? selSvc)) { - ISelectionService? selSvc = GetService(); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || selSvc is not null, "ISelectionService not found"); + // There must also be a component in the mix, and not the base component + ICollection selectedComponents = selSvc.GetSelectedComponents(); + object baseComp = host.RootComponent; - if (selSvc is not null) + if (!selSvc.GetComponentSelected(baseComp)) { - // There must also be a component in the mix, and not the base component - // - ICollection selectedComponents = selSvc.GetSelectedComponents(); - - object baseComp = host.RootComponent; - if (!selSvc.GetComponentSelected(baseComp)) + foreach (object obj in selectedComponents) { - foreach (object obj in selectedComponents) + // if the object is not sited to the same thing as the host container + // then don't allow copy. VSWhidbey# 275790 + if (obj is IComponent { Site: { } objSite } && objSite.Container == host.Container) { - // if the object is not sited to the same thing as the host container - // then don't allow copy. VSWhidbey# 275790 - if (obj is IComponent { Site: { } objSite } && objSite.Container == host.Container) - { - enable = true; - break; - } + enable = true; + break; } } } @@ -3115,53 +3062,32 @@ protected void OnStatusDelete(object? sender, EventArgs e) } } -#if UNUSED - - // Let's keep this in case we need it in the future - /// - /// Determines the status of a menu command. Commands with this event are - /// considered to be not yet implemented and are disabled. - /// - protected void OnStatusNYI(object? sender, EventArgs e) { - MenuCommand cmd = (MenuCommand)sender!; - cmd.Enabled = false; - } -#endif - - /// - /// Determines the status of a menu command. Commands with this event are - /// enabled when there is something yummy on the clipboard. + /// Determines the status of a menu command. Commands with this event are + /// enabled when there is something useful on the clipboard. /// protected void OnStatusPaste(object? sender, EventArgs e) { MenuCommand cmd = (MenuCommand)sender!; - IDesignerHost? host = GetService(); // Before we even look at the data format, check to see if the thing we're going to paste // into is privately inherited. If it is, then we definitely cannot paste. - // - if (primarySelection is not null) + if (TryGetService(out IDesignerHost? host) + && primarySelection is not null + && host.GetDesigner(primarySelection) is ParentControlDesigner) { - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); - - if (host?.GetDesigner(primarySelection) is ParentControlDesigner) + // This component is a target for our paste operation. We must ensure + // that it is not privately inherited. + InheritanceAttribute? attr = (InheritanceAttribute?)TypeDescriptor.GetAttributes(primarySelection)[typeof(InheritanceAttribute)]; + Debug.Assert(attr is not null, "Type descriptor gave us a null attribute -- problem in type descriptor"); + if (attr.InheritanceLevel == InheritanceLevel.InheritedReadOnly) { - // This component is a target for our paste operation. We must ensure - // that it is not privately inherited. - // - InheritanceAttribute? attr = (InheritanceAttribute?)TypeDescriptor.GetAttributes(primarySelection)[typeof(InheritanceAttribute)]; - Debug.Assert(attr is not null, "Type descriptor gave us a null attribute -- problem in type descriptor"); - if (attr.InheritanceLevel == InheritanceLevel.InheritedReadOnly) - { - cmd.Enabled = false; - return; - } + cmd.Enabled = false; + return; } } // Not being inherited. Now look at the contents of the data - // bool clipboardOperationSuccessful = ExecuteSafely(Clipboard.GetDataObject, false, out IDataObject? dataObj); bool enable = false; @@ -3175,10 +3101,9 @@ protected void OnStatusPaste(object? sender, EventArgs e) else { // Not ours, check to see if the toolbox service understands this - // if (TryGetService(out IToolboxService? ts)) { - enable = (host is not null ? ts.IsSupported(dataObj, host) : ts.IsToolboxItem(dataObj)); + enable = host is not null ? ts.IsSupported(dataObj, host) : ts.IsToolboxItem(dataObj); } } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs index 7e58b40e533..54e7d49ad14 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ComponentTray.cs @@ -239,6 +239,7 @@ private void OnSelectionChanged(object sender, EventArgs e) object primary = ((ISelectionService)sender).PrimarySelection; Invalidate(); _fSelectionChanged = true; + // Accessibility information foreach (object selObj in _selectedObjects) { @@ -247,7 +248,6 @@ private void OnSelectionChanged(object sender, EventArgs e) Control c = TrayControl.FromComponent(component); if (c is not null) { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"MSAA: SelectionAdd, traycontrol = {c}"); PInvoke.NotifyWinEvent( (uint)AccessibleEvents.SelectionAdd, c, @@ -847,7 +847,6 @@ protected override void Dispose(bool disposing) if (disposing && _controls is not null) { IExtenderProviderService es = (IExtenderProviderService)GetService(typeof(IExtenderProviderService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (es is not null), "IExtenderProviderService not found"); es?.RemoveExtenderProvider(this); IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); @@ -863,12 +862,12 @@ protected override void Dispose(bool disposing) IComponentChangeService componentChangeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); if (componentChangeService is not null) { - componentChangeService.ComponentRemoved -= new ComponentEventHandler(OnComponentRemoved); + componentChangeService.ComponentRemoved -= OnComponentRemoved; } - SystemEvents.DisplaySettingsChanged -= new EventHandler(OnSystemSettingChanged); - SystemEvents.InstalledFontsChanged -= new EventHandler(OnSystemSettingChanged); - SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); + SystemEvents.DisplaySettingsChanged -= OnSystemSettingChanged; + SystemEvents.InstalledFontsChanged -= OnSystemSettingChanged; + SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged; IMenuCommandService mcs = MenuService; if (mcs is not null) { @@ -1034,7 +1033,6 @@ protected override void OnMouseDoubleClick(MouseEventArgs e) { OnLostCapture(); IEventBindingService eps = (IEventBindingService)GetService(typeof(IEventBindingService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (eps is not null), "IEventBindingService not found"); eps?.ShowCode(); } } @@ -1055,14 +1053,15 @@ protected override void OnGiveFeedback(GiveFeedbackEventArgs gfevent) /// protected override void OnDragDrop(DragEventArgs de) { - // This will be used once during PositionComponent to place the component at the drop point. It is automatically set to null afterwards, so further components appear after the first one dropped. + // This will be used once during PositionComponent to place the component at the drop point. It is automatically + // set to null afterwards, so further components appear after the first one dropped. _mouseDropLocation = PointToClient(new Point(de.X, de.Y)); - _autoScrollPosBeforeDragging = AutoScrollPosition; // save the scroll position + _autoScrollPosBeforeDragging = AutoScrollPosition; + if (_mouseDragTool is not null) { ToolboxItem tool = _mouseDragTool; _mouseDragTool = null; - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (GetService(typeof(IDesignerHost)) is not null), "IDesignerHost not found"); try { IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); @@ -1257,7 +1256,6 @@ protected override void OnMouseDown(MouseEventArgs e) try { ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (ss is not null), "ISelectionService not found"); ss?.SetSelectedComponents(new object[] { _mainDesigner.Component }); } catch (Exception ex) when (!ex.IsCriticalException()) @@ -1345,7 +1343,6 @@ protected override void OnMouseUp(MouseEventArgs e) try { ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (ss is not null), "ISelectionService not found"); ss?.SetSelectedComponents(comps); } catch (Exception ex) when (!ex.IsCriticalException()) @@ -1905,10 +1902,9 @@ public TrayControl(ComponentTray tray, IComponent component) UpdateIconInfo(); IComponentChangeService cs = (IComponentChangeService)tray.GetService(typeof(IComponentChangeService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (cs is not null), "IComponentChangeService not found"); if (cs is not null) { - cs.ComponentRename += new ComponentRenameEventHandler(OnComponentRename); + cs.ComponentRename += OnComponentRename; } ISite site = component.Site; @@ -2003,16 +1999,15 @@ protected override void Dispose(bool disposing) ISite site = _component.Site; if (site is not null) { - IComponentChangeService cs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (cs is not null), "IComponentChangeService not found"); - if (cs is not null) + if (site.TryGetService(out IComponentChangeService cs)) { - cs.ComponentRename -= new ComponentRenameEventHandler(OnComponentRename); + cs.ComponentRename -= OnComponentRename; } - IDictionaryService ds = (IDictionaryService)site.GetService(typeof(IDictionaryService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (ds is not null), "IDictionaryService not found"); - ds?.SetValue(typeof(TrayControl), null); + if (site.TryGetService(out IDictionaryService ds)) + { + ds.SetValue(typeof(TrayControl), null); + } } } @@ -2024,24 +2019,17 @@ protected override void Dispose(bool disposing) /// public static TrayControl FromComponent(IComponent component) { - TrayControl c = null; if (component is null) { return null; } - ISite site = component.Site; - if (site is not null) + if (component.Site.TryGetService(out IDictionaryService ds)) { - IDictionaryService ds = (IDictionaryService)site.GetService(typeof(IDictionaryService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (ds is not null), "IDictionaryService not found"); - if (ds is not null) - { - c = (TrayControl)ds.GetValue(typeof(TrayControl)); - } + return (TrayControl)ds.GetValue(typeof(TrayControl)); } - return c; + return null; } /// @@ -2131,23 +2119,27 @@ private void OnEndDrag(bool cancel) protected override void OnMouseDown(MouseEventArgs me) { base.OnMouseDown(me); - if (!_tray.TabOrderActive) + if (_tray.TabOrderActive) { - _tray.FocusDesigner(); - // If this is the left mouse button, then begin a drag. - if (me.Button == MouseButtons.Left) + return; + } + + _tray.FocusDesigner(); + + // If this is the left mouse button, then begin a drag. + if (me.Button == MouseButtons.Left) + { + Capture = true; + _mouseDragLast = PointToScreen(new Point(me.X, me.Y)); + + // If the CTRL key isn't down, select this component, otherwise, we wait until the mouse up. + // Make sure the component is selected. + _ctrlSelect = PInvoke.GetKeyState((int)Keys.ControlKey) != 0; + if (!_ctrlSelect) { - Capture = true; - _mouseDragLast = PointToScreen(new Point(me.X, me.Y)); - // If the CTRL key isn't down, select this component, otherwise, we wait until the mouse up. Make sure the component is selected - _ctrlSelect = PInvoke.GetKeyState((int)Keys.ControlKey) != 0; - if (!_ctrlSelect) - { - ISelectionService sel = (ISelectionService)_tray.GetService(typeof(ISelectionService)); - // Make sure the component is selected - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (sel is not null), "ISelectionService not found"); - sel?.SetSelectedComponents(new object[] { Component }, SelectionTypes.Primary); - } + ISelectionService sel = (ISelectionService)_tray.GetService(typeof(ISelectionService)); + // Make sure the component is selected + sel?.SetSelectedComponents(new object[] { Component }, SelectionTypes.Primary); } } } @@ -2443,7 +2435,6 @@ public virtual void ViewDefaultEvent(IComponent component) PropertyDescriptor defaultPropEvent = null; bool eventChanged = false; IEventBindingService eps = (IEventBindingService)GetService(typeof(IEventBindingService)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || (eps is not null), "IEventBindingService not found"); if (eps is not null) { defaultPropEvent = eps.GetEventProperty(defaultEvent); @@ -2453,7 +2444,6 @@ public virtual void ViewDefaultEvent(IComponent component) if (defaultPropEvent is null || defaultPropEvent.IsReadOnly) { eps?.ShowCode(); - return; } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCommandSet.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCommandSet.cs index 2da4ac5f128..0cad0f99c99 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCommandSet.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlCommandSet.cs @@ -1249,22 +1249,14 @@ private void OnStatusMultiSelectNonContained(object sender, EventArgs e) /// protected void OnStatusShowGrid(object sender, EventArgs e) { - if (site is not null) + if (site.TryGetService(out IDesignerHost host) + && host.RootComponent is Control baseComponent + && GetProperty(baseComponent, "DrawGrid") is { } property) { - IDesignerHost host = (IDesignerHost)site.GetService(typeof(IDesignerHost)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); - - if (host?.RootComponent is Control baseComponent) - { - PropertyDescriptor prop = GetProperty(baseComponent, "DrawGrid"); - if (prop is not null) - { - bool drawGrid = (bool)prop.GetValue(baseComponent); - MenuCommand cmd = (MenuCommand)sender; - cmd.Enabled = true; - cmd.Checked = drawGrid; - } - } + bool drawGrid = (bool)property.GetValue(baseComponent); + MenuCommand cmd = (MenuCommand)sender; + cmd.Enabled = true; + cmd.Checked = drawGrid; } } @@ -1274,22 +1266,14 @@ protected void OnStatusShowGrid(object sender, EventArgs e) /// protected void OnStatusSnapToGrid(object sender, EventArgs e) { - if (site is not null) + if (site.TryGetService(out IDesignerHost host) + && host.RootComponent is Control baseComponent + && GetProperty(baseComponent, "SnapToGrid") is { } property) { - IDesignerHost host = (IDesignerHost)site.GetService(typeof(IDesignerHost)); - Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || host is not null, "IDesignerHost not found"); - - if (host?.RootComponent is Control baseComponent) - { - PropertyDescriptor prop = GetProperty(baseComponent, "SnapToGrid"); - if (prop is not null) - { - bool snapToGrid = (bool)prop.GetValue(baseComponent); - MenuCommand cmd = (MenuCommand)sender; - cmd.Enabled = controlsOnlySelection; - cmd.Checked = snapToGrid; - } - } + bool snapToGrid = (bool)property.GetValue(baseComponent); + MenuCommand cmd = (MenuCommand)sender; + cmd.Enabled = controlsOnlySelection; + cmd.Checked = snapToGrid; } } @@ -1325,7 +1309,6 @@ private void OnStatusZOrder(object sender, EventArgs e) // There must also be a control in the mix, and not the base component, and // it cannot be privately inherited. - // ICollection selectedComponents = SelectionService.GetSelectedComponents(); enable = false; diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.ControlDesignerAccessibleObject.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.ControlDesignerAccessibleObject.cs index bd4064b5a1d..80984aad70e 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.ControlDesignerAccessibleObject.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ControlDesigner.ControlDesignerAccessibleObject.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; @@ -65,10 +64,6 @@ public override AccessibleStates State public override AccessibleObject? GetChild(int index) { - Debug.WriteLineIf( - CompModSwitches.MSAA.TraceInfo, - $"ControlDesignerAccessibleObject.GetChild({index})"); - if (_control.AccessibilityObject.GetChild(index) is Control.ControlAccessibleObject childAccObj) { AccessibleObject? cao = GetDesignerAccessibleObject(childAccObj); diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs index 5f63d6b9be3..72470df130e 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/DocumentDesigner.cs @@ -1161,82 +1161,79 @@ private void OnComponentChanged(object sender, ComponentChangedEventArgs e) /// private void OnSelectionChanged(object sender, EventArgs e) { - ISelectionService svc = (ISelectionService)GetService(typeof(ISelectionService)); - if (svc is not null) + if (!TryGetService(out ISelectionService svc)) { - ICollection selComponents = svc.GetSelectedComponents(); + return; + } - // Setup the correct active accessibility selection / focus data - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "MSAA: SelectionChanged"); - foreach (object selObj in selComponents) - { - if (selObj is Control c) - { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"MSAA: SelectionAdd, control = {c}"); - PInvoke.NotifyWinEvent( - (uint)AccessibleEvents.SelectionAdd, - c, - (int)OBJECT_IDENTIFIER.OBJID_CLIENT, - (int)PInvoke.CHILDID_SELF); - } - } + ICollection selComponents = svc.GetSelectedComponents(); - if (svc.PrimarySelection is Control primary) + // Setup the correct active accessibility selection / focus data + foreach (object selObj in selComponents) + { + if (selObj is Control c) { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"MSAA: Focus, control = {primary}"); PInvoke.NotifyWinEvent( - (uint)AccessibleEvents.Focus, - primary, + (uint)AccessibleEvents.SelectionAdd, + c, (int)OBJECT_IDENTIFIER.OBJID_CLIENT, (int)PInvoke.CHILDID_SELF); } + } + + if (svc.PrimarySelection is Control primary) + { + PInvoke.NotifyWinEvent( + (uint)AccessibleEvents.Focus, + primary, + (int)OBJECT_IDENTIFIER.OBJID_CLIENT, + (int)PInvoke.CHILDID_SELF); + } - // See if there are visual controls selected. If so, we add a context attribute. - // Otherwise, we remove the attribute. We do not count the form. - IHelpService hs = (IHelpService)GetService(typeof(IHelpService)); + // See if there are visual controls selected. If so, we add a context attribute. + // Otherwise, we remove the attribute. We do not count the form. + IHelpService hs = (IHelpService)GetService(typeof(IHelpService)); - if (hs is not null) - { - ushort type = 0; - string[] types = - [ - "VisualSelection", + if (hs is not null) + { + ushort type = 0; + string[] types = + [ + "VisualSelection", "NonVisualSelection", "MixedSelection" - ]; + ]; - foreach (object obj in selComponents) + foreach (object obj in selComponents) + { + if (obj is Control) { - if (obj is Control) + if (obj != Component) { - if (obj != Component) - { - type |= 1; - } - } - else - { - type |= 2; - } - - if (type == 3) - { - break; + type |= 1; } } - - // Remove any prior attribute - // - for (int i = 0; i < types.Length; i++) + else { - hs.RemoveContextAttribute("Keyword", types[i]); + type |= 2; } - if (type != 0) + if (type == 3) { - hs.AddContextAttribute("Keyword", types[type - 1], HelpKeywordType.GeneralKeyword); + break; } } + + // Remove any prior attribute + for (int i = 0; i < types.Length; i++) + { + hs.RemoveContextAttribute("Keyword", types[i]); + } + + if (type != 0) + { + hs.AddContextAttribute("Keyword", types[type - 1], HelpKeywordType.GeneralKeyword); + } } } diff --git a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs index 473b01a6934..43fcccf97ee 100644 --- a/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs +++ b/src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripItemDesigner.cs @@ -951,7 +951,6 @@ private void OnSelectionChanged(object sender, EventArgs e) acc.AddState(AccessibleStates.Selected); if (tool is not null) { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"MSAA: SelectionAdd, tool = {tool}"); PInvoke.NotifyWinEvent( (uint)AccessibleEvents.SelectionAdd, owner, diff --git a/src/System.Windows.Forms.Primitives/src/System/ComponentModel/CompModSwitches.cs b/src/System.Windows.Forms.Primitives/src/System/ComponentModel/CompModSwitches.cs deleted file mode 100644 index 4e15a0588ab..00000000000 --- a/src/System.Windows.Forms.Primitives/src/System/ComponentModel/CompModSwitches.cs +++ /dev/null @@ -1,307 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace System.ComponentModel; - -internal static class CompModSwitches -{ - private static TraceSwitch? s_flowLayout; - private static TraceSwitch? s_dataCursor; - private static TraceSwitch? s_dataGridCursor; - private static TraceSwitch? s_dataGridEditing; - private static TraceSwitch? s_dataGridKeys; - private static TraceSwitch? s_dataGridLayout; - private static TraceSwitch? s_dataGridPainting; - private static TraceSwitch? s_dataGridParents; - private static TraceSwitch? s_dataGridScrolling; - private static TraceSwitch? s_dataGridSelection; - private static TraceSwitch? s_dataObject; - private static TraceSwitch? s_dataView; - private static TraceSwitch? s_dgCaptionPaint; - private static TraceSwitch? s_dgEditColumnEditing; - private static TraceSwitch? s_dgRelationShpRowLayout; - private static TraceSwitch? s_dgRelationShpRowPaint; - private static TraceSwitch? s_dgRowPaint; - private static TraceSwitch? s_imeMode; - private static TraceSwitch? s_msaa; - private static TraceSwitch? s_layoutPerformance; - private static TraceSwitch? s_layoutSuspendResume; - private static TraceSwitch? s_richLayout; - private static TraceSwitch? s_setBounds; - - private static BooleanSwitch? s_lifetimeTracing; - - private static TraceSwitch? s_handleLeak; - private static BooleanSwitch? s_traceCollect; - private static BooleanSwitch? s_commonDesignerServices; - - public static TraceSwitch DataCursor - { - get - { - s_dataCursor ??= new TraceSwitch("Microsoft.WFC.Data.DataCursor", "DataCursor"); - - return s_dataCursor; - } - } - - public static TraceSwitch DataGridCursor - { - get - { - s_dataGridCursor ??= new TraceSwitch("DataGridCursor", "DataGrid cursor tracing"); - - return s_dataGridCursor; - } - } - - public static TraceSwitch DataGridEditing - { - get - { - s_dataGridEditing ??= new TraceSwitch("DataGridEditing", "DataGrid edit related tracing"); - - return s_dataGridEditing; - } - } - - public static TraceSwitch DataGridKeys - { - get - { - s_dataGridKeys ??= new TraceSwitch("DataGridKeys", "DataGrid keystroke management tracing"); - - return s_dataGridKeys; - } - } - - public static TraceSwitch DataGridLayout - { - get - { - s_dataGridLayout ??= new TraceSwitch("DataGridLayout", "DataGrid layout tracing"); - - return s_dataGridLayout; - } - } - - public static TraceSwitch DataGridPainting - { - get - { - s_dataGridPainting ??= new TraceSwitch("DataGridPainting", "DataGrid Painting related tracing"); - - return s_dataGridPainting; - } - } - - public static TraceSwitch DataGridParents - { - get - { - s_dataGridParents ??= new TraceSwitch("DataGridParents", "DataGrid parent rows"); - - return s_dataGridParents; - } - } - - public static TraceSwitch DataGridScrolling - { - get - { - s_dataGridScrolling ??= new TraceSwitch("DataGridScrolling", "DataGrid scrolling"); - - return s_dataGridScrolling; - } - } - - public static TraceSwitch DataGridSelection - { - get - { - s_dataGridSelection ??= new TraceSwitch("DataGridSelection", "DataGrid selection management tracing"); - - return s_dataGridSelection; - } - } - - public static TraceSwitch DataObject - { - get - { - s_dataObject ??= new TraceSwitch("DataObject", "Enable tracing for the DataObject class."); - - return s_dataObject; - } - } - - public static TraceSwitch DataView - { - get - { - s_dataView ??= new TraceSwitch("DataView", "DataView"); - - return s_dataView; - } - } - - public static TraceSwitch DGCaptionPaint - { - get - { - s_dgCaptionPaint ??= new TraceSwitch("DGCaptionPaint", "DataGridCaption"); - - return s_dgCaptionPaint; - } - } - - public static TraceSwitch DGEditColumnEditing - { - get - { - s_dgEditColumnEditing ??= new TraceSwitch("DGEditColumnEditing", "Editing related tracing"); - - return s_dgEditColumnEditing; - } - } - - public static TraceSwitch DGRelationShpRowLayout - { - get - { - s_dgRelationShpRowLayout ??= new TraceSwitch("DGRelationShpRowLayout", "Relationship row layout"); - - return s_dgRelationShpRowLayout; - } - } - - public static TraceSwitch DGRelationShpRowPaint - { - get - { - s_dgRelationShpRowPaint ??= new TraceSwitch("DGRelationShpRowPaint", "Relationship row painting"); - - return s_dgRelationShpRowPaint; - } - } - - public static TraceSwitch DGRowPaint - { - get - { - s_dgRowPaint ??= new TraceSwitch("DGRowPaint", "DataGrid Simple Row painting stuff"); - - return s_dgRowPaint; - } - } - - public static TraceSwitch FlowLayout - { - get - { - s_flowLayout ??= new TraceSwitch("FlowLayout", "Debug flow layout"); - - return s_flowLayout; - } - } - - public static TraceSwitch ImeMode - { - get - { - s_imeMode ??= new TraceSwitch("ImeMode", "Debug IME Mode"); - - return s_imeMode; - } - } - - public static TraceSwitch LayoutPerformance - { - get - { - s_layoutPerformance ??= new TraceSwitch("LayoutPerformance", "Tracks layout events which impact performance."); - - return s_layoutPerformance; - } - } - - public static TraceSwitch LayoutSuspendResume - { - get - { - s_layoutSuspendResume ??= new TraceSwitch("LayoutSuspendResume", "Tracks SuspendLayout/ResumeLayout."); - - return s_layoutSuspendResume; - } - } - - public static BooleanSwitch LifetimeTracing - { - get - { - s_lifetimeTracing ??= new BooleanSwitch("LifetimeTracing", "Track lifetime events. This will cause objects to track the stack at creation and dispose."); - - return s_lifetimeTracing; - } - } - - public static TraceSwitch MSAA - { - get - { - s_msaa ??= new TraceSwitch("MSAA", "Debug Microsoft Active Accessibility"); - - return s_msaa; - } - } - - public static TraceSwitch RichLayout - { - get - { - s_richLayout ??= new TraceSwitch("RichLayout", "Debug layout in RichControls"); - - return s_richLayout; - } - } - - public static TraceSwitch SetBounds - { - get - { - s_setBounds ??= new TraceSwitch("SetBounds", "Trace changes to control size/position."); - - return s_setBounds; - } - } - - public static TraceSwitch HandleLeak - { - get - { - s_handleLeak ??= new TraceSwitch("HANDLELEAK", "HandleCollector: Track Win32 Handle Leaks"); - - return s_handleLeak; - } - } - - public static BooleanSwitch TraceCollect - { - get - { - s_traceCollect ??= new BooleanSwitch("TRACECOLLECT", "HandleCollector: Trace HandleCollector operations"); - - return s_traceCollect; - } - } - - public static BooleanSwitch CommonDesignerServices - { - get - { - s_commonDesignerServices ??= new BooleanSwitch("CommonDesignerServices", "Assert if any common designer service is not found."); - - return s_commonDesignerServices; - } - } -} diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/AccessibleObject.EnumVariantObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/AccessibleObject.EnumVariantObject.cs index 3b3eaf34d71..5dfbdc40aac 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/AccessibleObject.EnumVariantObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/AccessibleObject.EnumVariantObject.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; using Windows.Win32.System.Com; using Windows.Win32.System.Ole; using Windows.Win32.System.Variant; @@ -78,10 +77,6 @@ HRESULT IEnumVARIANT.Interface.Next(uint celt, VARIANT* rgVar, uint* pCeltFetche // NOTE: rgvar is a pointer to an array of variants if (_owner.IsClientObject) { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"EnumVariantObject: owner = {_owner}, celt = {celt}"); - - Debug.Indent(); - int childCount; int[]? newOrder; @@ -95,8 +90,6 @@ HRESULT IEnumVARIANT.Interface.Next(uint celt, VARIANT* rgVar, uint* pCeltFetche { *pCeltFetched = 0; } - - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.IEV.Next: no children to add"); } else if ((newOrder = _owner.GetSysChildOrder()) is not null) { @@ -106,8 +99,6 @@ HRESULT IEnumVARIANT.Interface.Next(uint celt, VARIANT* rgVar, uint* pCeltFetche { NextFromSystem(celt, rgVar, pCeltFetched); } - - Debug.Unindent(); } else { @@ -145,8 +136,6 @@ private unsafe void NextFromSystem(uint celt, VARIANT* rgVar, uint* pCeltFetched { *pCeltFetched = fetched; } - - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, "AccessibleObject.IEV.Next: Delegating to systemIEnumVariant"); } /// @@ -189,9 +178,6 @@ private unsafe void NextFromSystemReordered(uint celt, VARIANT* rgVar, uint* pCe } _currentChild++; - Debug.WriteLineIf( - CompModSwitches.MSAA.TraceInfo, - $"AccessibleObject.IEV.Next: adding sys child {_currentChild} of {newOrder.Length}"); } if (pCeltFetched is not null) @@ -213,9 +199,6 @@ private unsafe void NextFromChildCollection(uint celt, VARIANT* rgVar, uint* pCe // The type needs to be `int` or controls without UIA support build an incorrect Accessibility tree. rgVar[i] = (VARIANT)(int)_currentChild; - Debug.WriteLineIf( - CompModSwitches.MSAA.TraceInfo, - $"AccessibleObject.IEV.Next: adding own child {_currentChild} of {childCount}"); } if (pCeltFetched is not null) diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/Control.ControlAccessibleObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/Control.ControlAccessibleObject.cs index c6f1766d71f..7058d56238f 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/Control.ControlAccessibleObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Accessibility/Control.ControlAccessibleObject.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; using System.Globalization; using System.Windows.Forms.Automation; using System.Windows.Forms.Primitives; @@ -436,8 +435,6 @@ public override AccessibleRole Role public override int GetHelpTopic(out string? fileName) { - int topic = 0; - if (!this.TryGetOwnerAs(out Control? owner) || owner.Events[s_queryAccessibilityHelpEvent] is not QueryAccessibilityHelpEventHandler handler) { @@ -448,7 +445,7 @@ public override int GetHelpTopic(out string? fileName) handler(owner, args); fileName = args.HelpNamespace; - int.TryParse(args.HelpKeyword, NumberStyles.Integer, CultureInfo.InvariantCulture, out topic); + int.TryParse(args.HelpKeyword, NumberStyles.Integer, CultureInfo.InvariantCulture, out int topic); return topic; } @@ -471,9 +468,6 @@ public void NotifyClients(AccessibleEvents accEvent, int objectID, int childID) return; } - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, - $"Control.NotifyClients: this = {ToString()}, accEvent = {accEvent}, childID = {childID}"); - PInvoke.NotifyWinEvent( (uint)accEvent, new HandleRef(Owner, HandleInternal), diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Application.ComponentManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Application.ComponentManager.cs index 79b40433d01..6496f0497ad 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Application.ComponentManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Application.ComponentManager.cs @@ -180,16 +180,12 @@ BOOL IMsoComponentManager.Interface.FOnComponentExitState( if (uContext is msoccontext.All or msoccontext.Mine) { - Debug.Indent(); - // We should notify all components we contain that the state has changed. foreach (ComponentHashtableEntry entry in OleComponents.Values) { using var component = entry.component.GetInterface(); component.Value->OnEnterState(uStateID, false); } - - Debug.Unindent(); } return false; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Control.Ime.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Control.Ime.cs index 8d72fe8180e..0871885a13d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.Ime.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.Ime.cs @@ -35,31 +35,20 @@ internal ImeMode CachedImeMode { get { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_CachedImeMode(), this = {this}"); - Debug.Indent(); - // Get the ImeMode from the property store - // ImeMode cachedImeMode = (ImeMode)Properties.GetInteger(s_imeModeProperty, out bool found); if (!found) { cachedImeMode = DefaultImeMode; - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"using DefaultImeMode == {cachedImeMode}"); - } - else - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"using property store ImeMode == {cachedImeMode}"); } // If inherited, get the mode from this control's parent - // if (cachedImeMode == ImeMode.Inherit) { Control? parent = ParentInternal; if (parent is not null) { cachedImeMode = parent.CachedImeMode; - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"inherited from parent = {parent.GetType()}"); } else { @@ -67,24 +56,13 @@ internal ImeMode CachedImeMode } } - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"returning CachedImeMode == {cachedImeMode}"); - Debug.Unindent(); - return cachedImeMode; } - set { - // When the control is in restricted mode (!CanEnableIme) the CachedImeMode should be changed only programmatically, - // calls generated by user interaction should be wrapped with a check for CanEnableIme. - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside set_CachedImeMode(), this = {this}"); - Debug.Indent(); - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, $"Setting cached Ime == {value}"); + // When the control is in restricted mode (!CanEnableIme) the CachedImeMode should be changed only + // programmatically, calls generated by user interaction should be wrapped with a check for CanEnableIme. Properties.SetInteger(s_imeModeProperty, (int)value); - - Debug.Unindent(); } } @@ -98,11 +76,6 @@ protected virtual bool CanEnableIme get { // Note: If overriding this property make sure to add the Debug tracing code and call this method (base.CanEnableIme). - - Debug.Indent(); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_CanEnableIme(), value = {ImeSupported}, this = {this}"); - Debug.Unindent(); - return ImeSupported; } } @@ -114,8 +87,6 @@ internal ImeMode CurrentImeContextMode { get { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_CurrentImeContextMode(), this = {this}"); - if (IsHandleCreated) { return ImeContext.GetImeMode(Handle); @@ -128,10 +99,7 @@ internal ImeMode CurrentImeContextMode } } - protected virtual ImeMode DefaultImeMode - { - get { return ImeMode.Inherit; } - } + protected virtual ImeMode DefaultImeMode => ImeMode.Inherit; /// /// Flag used to avoid re-entrancy during WM_IME_NOTIFY message processing - see WmImeNotify(). @@ -141,22 +109,11 @@ internal int DisableImeModeChangedCount { get { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_DisableImeModeChangedCount()"); - Debug.Indent(); - int val = Properties.GetInteger(s_disableImeModeChangedCountProperty, out bool dummy); - Debug.Assert(val >= 0, "Counter underflow."); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Value: {val}"); - Debug.Unindent(); - return val; } - set - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside set_DisableImeModeChangedCount(): {value}"); - Properties.SetInteger(s_disableImeModeChangedCountProperty, value); - } + set => Properties.SetInteger(s_disableImeModeChangedCountProperty, value); } /// @@ -165,23 +122,8 @@ internal int DisableImeModeChangedCount /// private static bool IgnoreWmImeNotify { - get - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_IgnoreWmImeNotify()"); - Debug.Indent(); - - bool val = s_ignoreWmImeNotify; - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Value: {val}"); - Debug.Unindent(); - - return val; - } - set - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside set_IgnoreWmImeNotify(): {value}"); - s_ignoreWmImeNotify = value; - } + get => s_ignoreWmImeNotify; + set => s_ignoreWmImeNotify = value; } /// @@ -217,80 +159,59 @@ public ImeMode ImeMode /// protected virtual ImeMode ImeModeBase { - get - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_ImeModeBase(), this = {this}"); - Debug.Indent(); - - ImeMode imeMode = CachedImeMode; - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Value = {imeMode}"); - Debug.Unindent(); - - return imeMode; - } + get => CachedImeMode; set { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside set_ImeModeBase({value}), this = {this}"); - Debug.Indent(); - // valid values are -1 to 0xb SourceGenerated.EnumValidator.Validate(value); ImeMode oldImeMode = CachedImeMode; CachedImeMode = value; - if (oldImeMode != value) + if (oldImeMode == value) { - // Cache current value to determine whether we need to raise the ImeModeChanged. - Control? ctl = null; + return; + } + + // Cache current value to determine whether we need to raise the ImeModeChanged. + Control? ctl = null; - if (!DesignMode && ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + if (!DesignMode && ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + { + // Set the context to the new value if control is focused. + if (Focused) { - // Set the context to the new value if control is focused. - if (Focused) + ctl = this; + } + else if (ContainsFocus) + { + ctl = FromChildHandle(PInvoke.GetFocus()); + } + + if (ctl is not null && ctl.CanEnableIme) + { + // Block ImeModeChanged since we are checking for it below. + DisableImeModeChangedCount++; + + try { - ctl = this; + ctl.UpdateImeContextMode(); } - else if (ContainsFocus) + finally { - ctl = FromChildHandle(PInvoke.GetFocus()); - } - - if (ctl is not null && ctl.CanEnableIme) - { - // Block ImeModeChanged since we are checking for it below. - DisableImeModeChangedCount++; - - try - { - ctl.UpdateImeContextMode(); - } - finally - { - DisableImeModeChangedCount--; - } + DisableImeModeChangedCount--; } } - - VerifyImeModeChanged(oldImeMode, CachedImeMode); } - ImeContext.TraceImeStatus(this); - Debug.Unindent(); + VerifyImeModeChanged(oldImeMode, CachedImeMode); } } /// /// Determines whether the Control supports IME handling by default. /// - private bool ImeSupported - { - get - { - return DefaultImeMode != ImeMode.Disable; - } - } + private bool ImeSupported => DefaultImeMode != ImeMode.Disable; [WinCategory("Behavior")] [SRDescription(nameof(SR.ControlOnImeModeChangedDescr))] @@ -309,24 +230,15 @@ internal int ImeWmCharsToIgnore // after all messages are sent, corresponding WM_CHAR messages are also sent. (in non-unicode // windows two WM_CHAR messages are sent per char in the IME). We need to keep a counter // not to process each character twice or more. - get - { - return Properties.GetInteger(s_imeWmCharsToIgnoreProperty); - } + get => Properties.GetInteger(s_imeWmCharsToIgnoreProperty); set { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside set_ImeWmCharToIgnore(value={value}), this = {this}"); - Debug.Indent(); - // WM_CHAR is not send after WM_IME_CHAR when the composition has been closed by either, changing the conversion mode or // dissociating the IME (for instance when loosing focus and conversion is forced to complete). if (ImeWmCharsToIgnore != ImeCharsToIgnoreDisabled) { Properties.SetInteger(s_imeWmCharsToIgnoreProperty, value); } - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImeWmCharsToIgnore on leaving setter: {ImeWmCharsToIgnore}"); - Debug.Unindent(); } } @@ -339,9 +251,6 @@ private bool LastCanEnableIme { get { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_LastCanEnableIme()"); - Debug.Indent(); - int val = Properties.GetInteger(s_lastCanEnableImeProperty, out bool valueFound); if (valueFound) @@ -353,16 +262,9 @@ private bool LastCanEnableIme valueFound = true; } - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Value: {valueFound}"); - Debug.Unindent(); - return valueFound; } - set - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside set_LastCanEnableIme(): {value}"); - Properties.SetInteger(s_lastCanEnableImeProperty, value ? 1 : 0); - } + set => Properties.SetInteger(s_lastCanEnableImeProperty, value ? 1 : 0); } /// @@ -374,15 +276,10 @@ protected static ImeMode PropagatingImeMode { get { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside get_PropagatingImeMode()"); - Debug.Indent(); - if (s_propagatingImeMode == ImeMode.Inherit) { // Initialize the propagating IME mode to the value the IME associated to the focused window currently has, // this enables propagating the IME mode from/to unmanaged applications hosting winforms controls. - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "Initializing PropagatingImeMode"); - ImeMode imeMode = ImeMode.Inherit; HWND focusHandle = PInvoke.GetFocus(); @@ -407,38 +304,25 @@ protected static ImeMode PropagatingImeMode PropagatingImeMode = imeMode; } - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"Value: {s_propagatingImeMode}"); - Debug.Unindent(); - return s_propagatingImeMode; } private set { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, "Inside set_PropagatingImeMode()"); - Debug.Indent(); - - if (s_propagatingImeMode != value) + if (s_propagatingImeMode == value) { - switch (value) - { - case ImeMode.NoControl: - case ImeMode.Disable: - // Cannot set propagating ImeMode to one of these values. - Debug.WriteLineIf( - CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, - $"Cannot change PropagatingImeMode to {value}"); - return; - - default: - Debug.WriteLineIf( - CompModSwitches.ImeMode.Level >= TraceLevel.Warning, - $"Setting PropagatingImeMode: Current value = {s_propagatingImeMode}, New value = {value}"); - s_propagatingImeMode = value; - break; - } + return; } - Debug.Unindent(); + switch (value) + { + case ImeMode.NoControl: + case ImeMode.Disable: + // Cannot set propagating ImeMode to one of these values. + return; + default: + s_propagatingImeMode = value; + break; + } } } @@ -454,9 +338,6 @@ internal void UpdateImeContextMode() // Note: CHN IME won't send WM_IME_NOTIFY msg when getting associated, setting the IME context mode // forces the message to be sent as a side effect. - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside UpdateImeContextMode(), this = {this}"); - Debug.Indent(); - // If the value is not supported by the Ime, it will be mapped to a corresponding one, we need // to update the cached ImeMode to the actual value. @@ -517,9 +398,6 @@ internal void UpdateImeContextMode() VerifyImeModeChanged(newImeContextMode, CachedImeMode); } } - - ImeContext.TraceImeStatus(this); - Debug.Unindent(); } } @@ -528,17 +406,9 @@ internal void UpdateImeContextMode() /// private void VerifyImeModeChanged(ImeMode oldMode, ImeMode newMode) { - if (ImeSupported && (DisableImeModeChangedCount == 0) && (newMode != ImeMode.NoControl)) + if (ImeSupported && (DisableImeModeChangedCount == 0) && (newMode != ImeMode.NoControl) && oldMode != newMode) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside VerifyImeModeChanged(oldMode={oldMode}, newMode={newMode}), this = {this}"); - Debug.Indent(); - - if (oldMode != newMode) - { - OnImeModeChanged(EventArgs.Empty); - } - - Debug.Unindent(); + OnImeModeChanged(EventArgs.Empty); } } @@ -548,46 +418,43 @@ private void VerifyImeModeChanged(ImeMode oldMode, ImeMode newMode) /// internal void VerifyImeRestrictedModeChanged() { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside VerifyImeRestrictedModeChanged(), this = {this}"); - Debug.Indent(); - bool currentCanEnableIme = CanEnableIme; - if (LastCanEnableIme != currentCanEnableIme) + if (LastCanEnableIme == currentCanEnableIme) { - if (Focused) + return; + } + + if (Focused) + { + // Disable ImeModeChanged from the following call since we'll raise it here if needed. + DisableImeModeChangedCount++; + try { - // Disable ImeModeChanged from the following call since we'll raise it here if needed. - DisableImeModeChangedCount++; - try - { - UpdateImeContextMode(); - } - finally - { - DisableImeModeChangedCount--; - } + UpdateImeContextMode(); } - - // Assume for a moment the control is getting restricted; - ImeMode oldImeMode = CachedImeMode; - ImeMode newImeMode = ImeMode.Disable; - - if (currentCanEnableIme) + finally { - // Control is actually getting unrestricted, swap values. - newImeMode = oldImeMode; - oldImeMode = ImeMode.Disable; + DisableImeModeChangedCount--; } + } - // Do we need to raise the ImeModeChanged event? - VerifyImeModeChanged(oldImeMode, newImeMode); + // Assume for a moment the control is getting restricted; + ImeMode oldImeMode = CachedImeMode; + ImeMode newImeMode = ImeMode.Disable; - // Finally update the saved CanEnableIme value. - LastCanEnableIme = currentCanEnableIme; + if (currentCanEnableIme) + { + // Control is actually getting unrestricted, swap values. + newImeMode = oldImeMode; + oldImeMode = ImeMode.Disable; } - Debug.Unindent(); + // Do we need to raise the ImeModeChanged event? + VerifyImeModeChanged(oldImeMode, newImeMode); + + // Finally update the saved CanEnableIme value. + LastCanEnableIme = currentCanEnableIme; } /// @@ -597,9 +464,6 @@ internal void VerifyImeRestrictedModeChanged() /// internal void OnImeContextStatusChanged(IntPtr handle) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside OnImeContextStatusChanged(), this = {this}"); - Debug.Indent(); - Debug.Assert(ImeSupported, "WARNING: Attempting to update ImeMode properties on IME-Unaware control!"); Debug.Assert(!DesignMode, "Shouldn't be updating cached ime mode at design-time"); @@ -610,7 +474,8 @@ internal void OnImeContextStatusChanged(IntPtr handle) ImeMode oldImeMode = CachedImeMode; if (CanEnableIme) - { // Cache or Propagating ImeMode should not be updated by interaction when the control is in restricted mode. + { + // Cache or Propagating ImeMode should not be updated by interaction when the control is in restricted mode. if (oldImeMode != ImeMode.NoControl) { CachedImeMode = fromContext; // This could end up in the same value due to ImeMode language mapping. @@ -624,18 +489,14 @@ internal void OnImeContextStatusChanged(IntPtr handle) } } } - - Debug.Unindent(); } /// - /// Raises the - /// event. + /// Raises the event. /// protected virtual void OnImeModeChanged(EventArgs e) { Debug.Assert(ImeSupported, "ImeModeChanged should not be raised on an Ime-Unaware control."); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside OnImeModeChanged(), this = {this}"); ((EventHandler?)Events[s_imeModeChangedEvent])?.Invoke(this, e); } @@ -643,11 +504,7 @@ protected virtual void OnImeModeChanged(EventArgs e) /// Resets the Ime mode. /// [EditorBrowsable(EditorBrowsableState.Never)] - public void ResetImeMode() - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside ResetImeMode(), this = {this}"); - ImeMode = DefaultImeMode; - } + public void ResetImeMode() => ImeMode = DefaultImeMode; /// /// Returns true if the ImeMode should be persisted in code gen. @@ -667,9 +524,6 @@ internal virtual bool ShouldSerializeImeMode() /// private void WmInputLangChange(ref Message m) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside WmInputLangChange(), this = {this}"); - Debug.Indent(); - // Make sure the IME context is associated with the correct (mapped) mode. UpdateImeContextMode(); @@ -679,19 +533,13 @@ private void WmInputLangChange(ref Message m) PropagatingImeMode = ImeMode.Off; } - Form? form = FindForm(); - - if (form is not null) + if (FindForm() is Form form) { InputLanguageChangedEventArgs e = InputLanguage.CreateInputLanguageChangedEventArgs(m); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Culture={e.Culture}"); form.PerformOnInputLanguageChanged(e); } DefWndProc(ref m); - - ImeContext.TraceImeStatus(this); - Debug.Unindent(); } /// @@ -699,15 +547,10 @@ private void WmInputLangChange(ref Message m) /// private void WmInputLangChangeRequest(ref Message m) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside WmInputLangChangeRequest(), this={this}"); - Debug.Indent(); - InputLanguageChangingEventArgs e = InputLanguage.CreateInputLanguageChangingEventArgs(m); - Form? form = FindForm(); - if (form is not null) + if (FindForm() is Form form) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Culture={e.Culture}"); form.PerformOnInputLanguageChanging(e); } @@ -719,8 +562,6 @@ private void WmInputLangChangeRequest(ref Message m) { m.ResultInternal = (LRESULT)0; } - - Debug.Unindent(); } /// @@ -741,9 +582,6 @@ private void WmImeChar(ref Message m) /// private void WmImeEndComposition(ref Message m) { - Debug.WriteLineIf( - CompModSwitches.ImeMode.Level >= TraceLevel.Info, - $"Inside WmImeEndComposition() - Disabling ImeWmCharToIgnore, this={this}"); ImeWmCharsToIgnore = ImeCharsToIgnoreDisabled; DefWndProc(ref m); } @@ -776,15 +614,8 @@ private void WmImeNotify(ref Message m) if (wparam is ((int)PInvoke.IMN_SETCONVERSIONMODE) or ((int)PInvoke.IMN_SETOPENSTATUS)) { - Debug.WriteLineIf( - CompModSwitches.ImeMode.Level >= TraceLevel.Info, - $"Inside WmImeNotify(m.wparam=[{m.WParamInternal}]), this={this}"); - Debug.Indent(); - // Synchronize internal properties with the IME context mode. OnImeContextStatusChanged(Handle); - - Debug.Unindent(); } } @@ -798,15 +629,10 @@ internal void WmImeSetFocus() { if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside WmImeSetFocus(), this={this}"); - Debug.Indent(); - // Make sure the IME context is set to the correct value. // Consider - Perf improvement: ContainerControl controls should update the IME context only when they don't contain // a focusable control since it will be updated by that control. UpdateImeContextMode(); - - Debug.Unindent(); } } @@ -815,8 +641,6 @@ internal void WmImeSetFocus() /// private void WmImeStartComposition(ref Message m) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside WmImeStartComposition() - Enabling ImeWmCharToIgnore, this={this}"); - // Need to call the property store directly because the WmImeCharsToIgnore property is locked when ImeCharsToIgnoreDisabled. Properties.SetInteger(s_imeWmCharsToIgnoreProperty, ImeCharsToIgnoreEnabled); DefWndProc(ref m); @@ -827,9 +651,6 @@ private void WmImeStartComposition(ref Message m) /// private void WmImeKillFocus() { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside WmImeKillFocus(), this={this}"); - Debug.Indent(); - Control topMostWinformsParent = TopMostParent; Form? appForm = topMostWinformsParent as Form; @@ -838,8 +659,6 @@ private void WmImeKillFocus() // This means the winforms component container is not a WinForms host and it is no longer focused. // Or it is not the main app host. - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Unfocused TopMostParent = {topMostWinformsParent}"); - // We need to reset the PropagatingImeMode to force reinitialization when the winforms component gets focused again; // this enables inheriting the propagating mode from an unmanaged application hosting a winforms component. // But before leaving the winforms container we need to set the IME to the propagating IME mode since the focused control @@ -855,10 +674,7 @@ private void WmImeKillFocus() try { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"Setting IME context to PropagatingImeMode (leaving Winforms container). this = {this}"); ImeContext.SetImeStatus(PropagatingImeMode, topMostWinformsParent.Handle); - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"Resetting PropagatingImeMode. this = {this}"); PropagatingImeMode = ImeMode.Inherit; } finally @@ -867,12 +683,9 @@ private void WmImeKillFocus() } } } - - Debug.Unindent(); } -} // end class Control +} -///////////////////////////////////////////////////////// ImeContext class ///////////////////////////////////////////////////////// /// /// Represents the native IME context. /// @@ -888,30 +701,23 @@ public static class ImeContext /// public static void Disable(IntPtr handle) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside ImeContext.Disable({handle})"); - Debug.Indent(); - - if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + if (ImeModeConversion.InputLanguageTable == ImeModeConversion.UnsupportedTable) { - // Close the IME if necessary - // - if (IsOpen(handle)) - { - SetOpenStatus(false, handle); - } + return; + } - // Disable the IME by disassociating the context from the window. - // - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmAssociateContext({handle}, null)"); - HIMC oldContext = PInvoke.ImmAssociateContext((HWND)handle, (HIMC)IntPtr.Zero); - if (oldContext != IntPtr.Zero) - { - s_originalImeContext = oldContext; - } + // Close the IME if necessary + if (IsOpen(handle)) + { + SetOpenStatus(false, handle); } - TraceImeStatus(handle); - Debug.Unindent(); + // Disable the IME by disassociating the context from the window. + HIMC oldContext = PInvoke.ImmAssociateContext((HWND)handle, (HIMC)IntPtr.Zero); + if (oldContext != IntPtr.Zero) + { + s_originalImeContext = oldContext; + } } /// @@ -919,37 +725,28 @@ public static void Disable(IntPtr handle) /// public static void Enable(IntPtr handle) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside ImeContext.Enable({handle})"); - Debug.Indent(); - if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetContext({handle})"); HIMC inputContext = PInvoke.ImmGetContext((HWND)handle); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"context = {inputContext}"); // Enable IME by associating the IME context to the window. if (inputContext == IntPtr.Zero) { if (s_originalImeContext == IntPtr.Zero) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmCreateContext()"); inputContext = PInvoke.ImmCreateContext(); if (inputContext != IntPtr.Zero) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmAssociateContext({handle}, {inputContext})"); PInvoke.ImmAssociateContext((HWND)handle, inputContext); } } else { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, "ImmAssociateContext()"); PInvoke.ImmAssociateContext((HWND)handle, s_originalImeContext); } } else { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmReleaseContext({handle}, {inputContext})"); PInvoke.ImmReleaseContext((HWND)handle, inputContext); } @@ -959,24 +756,17 @@ public static void Enable(IntPtr handle) SetOpenStatus(true, handle); } } - - TraceImeStatus(handle); - Debug.Unindent(); } /// /// Gets the ImeMode that corresponds to ImeMode.Disable based on the current input language ImeMode table. /// - public static ImeMode GetImeMode(IntPtr handle) + public static unsafe ImeMode GetImeMode(IntPtr handle) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside ImeContext.GetImeMode({handle})"); - Debug.Indent(); - HIMC inputContext = (HIMC)IntPtr.Zero; ImeMode retval = ImeMode.NoControl; // Get the right table for the current keyboard layout - // ImeMode[] countryTable = ImeModeConversion.InputLanguageTable; if (countryTable == ImeModeConversion.UnsupportedTable) { @@ -985,9 +775,7 @@ public static ImeMode GetImeMode(IntPtr handle) goto cleanup; } - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetContext({handle})"); inputContext = PInvoke.ImmGetContext((HWND)handle); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"context = {inputContext}"); if (inputContext == IntPtr.Zero) { @@ -1004,13 +792,9 @@ public static ImeMode GetImeMode(IntPtr handle) } // Determine the IME mode from the conversion status - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetConversionStatus({inputContext}, conversion, sentence)"); IME_CONVERSION_MODE conversion; IME_SENTENCE_MODE sentence; - unsafe - { - PInvoke.ImmGetConversionStatus(inputContext, &conversion, &sentence); - } + PInvoke.ImmGetConversionStatus(inputContext, &conversion, &sentence); Debug.Assert(countryTable is not null, "countryTable is null"); @@ -1041,156 +825,51 @@ public static ImeMode GetImeMode(IntPtr handle) cleanup: if (inputContext != IntPtr.Zero) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmReleaseContext({handle}, {inputContext})"); PInvoke.ImmReleaseContext((HWND)handle, inputContext); } - TraceImeStatus(handle); - - Debug.Unindent(); return retval; } - /// - /// Get the actual IME status - This method is for debugging purposes only. - /// - [Conditional("DEBUG")] - internal static void TraceImeStatus(Control ctl) - { -#if DEBUG - if (ctl.IsHandleCreated) - { - TraceImeStatus(ctl.Handle); - } -#endif - } - - [Conditional("DEBUG")] - private static void TraceImeStatus(IntPtr handle) - { -#if DEBUG - if (CompModSwitches.ImeMode.Level >= TraceLevel.Info) - { - string status = "?"; - HIMC inputContext = (HIMC)IntPtr.Zero; - ImeMode[] countryTable = ImeModeConversion.InputLanguageTable; - - if (countryTable == ImeModeConversion.UnsupportedTable) - { - status = "IME not supported in current language."; - goto cleanup; - } - - inputContext = PInvoke.ImmGetContext((HWND)handle); - - if (inputContext == IntPtr.Zero) - { - status = $"No ime context for handle=[{handle}]"; - goto cleanup; - } - - if (!PInvoke.ImmGetOpenStatus(inputContext)) - { - status = $"Ime closed for handle=[{handle}]"; - goto cleanup; - } - - IME_CONVERSION_MODE conversion; - IME_SENTENCE_MODE sentence; - unsafe - { - PInvoke.ImmGetConversionStatus(inputContext, &conversion, &sentence); - } - - ImeMode retval; - - if ((conversion & IME_CONVERSION_MODE.IME_CMODE_NATIVE) != 0) - { - if ((conversion & IME_CONVERSION_MODE.IME_CMODE_KATAKANA) != 0) - { - retval = ((conversion & IME_CONVERSION_MODE.IME_CMODE_FULLSHAPE) != 0) - ? countryTable[ImeModeConversion.ImeNativeFullKatakana] - : countryTable[ImeModeConversion.ImeNativeHalfKatakana]; - } - else - { - retval = ((conversion & IME_CONVERSION_MODE.IME_CMODE_FULLSHAPE) != 0) - ? countryTable[ImeModeConversion.ImeNativeFullHiragana] - : countryTable[ImeModeConversion.ImeNativeHalfHiragana]; - } - } - else - { - retval = ((conversion & IME_CONVERSION_MODE.IME_CMODE_FULLSHAPE) != 0) - ? countryTable[ImeModeConversion.ImeAlphaFull] - : countryTable[ImeModeConversion.ImeAlphaHalf]; - } - - status = $"Ime conversion status mode for handle=[{handle}]: {retval}"; - - cleanup: - if (inputContext != IntPtr.Zero) - { - PInvoke.ImmReleaseContext((HWND)handle, inputContext); - } - - Debug.WriteLine(status); - } -#endif - } - /// /// Returns true if the IME is currently open /// public static bool IsOpen(IntPtr handle) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside ImeContext.IsOpen({handle})"); - Debug.Indent(); - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetContext({handle})"); HIMC inputContext = PInvoke.ImmGetContext((HWND)handle); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"context = {inputContext}"); bool retval = false; if (inputContext != IntPtr.Zero) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetOpenStatus({inputContext})"); retval = PInvoke.ImmGetOpenStatus(inputContext); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmReleaseContext({handle}, {inputContext})"); PInvoke.ImmReleaseContext((HWND)handle, inputContext); } - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $" IsOpen = {retval}"); - Debug.Unindent(); - return retval; } /// /// Sets the actual IME context value. /// - public static void SetImeStatus(ImeMode imeMode, IntPtr handle) + public static unsafe void SetImeStatus(ImeMode imeMode, IntPtr handle) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside ImeContext.SetImeStatus(ImeMode=[{imeMode}, handle=[{handle}])"); - Debug.Indent(); - Debug.Assert(imeMode != ImeMode.Inherit, "ImeMode.Inherit is an invalid argument to ImeContext.SetImeStatus"); if (imeMode is ImeMode.Inherit or ImeMode.NoControl) { - goto cleanup; // No action required + // No action required + return; } ImeMode[] inputLanguageTable = ImeModeConversion.InputLanguageTable; if (inputLanguageTable == ImeModeConversion.UnsupportedTable) { - goto cleanup; // We only support Japanese, Korean and Chinese IME. + // We only support Japanese, Korean and Chinese IME. + return; } - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Warning, $"\tSetting IME context to {imeMode}"); - if (imeMode == ImeMode.Disable) { Disable(handle); @@ -1241,34 +920,21 @@ public static void SetImeStatus(ImeMode imeMode, IntPtr handle) if (ImeModeConversion.ImeModeConversionBits.TryGetValue(imeMode, out ImeModeConversion conversionEntry)) { // Update the conversion status - // - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetContext({handle})"); HIMC inputContext = PInvoke.ImmGetContext((HWND)handle); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"context = {inputContext}"); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetConversionStatus({inputContext}, conversion, sentence)"); IME_CONVERSION_MODE conversion; IME_SENTENCE_MODE sentence; - unsafe - { - PInvoke.ImmGetConversionStatus(inputContext, &conversion, &sentence); - } + PInvoke.ImmGetConversionStatus(inputContext, &conversion, &sentence); conversion |= conversionEntry.SetBits; conversion &= ~conversionEntry.ClearBits; - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmSetConversionStatus({inputContext}, conversion, sentence)"); PInvoke.ImmSetConversionStatus(inputContext, conversion, sentence); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmReleaseContext({handle}, {inputContext})"); PInvoke.ImmReleaseContext((HWND)handle, inputContext); } break; } - - cleanup: - TraceImeStatus(handle); - Debug.Unindent(); } /// @@ -1276,32 +942,24 @@ public static void SetImeStatus(ImeMode imeMode, IntPtr handle) /// public static void SetOpenStatus(bool open, IntPtr handle) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside SetOpenStatus(open=[{open}], handle=[{handle}])"); - Debug.Indent(); + if (ImeModeConversion.InputLanguageTable == ImeModeConversion.UnsupportedTable) + { + return; + } - if (ImeModeConversion.InputLanguageTable != ImeModeConversion.UnsupportedTable) + HIMC inputContext = PInvoke.ImmGetContext((HWND)handle); + + if (inputContext != IntPtr.Zero) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmGetContext({handle})"); - HIMC inputContext = PInvoke.ImmGetContext((HWND)handle); - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"context = {inputContext}"); + bool succeeded = PInvoke.ImmSetOpenStatus(inputContext, open); + Debug.Assert(succeeded, "Could not set the IME open status."); - if (inputContext != IntPtr.Zero) + if (succeeded) { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmSetOpenStatus({inputContext}, {open})"); - bool succeeded = PInvoke.ImmSetOpenStatus(inputContext, open); - Debug.Assert(succeeded, "Could not set the IME open status."); - - if (succeeded) - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Verbose, $"ImmReleaseContext({handle}, {inputContext})"); - succeeded = PInvoke.ImmReleaseContext((HWND)handle, inputContext); - Debug.Assert(succeeded, "Could not release IME context."); - } + succeeded = PInvoke.ImmReleaseContext((HWND)handle, inputContext); + Debug.Assert(succeeded, "Could not release IME context."); } } - - TraceImeStatus(handle); - Debug.Unindent(); } } @@ -1399,7 +1057,6 @@ internal static ImeMode[] InputLanguageTable { get { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_InputLanguageTable(), Input Language = {InputLanguage.CurrentInputLanguage.Culture.DisplayName}, Thread = {Environment.CurrentManagedThreadId}"); InputLanguage inputLanguage = InputLanguage.CurrentInputLanguage; int lcid = (int)(inputLanguage.Handle & (long)0xFFFF); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs index f35e09406fd..c28f77f65e9 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Control.cs @@ -2647,7 +2647,7 @@ public event EventHandler? LocationChanged [Localizable(true)] public Padding Margin { - get { return CommonProperties.GetMargin(this); } + get => CommonProperties.GetMargin(this); set { // This should be done here rather than in the property store as @@ -9193,10 +9193,6 @@ protected virtual bool ProcessKeyEventArgs(ref Message m) if (charsToIgnore > 0) { charsToIgnore--; - Debug.WriteLineIf( - CompModSwitches.ImeMode.Level >= TraceLevel.Info, - $"charsToIgnore decreased, new val = {charsToIgnore}, this={this}"); - ImeWmCharsToIgnore = charsToIgnore; return false; } @@ -9766,9 +9762,6 @@ private void ResetVisible() /// public void ResumeLayout(bool performLayout) { - Debug.WriteLineIf(CompModSwitches.LayoutSuspendResume.TraceInfo, - $"{GetType().Name}::ResumeLayout( preformLayout = {performLayout}, newCount = {Math.Max(0, LayoutSuspendCount - 1)})"); - bool performedLayout = false; if (LayoutSuspendCount > 0) { @@ -10040,8 +10033,6 @@ internal void ScaleControl(SizeF includedFactor, SizeF excludedFactor) excludedSpecified |= (~RequiredScaling & BoundsSpecified.All); } - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"Scaling {this} Included: {includedFactor}, Excluded: {excludedFactor}"); - if (includedSpecified != BoundsSpecified.None) { ScaleControl(includedFactor, includedSpecified); @@ -10179,8 +10170,6 @@ protected virtual void ScaleControl(SizeF factor, BoundsSpecified specified) [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void ScaleCore(float dx, float dy) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"{GetType().Name}::ScaleCore({dx}, {dy})"); - using SuspendLayoutScope scope = new(this); int sx = (int)Math.Round(_x * dx); @@ -10313,6 +10302,7 @@ public bool SelectNextControl(Control? ctl, bool forward, bool tabStopOnly, bool } } while (ctl != start); + return null; } @@ -10322,8 +10312,7 @@ public bool SelectNextControl(Control? ctl, bool forward, bool tabStopOnly, bool /// private void SelectNextIfFocused() { - // We want to move focus away from hidden controls, so this - // function was added. + // We want to move focus away from hidden controls, so this function was added. if (ContainsFocus && ParentInternal is not null) { IContainerControl? c = ParentInternal.GetContainerControl(); @@ -10442,9 +10431,6 @@ public void SetBounds(int x, int y, int width, int height, BoundsSpecified speci [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { - Debug.WriteLineIf(CompModSwitches.SetBounds.TraceInfo, - $"{Name}::SetBoundsCore(x={x} y={y} width={width} height={height} specified={specified})"); - // SetWindowPos below sends a WmWindowPositionChanged (not posts) so we immediately // end up in WmWindowPositionChanged which may cause the parent to layout. We need to // suspend/resume to defer the parent from laying out until after InitLayout has been called @@ -11065,8 +11051,6 @@ public void SuspendLayout() } Debug.Assert(LayoutSuspendCount > 0, "SuspendLayout: layoutSuspendCount overflowed."); - Debug.WriteLineIf(CompModSwitches.LayoutSuspendResume.TraceInfo, - $"{GetType().Name}::SuspendLayout(newCount = {LayoutSuspendCount})"); } /// @@ -11182,15 +11166,6 @@ protected void UpdateBounds(int x, int y, int width, int height) [EditorBrowsable(EditorBrowsableState.Advanced)] protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) { -#if DEBUG - if (CompModSwitches.SetBounds.TraceVerbose) - { - Debug.WriteLine($"{Name}::UpdateBounds("); - Debug.Indent(); - Debug.WriteLine($"oldBounds={{x={_x} y={_y} width={_width} height={_height} clientWidth={_clientWidth} clientHeight={_clientHeight}}}"); - } -#endif // DEBUG - bool newLocation = _x != x || _y != y; bool newSize = Width != width || Height != height || _clientWidth != clientWidth || _clientHeight != clientHeight; @@ -11203,51 +11178,18 @@ protected void UpdateBounds(int x, int y, int width, int height, int clientWidth if (newLocation) { -#if DEBUG - Rectangle originalBounds = Bounds; -#endif OnLocationChanged(EventArgs.Empty); -#if DEBUG - if (Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) - { - Debug.WriteLine($""" - WARNING: Bounds changed during OnLocationChanged() - before={originalBounds} after={Bounds} - """); - } -#endif } if (newSize) { -#if DEBUG - Rectangle originalBounds = Bounds; -#endif OnSizeChanged(EventArgs.Empty); OnClientSizeChanged(EventArgs.Empty); // Clear PreferredSize cache for this control CommonProperties.xClearPreferredSizeCache(this); LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.Bounds); - -#if DEBUG - if (Bounds != originalBounds && CompModSwitches.SetBounds.TraceWarning) - { - Debug.WriteLine($""" - WARNING: Bounds changed during OnSizeChanged() - before={originalBounds} after={Bounds} - """); - } -#endif } - -#if DEBUG - if (CompModSwitches.SetBounds.TraceVerbose) - { - Debug.WriteLine($"newBounds={{x={x} y={y} width={width} height={height} clientWidth={clientWidth} clientHeight={clientHeight}}}"); - Debug.Unindent(); - } -#endif } /// @@ -11656,8 +11598,6 @@ private void WmGetControlType(ref Message m) /// private unsafe void WmGetObject(ref Message m) { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"In WmGetObject, this = {GetType().FullName}, lParam = {m.LParamInternal}"); - if (m.LParamInternal == PInvoke.UiaRootObjectId && SupportsUiaProviders) { // If the requested object identifier is UiaRootObjectId, @@ -11686,7 +11626,6 @@ private unsafe void WmGetObject(ref Message m) { // Obtain the Lresult. m.ResultInternal = accessibleObject.GetLRESULT(m.WParamInternal); - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"LresultFromObject returned {m.ResultInternal}"); } catch (Exception e) { diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.cs index ff4b3593026..a264b13b3a0 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/DataGridView/DataGridView.cs @@ -1128,9 +1128,6 @@ protected override bool CanEnableIme { bool canEnable = false; - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_CanEnableIme(), this = {this}"); - Debug.Indent(); - if (_ptCurrentCell.X != -1 && ColumnEditable(_ptCurrentCell.X)) { DataGridViewCell dataGridViewCell = CurrentCellInternal; @@ -1142,9 +1139,6 @@ protected override bool CanEnableIme } } - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Value = {canEnable}"); - Debug.Unindent(); - return canEnable; } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs index c153a4fcaa0..95fa5a88f89 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs @@ -376,21 +376,7 @@ public event EventHandler? BorderStyleChanged internal virtual bool CanRaiseTextChangedEvent => true; - protected override bool CanEnableIme - { - get - { - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_CanEnableIme(), this = {this}"); - Debug.Indent(); - - bool canEnable = !(ReadOnly || PasswordProtect) && base.CanEnableIme; - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Value = {canEnable}"); - Debug.Unindent(); - - return canEnable; - } - } + protected override bool CanEnableIme => !(ReadOnly || PasswordProtect) && base.CanEnableIme; /// /// Gets a value indicating whether the user can undo the previous operation in a text box control. @@ -559,23 +545,7 @@ public event EventHandler? HideSelectionChanged /// protected override ImeMode ImeModeBase { - get - { - if (DesignMode) - { - return base.ImeModeBase; - } - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Inside get_ImeModeInternal(), this = {this}"); - Debug.Indent(); - - ImeMode imeMode = CanEnableIme ? base.ImeModeBase : ImeMode.Disable; - - Debug.WriteLineIf(CompModSwitches.ImeMode.Level >= TraceLevel.Info, $"Value = {imeMode}"); - Debug.Unindent(); - - return imeMode; - } + get => (DesignMode || CanEnableIme) ? base.ImeModeBase : ImeMode.Disable; set => base.ImeModeBase = value; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs index 93e05e5e536..d8c438208f3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripDropDown.cs @@ -1585,8 +1585,8 @@ internal override void ResetScaling(int newDpi) [EditorBrowsable(EditorBrowsableState.Never)] protected override void ScaleCore(float dx, float dy) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"{GetType().Name}::ScaleCore({dx}, {dy})"); SuspendLayout(); + try { // Get size values in advance to prevent one change from affecting another. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs index 879f91d5332..e34744c7d2d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Controls/ToolStrips/ToolStripManager.cs @@ -1081,13 +1081,15 @@ public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) // We only do this if the source and target toolstrips are the same bool canMerge = IsSpecialMDIStrip(sourceToolStrip); - canMerge = (canMerge || (sourceToolStrip.AllowMerge && - targetToolStrip.AllowMerge && - (sourceToolStrip.GetType().IsAssignableFrom(targetToolStrip.GetType()) || targetToolStrip.GetType().IsAssignableFrom(sourceToolStrip.GetType())))); + canMerge = canMerge + || (sourceToolStrip.AllowMerge + && targetToolStrip.AllowMerge + && (sourceToolStrip.GetType().IsAssignableFrom(targetToolStrip.GetType()) + || targetToolStrip.GetType().IsAssignableFrom(sourceToolStrip.GetType()))); + MergeHistory? mergeHistory = null; if (canMerge) { - Debug.Indent(); mergeHistory = new MergeHistory(sourceToolStrip); int originalCount = sourceToolStrip.Items.Count; @@ -1113,7 +1115,6 @@ public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) } finally { - Debug.Unindent(); sourceToolStrip.ResumeLayout(); targetToolStrip.ResumeLayout(); } @@ -1131,8 +1132,8 @@ public static bool Merge(ToolStrip sourceToolStrip, ToolStrip targetToolStrip) private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection destinationItems, Stack history) { - Debug.Indent(); MergeHistoryItem maction; + switch (source.MergeAction) { case MergeAction.MatchOnly: @@ -1235,8 +1236,6 @@ private static void MergeRecursive(ToolStripItem source, ToolStripItemCollection history.Push(maction); break; } - - Debug.Unindent(); } /// @@ -1314,7 +1313,6 @@ internal static bool RevertMergeInternal(ToolStrip targetToolStrip, ToolStrip? s reApply.Push(history.MergedToolStrip); } - Debug.Indent(); while (history.MergeHistoryItemsStack.Count > 0) { MergeHistoryItem historyItem = history.MergeHistoryItemsStack.Pop(); @@ -1331,8 +1329,6 @@ internal static bool RevertMergeInternal(ToolStrip targetToolStrip, ToolStrip? s break; } } - - Debug.Unindent(); } // Re-apply the merges of the toolstrips we had to unmerge first. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/CurrencyManager.cs b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/CurrencyManager.cs index b9914c7a8c3..dccbd02ab54 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/CurrencyManager.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/DataBinding/CurrencyManager.cs @@ -681,7 +681,6 @@ ListChangedType.PropertyDescriptorDeleted or switch (dbe.ListChangedType) { case ListChangedType.Reset: - CompModSwitches.DataCursor.TraceVerbose($"System.ComponentModel.ListChangedType.Reset Position: {Position} Count: {_list.Count}"); if (listposition == -1 && _list.Count > 0) { ChangeRecordState(0, true, false, true, false); // last false: we don't pull the data from the control when DM changes @@ -691,11 +690,10 @@ ListChangedType.PropertyDescriptorDeleted or ChangeRecordState(Math.Min(listposition, _list.Count - 1), true, false, true, false); } - UpdateIsBinding(/*raiseItemChangedEvent:*/ false); + UpdateIsBinding(raiseItemChangedEvent: false); OnItemChanged(_resetEvent); break; case ListChangedType.ItemAdded: - CompModSwitches.DataCursor.TraceVerbose($"System.ComponentModel.ListChangedType.ItemAdded {dbe.NewIndex}"); if (dbe.NewIndex <= listposition && listposition < _list.Count - 1) { // this means the current row just moved down by one. @@ -737,7 +735,6 @@ ListChangedType.PropertyDescriptorDeleted or OnItemChanged(_resetEvent); break; case ListChangedType.ItemDeleted: - CompModSwitches.DataCursor.TraceVerbose($"System.ComponentModel.ListChangedType.ItemDeleted {dbe.NewIndex}"); if (dbe.NewIndex == listposition) { // this means that the current row got deleted. @@ -763,7 +760,6 @@ ListChangedType.PropertyDescriptorDeleted or OnItemChanged(_resetEvent); break; case ListChangedType.ItemChanged: - CompModSwitches.DataCursor.TraceVerbose($"System.ComponentModel.ListChangedType.ItemChanged {dbe.NewIndex}"); // the current item changed if (dbe.NewIndex == listposition) { @@ -773,7 +769,6 @@ ListChangedType.PropertyDescriptorDeleted or OnItemChanged(new ItemChangedEventArgs(dbe.NewIndex)); break; case ListChangedType.ItemMoved: - CompModSwitches.DataCursor.TraceVerbose($"System.ComponentModel.ListChangedType.ItemMoved {dbe.NewIndex}"); if (dbe.OldIndex == listposition) { // current got moved. @@ -838,7 +833,6 @@ protected internal override void OnCurrentChanged(EventArgs e) { if (!_state.HasFlag(CurrencyManagerStates.InChangeRecordState)) { - CompModSwitches.DataView.TraceVerbose($"OnCurrentChanged() {e}"); int curLastGoodKnownRow = _lastGoodKnownRow; bool positionChanged = false; if (!_state.HasFlag(CurrencyManagerStates.SuspendPushDataInCurrentChanged)) @@ -897,7 +891,6 @@ protected virtual void OnItemChanged(ItemChangedEventArgs e) positionChanged = CurrencyManager_PushData(); } - CompModSwitches.DataView.TraceVerbose($"OnItemChanged({e.Index}) {e}"); try { _onItemChanged?.Invoke(this, e); @@ -926,7 +919,6 @@ protected internal void OnMetaDataChanged(EventArgs e) protected virtual void OnPositionChanged(EventArgs e) { - CompModSwitches.DataView.TraceVerbose($"OnPositionChanged({listposition}) {e}"); try { onPositionChangedHandler?.Invoke(this, e); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider/ErrorProvider.ErrorWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider/ErrorProvider.ErrorWindow.cs index e9dac935a5d..d37e4eab647 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider/ErrorProvider.ErrorWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/ErrorProvider/ErrorProvider.ErrorWindow.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; using System.Drawing; namespace System.Windows.Forms; @@ -398,8 +397,6 @@ public unsafe void Update(bool timerCaused) /// private void WmGetObject(ref Message m) { - Debug.WriteLineIf(CompModSwitches.MSAA.TraceInfo, $"In WmGetObject, this = {GetType().FullName}, lParam = {m.LParamInternal}"); - if (m.Msg == (int)PInvoke.WM_GETOBJECT && m.LParamInternal == PInvoke.UiaRootObjectId) { // If the requested object identifier is UiaRootObjectId, diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs index 90976531089..04ca5d4a762 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Form.cs @@ -2796,24 +2796,15 @@ private void AdjustSystemMenu() [Obsolete("This method has been deprecated. Use the ApplyAutoScaling method instead. https://go.microsoft.com/fwlink/?linkid=14202")] protected void ApplyAutoScaling() { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "ApplyAutoScaling... "); - Debug.Indent(); - // NOTE : This function is cloned in FormDocumentDesigner... remember to keep - // : them in sync - // + // NOTE : This function is cloned in FormDocumentDesigner, remember to keep them in sync. - // We also don't do this if the property is empty. Otherwise we will perform - // two GetAutoScaleBaseSize calls only to find that they returned the same - // value. - // + // We also don't do this if the property is empty. Otherwise we will perform two GetAutoScaleBaseSize + // calls only to find that they returned the same value. if (!_autoScaleBaseSize.IsEmpty) { Size baseVar = AutoScaleBaseSize; - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"base ={baseVar}"); SizeF newVarF = GetAutoScaleSize(Font); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"new(f)={newVarF}"); Size newVar = new((int)Math.Round(newVarF.Width), (int)Math.Round(newVarF.Height)); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"new(i)={newVar}"); // We save a significant amount of time by bailing early if there's no work to be done if (baseVar.Equals(newVar)) @@ -2823,16 +2814,11 @@ protected void ApplyAutoScaling() float percY = AdjustScale(newVar.Height / ((float)baseVar.Height)); float percX = AdjustScale(newVar.Width / ((float)baseVar.Width)); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"scale={percX}, {percY}"); Scale(percX, percY); - // This would ensure that we use the new - // font information to calculate the AutoScaleBaseSize. According to Triage - // this was decided to Fix in this version. - // + + // This would ensure that we use the new font information to calculate the AutoScaleBaseSize. AutoScaleBaseSize = newVar; } - - Debug.Unindent(); } /// @@ -4900,8 +4886,6 @@ protected override void Select(bool directed, bool forward) [EditorBrowsable(EditorBrowsableState.Never)] protected override void ScaleCore(float x, float y) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"{GetType().Name}::ScaleCore({x}, {y})"); - using SuspendLayoutScope scope = new(this); // Get size values in advance to prevent one change from affecting another. diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs index f777c3bd3e7..e640f0ee606 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/CommonProperties.cs @@ -2,10 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Specialized; -#if DEBUG -using System.ComponentModel; -using System.Text; -#endif using System.Drawing; namespace System.Windows.Forms.Layout; @@ -27,11 +23,6 @@ internal partial class CommonProperties private static readonly int s_maximumSizeProperty = PropertyStore.CreateKey(); private static readonly int s_layoutBoundsProperty = PropertyStore.CreateKey(); -#if DEBUG - private static readonly int s_lastKnownStateProperty = PropertyStore.CreateKey(); - -#endif - internal const ContentAlignment DefaultAlignment = ContentAlignment.TopLeft; internal const AnchorStyles DefaultAnchor = AnchorStyles.Top | AnchorStyles.Left; internal const bool DefaultAutoSize = false; @@ -57,9 +48,9 @@ internal partial class CommonProperties #region AppliesToAllLayouts - /// ClearMaximumSize + /// /// Removes the maximum size from the property store, making it "unset". - /// + /// internal static void ClearMaximumSize(IArrangedElement element) { if (element.Properties.ContainsObject(s_maximumSizeProperty)) @@ -68,14 +59,17 @@ internal static void ClearMaximumSize(IArrangedElement element) } } - /// GetAutoSize - /// Determines whether or not the System.Windows.Forms.Layout LayoutEngines - /// think the element is AutoSized. - /// - /// A control can thwart the layout engine by overriding its virtual AutoSize - /// property and not calling base. If CommonProperties.GetAutoSize(element) is false, - /// a layout engine will treat it as AutoSize = false and not size the element to its - /// preferred size. + /// + /// Determines whether or not the s + /// think the element is auto sized. + /// + /// + /// + /// A control can thwart the layout engine by overriding its virtual + /// property and not calling base. If is false, a layout engine will + /// treat it as AutoSize = false and not size the element to its preferred size. + /// + /// internal static bool GetAutoSize(IArrangedElement element) { BitVector32 state = GetLayoutState(element); @@ -83,12 +77,16 @@ internal static bool GetAutoSize(IArrangedElement element) return value != 0; } - /// GetMargin - /// Returns the Margin (exterior space) for an item - /// - /// We can not use our pattern of passing the default value into Margin because the - /// LayoutEngines read this property and do not know each element's DefaultMargin. - /// Instead the Element sets the Margin in its ctor. + /// + /// Returns the margin (exterior space) for an item. + /// + /// + /// + /// We can not use our pattern of passing the default value into because the + /// LayoutEngines read this property and do not know each element's . + /// Instead the element sets the margin in its ctor. + /// + /// internal static Padding GetMargin(IArrangedElement element) { Padding padding = element.Properties.GetPadding(s_marginProperty, out bool found); @@ -100,8 +98,9 @@ internal static Padding GetMargin(IArrangedElement element) return DefaultMargin; } - /// GetMaximumSize - /// Returns the maximum size for an element + /// + /// Returns the maximum size for an element. + /// internal static Size GetMaximumSize(IArrangedElement element, Size defaultMaximumSize) { Size size = element.Properties.GetSize(s_maximumSizeProperty, out bool found); @@ -113,8 +112,9 @@ internal static Size GetMaximumSize(IArrangedElement element, Size defaultMaximu return defaultMaximumSize; } - /// GetMinimumSize - /// Returns the minimum size for an element + /// + /// Returns the minimum size for an element. + /// internal static Size GetMinimumSize(IArrangedElement element, Size defaultMinimumSize) { Size size = element.Properties.GetSize(s_minimumSizeProperty, out bool found); @@ -126,13 +126,19 @@ internal static Size GetMinimumSize(IArrangedElement element, Size defaultMinimu return defaultMinimumSize; } - /// GetPadding - /// Returns the padding for an element - /// Typically the padding is accounted for in either the DisplayRectangle calculation - /// and/or the GetPreferredSize calculation of a control. - /// - /// NOTE: LayoutEngines should never read this property. Padding gets incorporated into - /// layout by modifying what the control reports for preferred size. + /// + /// Returns the padding for an element. + /// + /// + /// + /// Typically the padding is accounted for in either the calculation + /// and/or the calculation of a control. + /// + /// + /// NOTE: s should never read this property. Padding gets incorporated into + /// layout by modifying what the control reports for preferred size. + /// + /// internal static Padding GetPadding(IArrangedElement element, Padding defaultPadding) { Padding padding = element.Properties.GetPadding(s_paddingProperty, out bool found); @@ -144,8 +150,14 @@ internal static Padding GetPadding(IArrangedElement element, Padding defaultPadd return defaultPadding; } - /// GetSpecifiedBounds - /// Returns the last size manually set into the element. See UpdateSpecifiedBounds. + /// + /// Returns the last size manually set into the element. + /// + /// + /// + /// See . + /// + /// internal static Rectangle GetSpecifiedBounds(IArrangedElement element) { Rectangle rectangle = element.Properties.GetRectangle(s_specifiedBoundsProperty, out bool found); @@ -157,8 +169,9 @@ internal static Rectangle GetSpecifiedBounds(IArrangedElement element) return element.Bounds; } - /// ResetPadding - /// clears out the padding from the property store + /// + /// Clears out the padding from the property store. + /// internal static void ResetPadding(IArrangedElement element) { object? value = element.Properties.GetObject(s_paddingProperty); @@ -168,8 +181,9 @@ internal static void ResetPadding(IArrangedElement element) } } - /// SetAutoSize + /// /// Sets whether or not the layout engines should treat this control as auto sized. + /// internal static void SetAutoSize(IArrangedElement element, bool value) { Debug.Assert(value != GetAutoSize(element), "PERF: Caller should guard against setting AutoSize to original value."); @@ -186,8 +200,9 @@ internal static void SetAutoSize(IArrangedElement element, bool value) Debug.Assert(GetAutoSize(element) == value, "Error detected setting AutoSize."); } - /// SetMargin + /// /// Sets the margin (exterior space) for an element. + /// internal static void SetMargin(IArrangedElement element, Padding value) { Debug.Assert(value != GetMargin(element), "PERF: Caller should guard against setting Margin to original value."); @@ -199,8 +214,9 @@ internal static void SetMargin(IArrangedElement element, Padding value) LayoutTransaction.DoLayout(element.Container, element, PropertyNames.Margin); } - /// SetMaximumSize + /// /// Sets the maximum size for an element. + /// internal static void SetMaximumSize(IArrangedElement element, Size value) { Debug.Assert(value != GetMaximumSize(element, new Size(-7109, -7107)), @@ -209,7 +225,6 @@ internal static void SetMaximumSize(IArrangedElement element, Size value) element.Properties.SetSize(s_maximumSizeProperty, value); // Element bounds may need to truncated to new maximum - // Rectangle bounds = element.Bounds; bounds.Width = Math.Min(bounds.Width, value.Width); bounds.Height = Math.Min(bounds.Height, value.Height); @@ -221,8 +236,9 @@ internal static void SetMaximumSize(IArrangedElement element, Size value) Debug.Assert(GetMaximumSize(element, new Size(-7109, -7107)) == value, "Error detected setting MaximumSize."); } - /// SetMinimumSize + /// /// Sets the minimum size for an element. + /// internal static void SetMinimumSize(IArrangedElement element, Size value) { Debug.Assert(value != GetMinimumSize(element, new Size(-7109, -7107)), @@ -233,7 +249,6 @@ internal static void SetMinimumSize(IArrangedElement element, Size value) using (new LayoutTransaction(element.Container as Control, element, PropertyNames.MinimumSize)) { // Element bounds may need to inflated to new minimum - // Rectangle bounds = element.Bounds; bounds.Width = Math.Max(bounds.Width, value.Width); bounds.Height = Math.Max(bounds.Height, value.Height); @@ -243,9 +258,15 @@ internal static void SetMinimumSize(IArrangedElement element, Size value) Debug.Assert(GetMinimumSize(element, new Size(-7109, -7107)) == value, "Error detected setting MinimumSize."); } - /// SetPadding - /// Sets the padding (interior space) for an element. See GetPadding for more details. - /// NOTE: It is the callers responsibility to do layout. See Control.Padding for details. + /// + /// Sets the padding (interior space) for an element. + /// + /// + /// + /// See for more details. NOTE: It is the callers + /// responsibility to do layout. See for details. + /// + /// internal static void SetPadding(IArrangedElement element, Padding value) { Debug.Assert(value != GetPadding(element, new Padding(-7105)), @@ -257,20 +278,31 @@ internal static void SetPadding(IArrangedElement element, Padding value) Debug.Assert(GetPadding(element, new Padding(-7105)) == value, "Error detected setting Padding."); } - /// UpdateSpecifiedBounds - /// The main purpose of this function is to remember what size someone specified in the Size, Width, Height, Bounds - /// property. (Its the whole reason the BoundsSpecified enum exists.) Consider this scenario. You set a Button - /// to DockStyle.Fill, then DockStyle.None. When Dock.Filled, the Size changed to 300,300. When you - /// set it back to DockStyle.None, the size switches back to 100,23. How does this happen? - /// - /// Setting the control to Dock.Fill (via DefaultLayout engine) - /// element.SetBounds(newElementBounds, BoundsSpecified.None); - /// - /// (If someone happens to set the Size property here the specified bounds gets updated via Control.Size) - /// SetBounds(x, y, value.Width, value.Height, BoundsSpecified.Size); - /// - /// Setting the control to Dock.None (via DefaultLayout.SetDock) - /// element.SetBounds(CommonProperties.GetSpecifiedBounds(element), BoundsSpecified.None); + /// + /// Updates the specified bounds for an element. + /// + /// + /// + /// The main purpose of this function is to remember what size someone specified in the , + /// , , , property. (Its the + /// whole reason the enum exists.) Consider this scenario. You set a + /// to , then . When filled, the + /// changed to 300,300. When you set it back to the size switches back to 100,23. + /// How does this happen? + /// + /// + /// Setting the control to (via engine) + /// element.SetBounds(newElementBounds, BoundsSpecified.None); + /// + /// + /// (If someone happens to set the Size property here the specified bounds gets updated via Control.Size) + /// SetBounds(x, y, value.Width, value.Height, BoundsSpecified.Size); + /// + /// + /// Setting the control to (via DefaultLayout.SetDock) + /// element.SetBounds(CommonProperties.GetSpecifiedBounds(element), BoundsSpecified.None); + /// + /// internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int y, int width, int height, BoundsSpecified specified) { Rectangle originalBounds = GetSpecifiedBounds(element); @@ -284,7 +316,7 @@ internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int if (xChangedButNotSpecified | yChangedButNotSpecified | wChangedButNotSpecified | hChangedButNotSpecified) { - // if any of them are changed and specified cache the new value. + // If any of them are changed and specified cache the new value. if (!xChangedButNotSpecified) { @@ -327,29 +359,26 @@ internal static void UpdateSpecifiedBounds(IArrangedElement element, int x, int element.Properties.SetRectangle(s_specifiedBoundsProperty, bounds); } - /// xClearPreferredSizeCache - /// clears the preferred size cached for any control that overrides - /// the internal GetPreferredSizeCore method. DO NOT CALL DIRECTLY + /// + /// Clears the preferred size cached for any control that overrides the internal + /// method. DO NOT CALL DIRECTLY /// unless it is understood how the size of the control is going to be updated. - /// + /// internal static void xClearPreferredSizeCache(IArrangedElement element) { element.Properties.SetSize(s_preferredSizeCacheProperty, LayoutUtils.s_invalidSize); -#if DEBUG - Debug_ClearProperties(element); -#endif - Debug.Assert(xGetPreferredSizeCache(element) == Size.Empty, "Error detected in xClearPreferredSizeCache."); } - /// xClearAllPreferredSizeCaches - /// clears all the caching for an IArrangedElement hierarchy - /// typically done in dispose. + /// + /// Clears all the caching for an hierarchy. Typically done in dispose. + /// internal static void xClearAllPreferredSizeCaches(IArrangedElement start) { xClearPreferredSizeCache(start); ArrangedElementCollection controlsCollection = start.Children; + // This may have changed the sizes of our children. // PERFNOTE: This is more efficient than using Foreach. Foreach // forces the creation of an array subset enum each time we @@ -360,10 +389,11 @@ internal static void xClearAllPreferredSizeCaches(IArrangedElement start) } } - /// xGetPreferredSizeCache - /// This value is the cached result of the return value from - /// a control's GetPreferredSizeCore implementation when asked - /// for a constraining value of LayoutUtils.MaxValue (or Size.Empty too). + /// + /// This value is the cached result of the return value from a control's + /// implementation when asked for a constraining + /// value of (or too). + /// internal static Size xGetPreferredSizeCache(IArrangedElement element) { Size size = element.Properties.GetSize(s_preferredSizeCacheProperty, out bool found); @@ -375,14 +405,14 @@ internal static Size xGetPreferredSizeCache(IArrangedElement element) return Size.Empty; } - /// xSetPreferredSizeCache - /// Sets a control's preferred size. See xGetPreferredSizeCache. + /// + /// Sets a control's preferred size. See . + /// internal static void xSetPreferredSizeCache(IArrangedElement element, Size value) { - Debug.Assert(value == Size.Empty || value != xGetPreferredSizeCache(element), "PERF: Caller should guard against setting PreferredSizeCache to original value."); -#if DEBUG - Debug_SnapProperties(element); -#endif + Debug.Assert( + value == Size.Empty || value != xGetPreferredSizeCache(element), + "PERF: Caller should guard against setting PreferredSizeCache to original value."); element.Properties.SetSize(s_preferredSizeCacheProperty, value); Debug.Assert(xGetPreferredSizeCache(element) == value, "Error detected in xGetPreferredSizeCache."); } @@ -391,21 +421,23 @@ internal static void xSetPreferredSizeCache(IArrangedElement element, Size value #region DockAndAnchorLayoutSpecific - /// GetAutoSizeMode + /// /// Returns whether or not a control should snap to its smallest size /// or retain its original size and only grow if the preferred size is larger. /// We tried not having GrowOnly as the default, but it becomes difficult /// to design panels or have Buttons maintain their default size of 100,23 + /// internal static AutoSizeMode GetAutoSizeMode(IArrangedElement element) { BitVector32 state = GetLayoutState(element); return state[s_autoSizeModeSection] == 0 ? AutoSizeMode.GrowOnly : AutoSizeMode.GrowAndShrink; } - /// GetNeedsDockAndAnchorLayout - /// Do not use. Internal property for DockAndAnchor layout. - /// Returns true if DefaultLayout needs to do any work for this element. - /// (Returns false if the element is purely absolutely positioned) + /// + /// Do not use. Internal property for DockAndAnchor layout. + /// Returns if DefaultLayout needs to do any work for this element. + /// (Returns if the element is purely absolutely positioned) + /// internal static bool GetNeedsDockAndAnchorLayout(IArrangedElement element) { BitVector32 state = GetLayoutState(element); @@ -420,9 +452,10 @@ internal static bool GetNeedsDockAndAnchorLayout(IArrangedElement element) return result; } - /// GetNeedsAnchorLayout - /// Do not use. Internal property for DockAndAnchor layout. - /// Returns true if DefaultLayout needs to do anchoring for this element. + /// + /// Do not use. Internal property for DockAndAnchor layout. + /// Returns if DefaultLayout needs to do anchoring for this element. + /// internal static bool GetNeedsAnchorLayout(IArrangedElement element) { BitVector32 state = GetLayoutState(element); @@ -436,9 +469,10 @@ internal static bool GetNeedsAnchorLayout(IArrangedElement element) return result; } - /// GetNeedsDockLayout - /// Do not use. Internal property for DockAndAnchor layout. - /// Returns true if DefaultLayout needs to do docking for this element. + /// + /// Do not use. Internal property for DockAndAnchor layout. + /// Returns if DefaultLayout needs to do docking for this element. + /// internal static bool GetNeedsDockLayout(IArrangedElement element) { BitVector32 state = GetLayoutState(element); @@ -464,11 +498,12 @@ internal static bool GetSelfAutoSizeInDefaultLayout(IArrangedElement element) return (value == 1); } - /// SetAutoSizeMode + /// /// Returns whether or not a control should snap to its smallest size /// or retain its original size and only grow if the preferred size is larger. /// We tried not having GrowOnly as the default, but it becomes difficult - /// to design panels or have Buttons maintain their default size of 100,23 + /// to design panels or have Buttons maintain their default size of 100,23. + /// internal static void SetAutoSizeMode(IArrangedElement element, AutoSizeMode mode) { BitVector32 state = GetLayoutState(element); @@ -476,32 +511,32 @@ internal static void SetAutoSizeMode(IArrangedElement element, AutoSizeMode mode SetLayoutState(element, state); } - /// ShouldSelfSize + /// /// Compat flag for controls that previously sized themselves. - /// See GetSelfAutoSize comments. + /// See comments. + /// internal static bool ShouldSelfSize(IArrangedElement element) { if (GetAutoSize(element)) { - // check for legacy layout engine + // Check for legacy layout engine if (element.Container is Control { LayoutEngine: DefaultLayout }) { return GetSelfAutoSizeInDefaultLayout(element); } - // else - // - unknown element type - // - new LayoutEngine which should set the size to the preferredSize anyways. + // Unknown element type or new LayoutEngine which should set the size to the preferredSize anyways. return false; } - // autosize false things should selfsize. + // Autosize false things should selfsize. return true; } - /// SetSelfAutoSizeInDefaultLayout + /// /// Compat flag for controls that previously sized themselves. - /// See GetSelfAutoSize comments. + /// See comments. + /// internal static void SetSelfAutoSizeInDefaultLayout(IArrangedElement element, bool value) { Debug.Assert(value != GetSelfAutoSizeInDefaultLayout(element), "PERF: Caller should guard against setting AutoSize to original value."); @@ -513,9 +548,10 @@ internal static void SetSelfAutoSizeInDefaultLayout(IArrangedElement element, bo Debug.Assert(GetSelfAutoSizeInDefaultLayout(element) == value, "Error detected setting AutoSize."); } - /// xGetAnchor - - /// Do not use this. Use DefaultLayout.GetAnchor. + /// + /// Do not use this. Use . /// NOTE that Dock and Anchor are exclusive, so we store their enums in the same section. + /// internal static AnchorStyles xGetAnchor(IArrangedElement element) { BitVector32 state = GetLayoutState(element); @@ -529,9 +565,10 @@ internal static AnchorStyles xGetAnchor(IArrangedElement element) return value; } - /// xGetAutoSizedAndAnchored - - /// Do not use. Internal property for DockAndAnchor layout. - /// Returns true if the element is both AutoSized and Anchored. + /// + /// Do not use. Internal property for DockAndAnchor layout. + /// Returns if the element is both AutoSize and Anchored. + /// internal static bool xGetAutoSizedAndAnchored(IArrangedElement element) { BitVector32 state = GetLayoutState(element); @@ -623,8 +660,6 @@ internal static void xSetDock(IArrangedElement element, DockStyle value) #endregion #region FlowLayoutSpecific - // - internal static bool GetFlowBreak(IArrangedElement element) { BitVector32 state = GetLayoutState(element); @@ -650,11 +685,15 @@ internal static void SetFlowBreak(IArrangedElement element, bool value) #endregion #region AutoScrollSpecific - /// GetLayoutBounds - + /// /// This is the size used to determine whether or not we need scrollbars. - /// - /// Used if the layoutengine always want to return the same layout bounds regardless - /// of how it lays out. Example is TLP in RTL and LTR. + /// + /// + /// + /// Used if the layout engine always wants to return the same layout bounds regardless + /// of how it lays out. Example is TLP in RTL and LTR. + /// + /// internal static Size GetLayoutBounds(IArrangedElement element) { Size size = element.Properties.GetSize(s_layoutBoundsProperty, out bool found); @@ -666,24 +705,27 @@ internal static Size GetLayoutBounds(IArrangedElement element) return Size.Empty; } - /// SetLayoutBounds - + /// /// This is the size used to determine whether or not we need scrollbars. - /// - /// The TableLayout engine now calls CommonProperties.SetLayoutBounds when - /// it is done with its layout. The layoutbounds are the total column width - /// and the total row height. ScrollableControl checks if the LayoutBounds - /// has been set in the CommonProperties when it tries to figure out if it - /// should add scrollbars - but only if the layout engine is not the default - /// layout engine. If the bounds has been set, ScrollableControl will use - /// those bounds to check if scrollbars should be added, rather than doing - /// its own magic to figure it out. + /// + /// + /// + /// The engine now calls when it + /// is done with its layout. The layout bounds are the total column width and the total row height. + /// checks if the layout bounds has been set in the + /// when it tries to figure out if it should add scrollbars - but only if the layout engine is not the default + /// layout engine. If the bounds has been set, will use those bounds to check if + /// scrollbars should be added, rather than doing its own magic to figure it out. + /// + /// internal static void SetLayoutBounds(IArrangedElement element, Size value) { element.Properties.SetSize(s_layoutBoundsProperty, value); } - /// HasLayoutBounds - + /// /// Returns whether we have layout bounds stored for this element. + /// internal static bool HasLayoutBounds(IArrangedElement element) { element.Properties.GetSize(s_layoutBoundsProperty, out bool found); @@ -693,93 +735,19 @@ internal static bool HasLayoutBounds(IArrangedElement element) #endregion #region InternalCommonPropertiesHelpers - /// GetLayoutState - returns the layout state bit vector from the property store. - /// CAREFUL: this is a copy of the state. You need to SetLayoutState() to save your changes. - /// - internal static BitVector32 GetLayoutState(IArrangedElement element) - { - return new BitVector32(element.Properties.GetInteger(s_layoutStateProperty)); - } - - internal static void SetLayoutState(IArrangedElement element, BitVector32 state) - { + /// + /// Returns the layout state bit vector from the property store. + /// + /// + /// + /// CAREFUL: this is a copy of the state. You need to + /// to save your changes. + /// + /// + internal static BitVector32 GetLayoutState(IArrangedElement element) => + new BitVector32(element.Properties.GetInteger(s_layoutStateProperty)); + + internal static void SetLayoutState(IArrangedElement element, BitVector32 state) => element.Properties.SetInteger(s_layoutStateProperty, state.Data); - } - #endregion - - #region DebugHelpers -#if DEBUG - - internal static TraceSwitch PreferredSize { get; } = new("PreferredSize", "Debug preferred size assertion"); - - internal static string Debug_GetChangedProperties(IArrangedElement element) - { - string diff = string.Empty; - if (PreferredSize.TraceVerbose) - { - if (element.Properties.GetObject(s_lastKnownStateProperty) is Dictionary propertyHash) - { - StringBuilder sb = new(); - - foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(element)) - { - if (propertyHash.TryGetValue(pd.Name, out string? value) && (value != pd.Converter.ConvertToString(pd.GetValue(element)))) - { - sb.AppendLine($"Prop [{pd.Name}] OLD [{propertyHash[pd.Name]}] NEW [{pd.Converter.ConvertToString(pd.GetValue(element))}]"); - } - } - - diff = sb.ToString(); - } - } - else - { - diff = "For more info, try enabling PreferredSize trace switch"; - } - - return diff; - } - - internal static void Debug_SnapProperties(IArrangedElement element) - { - // DEBUG - store off the old state so we can figure out what has changed in a GPS assert - element.Properties.SetObject(s_lastKnownStateProperty, Debug_GetCurrentPropertyState(element)); - } - - internal static void Debug_ClearProperties(IArrangedElement element) - { - // DEBUG - clear off the old state so we can figure out what has changed in a GPS assert - element.Properties.SetObject(s_lastKnownStateProperty, null); - } - - public static Dictionary Debug_GetCurrentPropertyState(object obj) - { - Dictionary propertyHash = []; - if (PreferredSize.TraceVerbose) - { - foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(obj)) - { - if (pd.Name == "PreferredSize") - { - continue; // avoid accidentally forcing a call to GetPreferredSize - } - - try - { - if (pd.IsBrowsable && !pd.IsReadOnly && pd.SerializationVisibility != DesignerSerializationVisibility.Hidden) - { - propertyHash[pd.Name] = pd.Converter.ConvertToString(pd.GetValue(obj)); - } - } - catch - { - } - } - } - - return propertyHash; - } - -#endif #endregion } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs index 7f91eb9024a..4dea17f2f10 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/Containers/ContainerControl.cs @@ -268,21 +268,7 @@ public override BindingContext? BindingContext /// /// Container controls support ImeMode only to allow child controls to inherit it from their parents. /// - protected override bool CanEnableIme - { - get - { - // Note: If overriding this property make sure to copy the Debug code and call this method. - - Debug.Indent(); - Debug.WriteLineIf( - CompModSwitches.ImeMode.Level >= TraceLevel.Info, - $"Inside get_CanEnableIme(), value = false, this = {this}"); - Debug.Unindent(); - - return false; - } - } + protected override bool CanEnableIme => false; /// /// Indicates the current active control on the container control. @@ -1319,7 +1305,6 @@ protected internal override bool ProcessMnemonic(char charCode) _state[s_stateProcessingMnemonic] = false; } - Debug.Unindent(); return processed; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs index d48158ec06e..feb1eb53a18 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/DefaultLayout.cs @@ -3,7 +3,6 @@ using System.Collections; using System.Collections.Specialized; -using System.ComponentModel; using System.Drawing; using System.Windows.Forms.Primitives; using static System.Windows.Forms.Control; @@ -151,15 +150,6 @@ private static GrowthDirection GetGrowthDirection(IArrangedElement element) private static Rectangle GetAnchorDestination(IArrangedElement element, Rectangle displayRect, bool measureOnly) { // Container can not be null since we AnchorControls takes a non-null container. - // - // NB: DO NOT convert the following into Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "...") - // because it WILL execute GetCachedBounds(control).ToString() calls even if CompModSwitches.RichLayout.TraceInfo=false - // This in turn will lead to a cascade of native calls and callbacks - if (CompModSwitches.RichLayout.TraceInfo) - { - Debug.WriteLine($"\t\t'{element}' is anchored at {GetCachedBounds(element)}"); - } - return UseAnchorLayoutV2(element) ? ComputeAnchoredBoundsV2(element, displayRect) : ComputeAnchoredBounds(element, displayRect, measureOnly); @@ -252,24 +242,20 @@ private static Rectangle ComputeAnchoredBounds(IArrangedElement element, Rectang int top = layout.Top + displayRect.Y; int right = layout.Right + displayRect.X; int bottom = layout.Bottom + displayRect.Y; - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"\t\t...anchor dim (l,t,r,b) {{{left}, {top}, {right}, {bottom}}}"); AnchorStyles anchor = GetAnchor(element); if (IsAnchored(anchor, AnchorStyles.Right)) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting right"); right += displayRect.Width; if (!IsAnchored(anchor, AnchorStyles.Left)) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting left"); left += displayRect.Width; } } else if (!IsAnchored(anchor, AnchorStyles.Left)) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting left & right"); int center = displayRect.Width / 2; right += center; left += center; @@ -277,18 +263,15 @@ private static Rectangle ComputeAnchoredBounds(IArrangedElement element, Rectang if (IsAnchored(anchor, AnchorStyles.Bottom)) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting bottom"); bottom += displayRect.Height; if (!IsAnchored(anchor, AnchorStyles.Top)) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting top"); top += displayRect.Height; } } else if (!IsAnchored(anchor, AnchorStyles.Top)) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\t\t...adjusting top & bottom"); int center = displayRect.Height / 2; bottom += center; top += center; @@ -350,8 +333,6 @@ private static Rectangle ComputeAnchoredBounds(IArrangedElement element, Rectang } } - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"\t\t...new anchor dim (l,t,r,b) {{{left}, {top}, {right}, {bottom}}}"); - return new Rectangle(left, top, right - left, bottom - top); } @@ -368,9 +349,6 @@ internal static bool UseAnchorLayoutV2(IArrangedElement element) private static void LayoutAnchoredControls(IArrangedElement container) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\tAnchor Processing"); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"\t\tdisplayRect: {container.DisplayRectangle}"); - Rectangle displayRectangle = container.DisplayRectangle; if (CommonProperties.GetAutoSize(container) && ((displayRectangle.Width == 0) || (displayRectangle.Height == 0))) { @@ -395,7 +373,6 @@ private static void LayoutAnchoredControls(IArrangedElement container) private static Size LayoutDockedControls(IArrangedElement container, bool measureOnly) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "\tDock Processing"); Debug.Assert(!HasCachedBounds(container), "Do not call this method with an active cached bounds list."); // If measuring, we start with an empty rectangle and add as needed. @@ -655,9 +632,6 @@ private static bool TryCalculatePreferredSize(IArrangedElement container, bool m } } - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"\tanchor : {anchor}"); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"\tdock : {dock}"); - Size preferredSizeForDocking = Size.Empty; Size preferredSizeForAnchoring = Size.Empty; @@ -737,10 +711,6 @@ private static void UpdateAnchorInfo(IArrangedElement element) { Debug.Assert(!HasCachedBounds(element.Container), "Do not call this method with an active cached bounds list."); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "Update anchor info"); - Debug.Indent(); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, element.Container is null ? "No parent" : "Parent"); - if (element.Container is null) { return; @@ -776,7 +746,6 @@ private static void UpdateAnchorInfo(IArrangedElement element) anchorInfo.Bottom = elementBounds.Bottom; Rectangle parentDisplayRect = element.Container.DisplayRectangle; - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"Parent displayRectangle{parentDisplayRect}"); int parentWidth = parentDisplayRect.Width; int parentHeight = parentDisplayRect.Height; @@ -844,9 +813,6 @@ private static void UpdateAnchorInfo(IArrangedElement element) anchorInfo.Bottom -= parentHeight / 2; anchorInfo.Top -= parentHeight / 2; } - - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"anchor info (l,t,r,b): ({anchorInfo.Left}, {anchorInfo.Top}, {anchorInfo.Right}, {anchorInfo.Bottom})"); - Debug.Unindent(); } /// diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs index cd8bfd26ccf..d58ab134f18 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Layout/FlowLayout.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#if DEBUG -using System.ComponentModel; -#endif using System.Drawing; namespace System.Windows.Forms.Layout; @@ -17,31 +14,14 @@ internal partial class FlowLayout : LayoutEngine private protected override bool LayoutCore(IArrangedElement container, LayoutEventArgs args) { -#if DEBUG - Debug.WriteLineIf( - CompModSwitches.FlowLayout.TraceInfo, - $"FlowLayout::Layout(container={container}, displayRect={container.DisplayRectangle}, args={args})"); -#endif - Debug.Indent(); - // ScrollableControl will first try to get the layoutbounds from the derived control when // trying to figure out if ScrollBars should be added. CommonProperties.SetLayoutBounds(container, TryCalculatePreferredSize(container, container.DisplayRectangle, measureOnly: false)); - - Debug.Unindent(); - return CommonProperties.GetAutoSize(container); } internal override Size GetPreferredSize(IArrangedElement container, Size proposedConstraints) { -#if DEBUG - if (CompModSwitches.FlowLayout.TraceInfo) - { - Debug.WriteLine($"FlowLayout::GetPreferredSize(container={container}, proposedConstraints={proposedConstraints})"); - Debug.Indent(); - } -#endif Rectangle measureBounds = new(new Point(0, 0), proposedConstraints); Size prefSize = TryCalculatePreferredSize(container, measureBounds, measureOnly: true); @@ -54,13 +34,6 @@ internal override Size GetPreferredSize(IArrangedElement container, Size propose prefSize = TryCalculatePreferredSize(container, measureBounds, measureOnly: true); } -#if DEBUG - if (CompModSwitches.FlowLayout.TraceInfo) - { - Debug.Unindent(); - Debug.WriteLine($"GetPreferredSize returned {prefSize}"); - } -#endif return prefSize; } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs index c5fba2ba227..97e06e649f2 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/NativeWindow.cs @@ -195,8 +195,6 @@ private static int WndProcFlags if (intWndProcFlags == 0) { - Debug.Indent(); - if (t_userSetProcFlags != 0) { intWndProcFlags = t_userSetProcFlags; @@ -221,7 +219,6 @@ private static int WndProcFlags #endif intWndProcFlags |= InitializedFlags; t_wndProcFlags = (byte)intWndProcFlags; - Debug.Unindent(); } return intWndProcFlags; diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.DataStore.cs b/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.DataStore.cs index de032dcff9c..48b8ca4b9bf 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.DataStore.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.DataStore.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Specialized; -using System.ComponentModel; using System.Drawing; using System.Runtime.Serialization; @@ -28,12 +27,10 @@ public DataStoreEntry(object? data, bool autoConvert) public DataStore() { - CompModSwitches.DataObject.TraceVerbose("DataStore: Constructed DataStore"); } public virtual object? GetData(string format, bool autoConvert) { - CompModSwitches.DataObject.TraceVerbose($"DataStore: GetData: {format}, {autoConvert}"); if (string.IsNullOrWhiteSpace(format)) { return null; @@ -73,35 +70,18 @@ public DataStore() } } - if (original is not null) - { - return original; - } - else - { - return baseVar; - } + return original ?? baseVar; } - public virtual object? GetData(string format) - { - CompModSwitches.DataObject.TraceVerbose($"DataStore: GetData: {format}"); - return GetData(format, true); - } + public virtual object? GetData(string format) => GetData(format, autoConvert: true); - public virtual object? GetData(Type format) - { - CompModSwitches.DataObject.TraceVerbose($"DataStore: GetData: {format.FullName}"); - return GetData(format.FullName!); - } + public virtual object? GetData(Type format) => GetData(format.FullName!); public virtual void SetData(string format, bool autoConvert, object? data) { - CompModSwitches.DataObject.TraceVerbose($"DataStore: SetData: {format}, {autoConvert}, {data?.ToString() ?? "(null)"}"); if (string.IsNullOrWhiteSpace(format)) { ArgumentNullException.ThrowIfNull(format); - throw new ArgumentException(SR.DataObjectWhitespaceEmptyFormatNotAllowed, nameof(format)); } @@ -123,23 +103,16 @@ public virtual void SetData(string format, bool autoConvert, object? data) _data[format] = new DataStoreEntry(data, autoConvert); } - public virtual void SetData(string format, object? data) - { - CompModSwitches.DataObject.TraceVerbose($"DataStore: SetData: {format}, {data?.ToString() ?? "(null)"}"); - SetData(format, true, data); - } + public virtual void SetData(string format, object? data) => SetData(format, autoConvert: true, data); public virtual void SetData(Type format, object? data) { - CompModSwitches.DataObject.TraceVerbose($"DataStore: SetData: {format?.FullName ?? "(null)"}, {data?.ToString() ?? "(null)"}"); ArgumentNullException.ThrowIfNull(format); - SetData(format.FullName!, data); } public virtual void SetData(object? data) { - CompModSwitches.DataObject.TraceVerbose($"DataStore: SetData: {data?.ToString() ?? "(null)"}"); ArgumentNullException.ThrowIfNull(data); if (data is ISerializable @@ -153,13 +126,11 @@ public virtual void SetData(object? data) public virtual bool GetDataPresent(Type format) { - CompModSwitches.DataObject.TraceVerbose($"DataStore: GetDataPresent: {format.FullName}"); return GetDataPresent(format.FullName!); } public virtual bool GetDataPresent(string format, bool autoConvert) { - CompModSwitches.DataObject.TraceVerbose($"DataStore: GetDataPresent: {format}, {autoConvert}"); if (string.IsNullOrWhiteSpace(format)) { return false; @@ -173,42 +144,34 @@ public virtual bool GetDataPresent(string format, bool autoConvert) else { string[] formats = GetFormats(autoConvert); - CompModSwitches.DataObject.TraceVerbose($"DataStore: got {formats.Length} formats from get formats"); Debug.Assert(formats is not null, "Null returned from GetFormats"); + for (int i = 0; i < formats.Length; i++) { Debug.Assert(formats[i] is not null, $"Null format inside of formats at index {i}"); if (format.Equals(formats[i])) { - CompModSwitches.DataObject.TraceVerbose("DataStore: GetDataPresent: returning true"); return true; } } - CompModSwitches.DataObject.TraceVerbose("DataStore: GetDataPresent: returning false"); return false; } } - public virtual bool GetDataPresent(string format) - { - CompModSwitches.DataObject.TraceVerbose($"DataStore: GetDataPresent: {format}"); - return GetDataPresent(format, true); - } + public virtual bool GetDataPresent(string format) => GetDataPresent(format, autoConvert: true); public virtual string[] GetFormats(bool autoConvert) { - CompModSwitches.DataObject.TraceVerbose($"DataStore: GetFormats: {autoConvert}"); Debug.Assert(_data is not null, "data collection can't be null"); Debug.Assert(_data.Keys is not null, "data Keys collection can't be null"); string[] baseVar = new string[_data.Keys.Count]; _data.Keys.CopyTo(baseVar, 0); Debug.Assert(baseVar is not null, "Collections should never return NULL arrays!!!"); + if (autoConvert) { - CompModSwitches.DataObject.TraceVerbose("DataStore: applying autoConvert"); - // Since we are only adding elements to the HashSet, the order will be preserved. int baseVarLength = baseVar.Length; HashSet distinctFormats = new(baseVarLength); @@ -233,14 +196,9 @@ public virtual string[] GetFormats(bool autoConvert) baseVar = [.. distinctFormats]; } - CompModSwitches.DataObject.TraceVerbose($"DataStore: returning {baseVar.Length} formats from GetFormats"); return baseVar; } - public virtual string[] GetFormats() - { - CompModSwitches.DataObject.TraceVerbose("DataStore: GetFormats"); - return GetFormats(true); - } + public virtual string[] GetFormats() => GetFormats(autoConvert: true); } } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.FormatEnumerator.cs b/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.FormatEnumerator.cs index 099735d011a..3c33ad8a0e3 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.FormatEnumerator.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.FormatEnumerator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; using System.Runtime.CompilerServices; using Windows.Win32.System.Com; using ComTypes = System.Runtime.InteropServices.ComTypes; @@ -21,7 +20,6 @@ private unsafe class FormatEnumerator : ComTypes.IEnumFORMATETC, IEnumFORMATETC. public FormatEnumerator(IDataObject parent) : this(parent, parent.GetFormats()) { - CompModSwitches.DataObject.TraceVerbose($"FormatEnumerator: Constructed: {parent}"); } private FormatEnumerator(FormatEnumerator source) @@ -33,8 +31,6 @@ private FormatEnumerator(FormatEnumerator source) public FormatEnumerator(IDataObject parent, string[]? formats) { - CompModSwitches.DataObject.TraceVerbose($"FormatEnumerator: Constructed: {parent}, string[{formats?.Length ?? 0}]"); - _parent = parent; if (formats is null) @@ -60,7 +56,6 @@ public FormatEnumerator(IDataObject parent, string[]? formats) public int Next(int celt, ComTypes.FORMATETC[] rgelt, int[]? pceltFetched) { - CompModSwitches.DataObject.TraceVerbose("FormatEnumerator: Next"); if (_current >= _formats.Count || celt <= 0) { if (pceltFetched is not null) @@ -92,7 +87,6 @@ public int Next(int celt, ComTypes.FORMATETC[] rgelt, int[]? pceltFetched) public int Skip(int celt) { - CompModSwitches.DataObject.TraceVerbose("FormatEnumerator: Skip"); if (_current + celt >= _formats.Count) { return (int)HRESULT.S_FALSE; @@ -104,14 +98,12 @@ public int Skip(int celt) public int Reset() { - CompModSwitches.DataObject.TraceVerbose("FormatEnumerator: Reset"); _current = 0; return (int)HRESULT.S_OK; } public void Clone(out ComTypes.IEnumFORMATETC ppenum) { - CompModSwitches.DataObject.TraceVerbose("FormatEnumerator: Clone"); ppenum = new FormatEnumerator(this); } diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.cs b/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.cs index 7334ee72417..349b81b4b9d 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/OLE/DataObject.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Specialized; -using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; @@ -31,18 +30,13 @@ public unsafe partial class DataObject : /// Initializes a new instance of the class, with the raw /// and the managed data object the raw pointer is associated with. /// - internal DataObject(Com.IDataObject* data) - { - CompModSwitches.DataObject.TraceVerbose("Constructed DataObject based on IComDataObject"); - _innerData = ComposedDataObject.CreateFromNativeDataObject(data); - } + internal DataObject(Com.IDataObject* data) => _innerData = ComposedDataObject.CreateFromNativeDataObject(data); /// /// Initializes a new instance of the class, which can store arbitrary data. /// public DataObject() { - CompModSwitches.DataObject.TraceVerbose("Constructed DataObject standalone"); _innerData = ComposedDataObject.CreateFromWinFormsDataObject(new DataStore()); } @@ -51,7 +45,6 @@ public DataObject() /// public DataObject(object data) { - CompModSwitches.DataObject.TraceVerbose($"Constructed DataObject base on Object: {data}"); if (data is DataObject dataObject) { _innerData = dataObject._innerData; @@ -102,90 +95,49 @@ internal IDataObject TryUnwrapInnerIDataObject() /// Retrieves the data associated with the specified data format, using an automated conversion parameter to /// determine whether to convert the data to the format. /// - public virtual object? GetData(string format, bool autoConvert) - { - CompModSwitches.DataObject.TraceVerbose($"Request data: {format}, {autoConvert}"); - return ((IDataObject)_innerData).GetData(format, autoConvert); - } + public virtual object? GetData(string format, bool autoConvert) => + ((IDataObject)_innerData).GetData(format, autoConvert); /// /// Retrieves the data associated with the specified data format. /// - public virtual object? GetData(string format) - { - CompModSwitches.DataObject.TraceVerbose($"Request data: {format}"); - return GetData(format, autoConvert: true); - } + public virtual object? GetData(string format) => GetData(format, autoConvert: true); /// /// Retrieves the data associated with the specified class type format. /// - public virtual object? GetData(Type format) - { - CompModSwitches.DataObject.TraceVerbose($"Request data: {format?.FullName ?? "(null)"}"); - return format is null ? null : GetData(format.FullName!); - } + public virtual object? GetData(Type format) => format is null ? null : GetData(format.FullName!); /// /// Determines whether data stored in this instance is associated with, or can be converted to, /// the specified format. /// - public virtual bool GetDataPresent(Type format) - { - CompModSwitches.DataObject.TraceVerbose($"Check data: {format?.FullName ?? "(null)"}"); - if (format is null) - { - return false; - } - - bool present = GetDataPresent(format.FullName!); - CompModSwitches.DataObject.TraceVerbose($" ret: {present}"); - return present; - } + public virtual bool GetDataPresent(Type format) => format is not null && GetDataPresent(format.FullName!); /// /// Determines whether data stored in this instance is associated with the specified format, using an /// automatic conversion parameter to determine whether to convert the data to the format. /// - public virtual bool GetDataPresent(string format, bool autoConvert) - { - CompModSwitches.DataObject.TraceVerbose($"Check data: {format}, {autoConvert}"); - bool present = ((IDataObject)_innerData).GetDataPresent(format, autoConvert); - CompModSwitches.DataObject.TraceVerbose($" ret: {present}"); - return present; - } + public virtual bool GetDataPresent(string format, bool autoConvert) => + ((IDataObject)_innerData).GetDataPresent(format, autoConvert); /// /// Determines whether data stored in this instance is associated with, or can be converted to, /// the specified format. /// - public virtual bool GetDataPresent(string format) - { - CompModSwitches.DataObject.TraceVerbose($"Check data: {format}"); - bool present = GetDataPresent(format, autoConvert: true); - CompModSwitches.DataObject.TraceVerbose($" ret: {present}"); - return present; - } + public virtual bool GetDataPresent(string format) => GetDataPresent(format, autoConvert: true); /// /// Gets a list of all formats that data stored in this instance is associated with or can be converted to, /// using an automatic conversion parameter to determine whether to retrieve /// all formats that the data can be converted to or only native data formats. /// - public virtual string[] GetFormats(bool autoConvert) - { - CompModSwitches.DataObject.TraceVerbose($"Check formats: {autoConvert}"); - return ((IDataObject)_innerData).GetFormats(autoConvert); - } + public virtual string[] GetFormats(bool autoConvert) => ((IDataObject)_innerData).GetFormats(autoConvert); /// /// Gets a list of all formats that data stored in this instance is associated with or can be converted to. /// - public virtual string[] GetFormats() - { - CompModSwitches.DataObject.TraceVerbose("Check formats:"); - return GetFormats(autoConvert: true); - } + public virtual string[] GetFormats() => GetFormats(autoConvert: true); public virtual bool ContainsAudio() => GetDataPresent(DataFormats.WaveAudioConstant, autoConvert: false); @@ -317,38 +269,23 @@ void ComTypes.IDataObject.SetData(ref FORMATETC pFormatetcIn, ref STGMEDIUM pmed /// Stores the specified data and its associated format in this instance, using the automatic conversion /// parameter to specify whether the data can be converted to another format. /// - public virtual void SetData(string format, bool autoConvert, object? data) - { - CompModSwitches.DataObject.TraceVerbose($"Set data: {format}, {autoConvert}, {data ?? "(null)"}"); + public virtual void SetData(string format, bool autoConvert, object? data) => ((IDataObject)_innerData).SetData(format, autoConvert, data); - } /// /// Stores the specified data and its associated format in this instance. /// - public virtual void SetData(string format, object? data) - { - CompModSwitches.DataObject.TraceVerbose($"Set data: {format}, {data ?? "(null)"}"); - ((IDataObject)_innerData).SetData(format, data); - } + public virtual void SetData(string format, object? data) => ((IDataObject)_innerData).SetData(format, data); /// /// Stores the specified data and its associated class type in this instance. /// - public virtual void SetData(Type format, object? data) - { - CompModSwitches.DataObject.TraceVerbose($"Set data: {format?.FullName ?? "(null)"}, {data ?? "(null)"}"); - ((IDataObject)_innerData).SetData(format!, data); - } + public virtual void SetData(Type format, object? data) => ((IDataObject)_innerData).SetData(format!, data); /// /// Stores the specified data in this instance, using the class of the data for the format. /// - public virtual void SetData(object? data) - { - CompModSwitches.DataObject.TraceVerbose($"Set data: {data ?? "(null)"}"); - ((IDataObject)_innerData).SetData(data); - } + public virtual void SetData(object? data) => ((IDataObject)_innerData).SetData(data); HRESULT Com.IDataObject.Interface.GetData(Com.FORMATETC* pformatetcIn, Com.STGMEDIUM* pmedium) => ((Com.IDataObject.Interface)_innerData).GetData(pformatetcIn, pmedium); diff --git a/src/System.Windows.Forms/src/System/Windows/Forms/Scrolling/ScrollableControl.cs b/src/System.Windows.Forms/src/System/Windows/Forms/Scrolling/ScrollableControl.cs index 0aa12522d1a..4fa91ec96d8 100644 --- a/src/System.Windows.Forms/src/System/Windows/Forms/Scrolling/ScrollableControl.cs +++ b/src/System.Windows.Forms/src/System/Windows/Forms/Scrolling/ScrollableControl.cs @@ -301,9 +301,6 @@ protected virtual void AdjustFormScrollbars(bool displayScrollbars) private bool ApplyScrollbarChanges(Rectangle display) { - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"{GetType().Name}::ApplyScrollbarChanges({display}) {{"); - Debug.Indent(); - bool needLayout = false; bool needHscroll = false; bool needVscroll = false; @@ -527,9 +524,6 @@ private bool ApplyScrollbarChanges(Rectangle display) maxY = clientToBe.Height; } - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"Current scrollbars({HScroll}, {VScroll})"); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, $"Needed scrollbars({needHscroll}, {needVscroll})"); - // Show the needed scrollbars needLayout = (SetVisibleScrollbars(needHscroll, needVscroll) || needLayout); @@ -538,20 +532,15 @@ private bool ApplyScrollbarChanges(Rectangle display) { needLayout = (SetDisplayRectangleSize(maxX, maxY) || needLayout); } - - // Else just update the display rect size. This keeps it as big as the client - // area in a resize scenario else { + // Else just update the display rect size. This keeps it as big as the client + // area in a resize scenario. SetDisplayRectangleSize(maxX, maxY); } // Sync up the scrollbars SyncScrollbars(true); - - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, needLayout ? "Need layout" : "No layout changes"); - Debug.Unindent(); - Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "}"); return needLayout; }