File: MobileContainerDesigner.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (664 lines) | stat: -rw-r--r-- 24,739 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//------------------------------------------------------------------------------
// <copyright file="MobileContainerDesigner.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.Design.MobileControls
{
    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Diagnostics;
    using System.Drawing;
    using System.Globalization;
    using System.Reflection;
    using System.Web.UI.Design.MobileControls.Adapters;
    using System.Web.UI.MobileControls;
    using System.Web.UI.MobileControls.Adapters;

    using IHTMLElement = NativeMethods.IHTMLElement;
    using IHTMLElementCollection = NativeMethods.IHTMLElementCollection;

    /// <summary>
    ///    <para>Provides a base designer class for all mobile container controls.</para>
    /// </summary>
    [
        System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
        Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
    ]
    [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
    internal abstract class MobileContainerDesigner : ControlDesigner, IMobileDesigner
    {
        private MobileControl               _mobileControl;
        private readonly Size               _defaultSize;
        private bool                        _containmentStatusDirty = true;
        private bool                        _hasAttributesCached = false;
        private bool                        _shouldDirtyPage = false;
        private ContainmentStatus           _containmentStatus = ContainmentStatus.Unknown;
        private IDictionary                 _behaviorAttributes;
        private String                      _currentErrorMessage = null;
        private IWebFormsDocumentService    _iWebFormsDocumentService;
        private IMobileWebFormServices      _iMobileWebFormServices;
        private EventHandler                _loadComplete = null;

        // cached Behavior object
        private IHtmlControlDesignerBehavior _cachedBehavior = null;

        /// <summary>
        ///    <para>
        ///       Initializes an instance of the <see cref='System.Web.UI.Design.MobileControls.MobileContainerDesigner'/> class.
        ///    </para>
        /// </summary>
        internal MobileContainerDesigner()
        {
            ReadOnly = false;

            _defaultSize = new Size(300, 100);
            _behaviorAttributes = new HybridDictionary();
        }

        /// <summary>
        /// return the containment status
        /// </summary>
        protected ContainmentStatus ContainmentStatus
        {
            get
            {
                if (!_containmentStatusDirty)
                {
                    return _containmentStatus;
                }

                _containmentStatus =
                    DesignerAdapterUtil.GetContainmentStatus(_mobileControl);

                _containmentStatusDirty = false;
                return _containmentStatus;
            }
        }

        internal Object DesignTimeElementInternal
        {
            get
            {
                return typeof(HtmlControlDesigner).InvokeMember("DesignTimeElement", 
                    BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic, 
                    null, this, null, CultureInfo.InvariantCulture);
            }
        }

        private IMobileWebFormServices IMobileWebFormServices
        {
            get
            {
                if (_iMobileWebFormServices == null)
                {
                    _iMobileWebFormServices =
                        (IMobileWebFormServices)GetService(typeof(IMobileWebFormServices));
                }

                return _iMobileWebFormServices;
            }
        }

        private IWebFormsDocumentService IWebFormsDocumentService
        {
            get
            {
                if (_iWebFormsDocumentService == null)
                {
                    _iWebFormsDocumentService =
                        (IWebFormsDocumentService)GetService(typeof(IWebFormsDocumentService));

                    Debug.Assert(_iWebFormsDocumentService != null);
                }

                return _iWebFormsDocumentService;
            }
        }

        /// <summary>
        ///     Indicates whether the initial page load is completed
        /// </summary>
        protected bool LoadComplete
        {
            get
            {
                return !IWebFormsDocumentService.IsLoading;
            }
        }

        /// <summary>
        ///    Control's style, available only when page is MobilePage
        /// </summary>
        protected Style Style
        {
            get
            {
                if (!DesignerAdapterUtil.InMobilePage(_mobileControl))
                {
                    return null;
                }

                Style style = ((ControlAdapter)_mobileControl.Adapter).Style;

                // Each MobileControl should have its own style
                Debug.Assert(style != null);

                return style;
            }
        }

        /// <summary>
        ///    Apply style related properties to behavior
        /// </summary>
        /// <param name="propName">
        ///    property that needs to be applied, null to apply all
        /// </param>
        private void ApplyPropertyToBehavior(String propName)
        {
            if (Style == null)
            {
                return;
            }

            if (propName == null || propName.Equals("BackColor"))
            {
                Color backColor = (Color)Style[Style.BackColorKey, true];
                SetBehaviorStyle("backgroundColor", ColorTranslator.ToHtml(backColor));
            }
            if (propName == null || propName.Equals("ForeColor"))
            {
                Color foreColor = (Color)Style[Style.ForeColorKey, true];
                SetBehaviorStyle("color", ColorTranslator.ToHtml(foreColor));
            }
            if (propName == null || propName.Equals("Font"))
            {
                bool bold =
                    (BooleanOption)Style[Style.BoldKey, true] == BooleanOption.True;
                bool italic =
                    (BooleanOption)Style[Style.ItalicKey, true] == BooleanOption.True;
                FontSize  fontSize  = (FontSize) Style[Style.FontSizeKey , true];
                String    fontName  = (String)   Style[Style.FontNameKey , true];

                SetBehaviorStyle("fontWeight", bold? "bold" : "normal");
                SetBehaviorStyle("fontStyle", italic? "italic" : "normal");

                if (fontSize == FontSize.Large)
                {
                    SetBehaviorStyle("fontSize", "medium");
                }
                else if (fontSize == FontSize.Small)
                {
                    SetBehaviorStyle("fontSize", "x-small");
                }
                else
                {
                    RemoveBehaviorStyle("fontSize");
                }

                SetBehaviorStyle("fontFamily", fontName);
            }
            if (propName == null || propName.Equals("Alignment"))
            {
                Alignment alignment = (Alignment)Style[Style.AlignmentKey, true];
                bool alignmentNotSet = alignment == Alignment.NotSet;

                SetBehaviorStyle("textAlign",
                    alignmentNotSet ? "" : Enum.Format(typeof(Alignment), alignment, "G"));
            }
        }

        /// <summary>
        ///   Performs the cleanup of the designer class.
        /// </summary>
        /// <seealso cref='IDesigner'/>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_loadComplete != null)
                {
                    IWebFormsDocumentService.LoadComplete -= _loadComplete;
                    _loadComplete = null;
                }
            }

            base.Dispose(disposing);
        }

        /// <summary>
        ///   The default size of Container Control.
        /// </summary>
        protected virtual Size GetDefaultSize()
        {
            return _defaultSize;
        }

        /// <summary>
        ///    non-null string will render the text as an image
        ///    on the top of container control.
        /// </summary>
        protected virtual String GetErrorMessage(out bool infoMode)
        {
            infoMode = false;
            return null;
        }

        /// <summary>
        ///    <para>
        ///       Initializes the designer using
        ///       the specified component.
        ///    </para>
        /// </summary>
        /// <param name='component'>
        ///    The control element being designed.
        /// </param>
        /// <remarks>
        ///    <para>
        ///       This is called by the designer host to establish the component being
        ///       designed.
        ///    </para>
        /// </remarks>
        /// <seealso cref='System.ComponentModel.Design.IDesigner'/>
        public override void Initialize(IComponent component)
        {
            Debug.Assert(component is MobileControl,
                         "MobileContainerDesigner.Initialize - Invalid Mobile Control");

            _mobileControl = (MobileControl) component;
            base.Initialize(component);

            _loadComplete = new EventHandler(this.OnLoadComplete);
            IWebFormsDocumentService.LoadComplete += _loadComplete;
        }

        /// <summary>
        ///    return true if the property is an appearance attribute that needs
        ///    to apply to all child controls.
        /// </summary>
        /// <param name="propertyName">
        /// </param>
        private bool IsAppearanceAttribute(String propertyName)
        {
            return (
                propertyName.Equals("Font") ||
                propertyName.Equals("ForeColor") ||
                propertyName.Equals("BackColor") ||
                propertyName.Equals("Wrapping") ||
                propertyName.Equals("Alignment") ||
                propertyName.Equals("StyleReference"));
        }

        internal virtual void OnBackgroundImageChange(String message, bool infoMode)
        {
        }

        /// <summary>
        ///    <para>
        ///       Notification that is called when the designer is attached to the behavior.
        ///    </para>
        /// </summary>
        protected override void OnBehaviorAttached()
        {
            Debug.Assert(_cachedBehavior == null);
            _cachedBehavior = Behavior;

            PrefixDeviceSpecificTags();
            base.OnBehaviorAttached();

            // Reload the original state if an old Behavior is cached.
            if (_hasAttributesCached)
            {
                ReloadBehaviorState();
            }
        }

        /// <summary>
        ///    Notification that is called when the behavior is detached from designer
        /// </summary>
        protected override void OnBehaviorDetaching()
        {
            // dispose the cached behavior.
            _cachedBehavior = null;
        }

        /// <summary>
        ///    <para>
        ///       Delegate to handle component changed event.
        ///    </para>
        /// </summary>
        /// <param name='sender'>
        ///    The object sending the event.
        /// </param>
        /// <param name='ce'>
        ///    The event object used when firing a component changed notification.
        /// </param>
        /// <remarks>
        ///    <para>
        ///       This is called after a property has been changed. It allows the implementor
        ///       to do any post-processing that may be needed after a property change.
        ///    </para>
        /// </remarks>
        public override void OnComponentChanged(Object sender, ComponentChangedEventArgs ce)
        {
            // Delegate to the base class implementation first!
            base.OnComponentChanged(sender, ce);

            MemberDescriptor member = ce.Member;
            if (member != null &&
                member.GetType().FullName.Equals(Constants.ReflectPropertyDescriptorTypeFullName))
            {
                PropertyDescriptor propDesc = (PropertyDescriptor)member;
                String propName = propDesc.Name;

                if (IsAppearanceAttribute(propName))
                {
                    // Update control rendering
                    UpdateRenderingRecursive();
                }
            }
        }

        /// <summary>
        ///   Subclasses can override to modify their container appearance,
        ///   this method is invoked by OnLoadComplete()
        /// </summary>
        protected virtual void OnContainmentChanged()
        {
            // do nothing
        }

        /// <summary>
        ///     helper method for external UIs
        /// </summary>
        protected virtual void OnInternalChange()
        {
            ISite site = _mobileControl.Site;
            if (site != null)
            {
                IComponentChangeService changeService =
                    (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
                if (changeService != null)
                {
                    try
                    {
                        changeService.OnComponentChanging(_mobileControl, null);
                    }
                    catch (CheckoutException ex)
                    {
                        if (ex == CheckoutException.Canceled)
                            return;
                        throw;
                    }
                    changeService.OnComponentChanged(_mobileControl, null, null, null);
                }
            }
        }

        /// <summary>
        ///    <para>
        ///       Notification that is called when the page completes loading.
        ///    </para>
        /// </summary>
        private void OnLoadComplete(Object source, EventArgs e)
        {
            // Need to apply behavior attributes since none are cached
            if (!_hasAttributesCached)
            {
                SetControlDefaultAppearance();

                // Apply the style properties to Behavior
                ApplyPropertyToBehavior(null);
            }

            bool infoMode = false;
            String msg = GetErrorMessage(out infoMode);
            if (msg != _currentErrorMessage || !_hasAttributesCached)
            {
                OnBackgroundImageChange(msg, infoMode);
                _currentErrorMessage = msg;
            }

            // we could reload the attributes
            _hasAttributesCached = true;

            // Change containment related appearance
            OnContainmentChanged();

            // Don't forget the change children appearance,
            // this call is necessary to solve multi-nested control problem.
            UpdateRenderingRecursive();

            // Make the page dirty by calling OnInternalChange if an subsitution occurs.
            if (_shouldDirtyPage)
            {
                OnInternalChange();
                _shouldDirtyPage = false;
            }
        }

        /// <summary>
        ///    <para>
        ///       Notification that is called when the associated control is parented.
        ///    </para>
        /// </summary>
        public override void OnSetParent()
        {
            base.OnSetParent();

            // The containment status is invalidated
            _containmentStatusDirty = true;

            // Make sure the control refreshes when it is moved around
            if (LoadComplete)
            {
                OnLoadComplete(this, EventArgs.Empty);
            }
        }

        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);

            PropertyDescriptor property = (PropertyDescriptor) properties["Expressions"];
            if (property != null) {
                properties["Expressions"] = TypeDescriptor.CreateProperty(this.GetType(), property, BrowsableAttribute.No);
            }
        }

        /// <summary>
        ///    dynamically transform DeviceSpecific element to a server control,
        ///    called from OnBehaviorAttached
        /// </summary>
        private void PrefixDeviceSpecificTags()
        {
            IHTMLElement htmlElement = (IHTMLElement) DesignTimeElementInternal;
            Debug.Assert(htmlElement != null,
                "Invalid HTML element in FormDesigner.OnBehaviorAttached");

            IWebFormReferenceManager refMgr =
                (IWebFormReferenceManager) GetService(typeof(IWebFormReferenceManager));
            Debug.Assert(refMgr != null, "Did not get back IWebFormReferenceManager service.");

            String tagPrefix = refMgr.GetTagPrefix(typeof(DeviceSpecific));
            Debug.Assert(tagPrefix != null && tagPrefix.Length > 0, "TagPrefix is invalid");

            IHTMLElementCollection allChildren = (IHTMLElementCollection) htmlElement.GetChildren();
            if (null != allChildren)
            {
                bool substitutions = false;
                int nestingLevel = 0;
                String modifiedInnerHTML = String.Empty;
                for (Int32 i = 0; i < allChildren.GetLength(); i++)
                {
                    IHTMLElement htmlChild = (IHTMLElement) allChildren.Item(i, 0);
                    Debug.Assert(null != htmlChild, "htmlChild is null");
                    String childContent = htmlChild.GetOuterHTML();
                    String childUpperContent = childContent.ToUpper(CultureInfo.InvariantCulture);
                    if (childContent.StartsWith("<", StringComparison.Ordinal) &&
                        !(childContent.StartsWith("</", StringComparison.Ordinal) || (childContent.EndsWith("/>", StringComparison.Ordinal))))
                    {
                        if (!childUpperContent.StartsWith("<" + tagPrefix.ToUpper(CultureInfo.InvariantCulture) + ":", StringComparison.Ordinal))
                        {
                            nestingLevel++;
                        }
                    }
                    else if (childContent.StartsWith("</", StringComparison.Ordinal))
                    {
                        nestingLevel--;
                    }
                    if (1 == nestingLevel &&
                        childUpperContent.StartsWith("<DEVICESPECIFIC", StringComparison.Ordinal) &&
                        childUpperContent.EndsWith(">", StringComparison.Ordinal))
                    {
                        Debug.Assert(substitutions == false, "substitutions is true");
                        modifiedInnerHTML += "<" + tagPrefix + ":DeviceSpecific runat=\"server\">\r\n";
                        substitutions = true;
                    }
                    else if (1 == nestingLevel &&
                             childUpperContent.StartsWith("<DEVICESPECIFIC", StringComparison.Ordinal) &&
                             childUpperContent.EndsWith("/>", StringComparison.Ordinal))
                    {
                        modifiedInnerHTML += "<" + tagPrefix + ":DeviceSpecific runat=\"server\"></" + tagPrefix + ":DeviceSpecific>\r\n";
                        substitutions = true;
                    }
                    else if (0 == nestingLevel && 0 == String.Compare(childUpperContent, "</DEVICESPECIFIC>", StringComparison.Ordinal))
                    {
                        Debug.Assert(substitutions == true, "substitutions is false");
                        modifiedInnerHTML += "</" + tagPrefix + ":DeviceSpecific>\r\n";
                    }
                    else
                    {
                        modifiedInnerHTML += childContent + "\r\n";
                    }
                }
                if (substitutions)
                {
                    _shouldDirtyPage = true;
                    htmlElement.SetInnerHTML(modifiedInnerHTML);
                }
            }
        }

        /// <summary>
        ///    Reload the cached Behavior states
        /// </summary>
        private void ReloadBehaviorState()
        {
            Debug.Assert(Behavior != null && _behaviorAttributes != null);

            IDictionaryEnumerator enumerator = _behaviorAttributes.GetEnumerator();
            while (enumerator.MoveNext())
            {
                String key = (String)enumerator.Key;
                Object obj = _behaviorAttributes[key];

                Behavior.SetStyleAttribute(key, true, obj, true);
            }
        }

        /// <summary>
        ///    Remove the attribute from Behavior
        /// </summary>
        /// <param name="attribute">
        ///    attribute that need to be removed.
        /// </param>
        protected void RemoveBehaviorStyle(String attribute)
        {
            Debug.Assert (_behaviorAttributes != null);

            if (Behavior != null)
            {
                Behavior.RemoveStyleAttribute(attribute, true, true);
            }

            // also remove the cached attribute
            _behaviorAttributes.Remove(attribute);
        }

        /// <summary>
        ///    Apply the style attribute to Behavior
        /// </summary>
        /// <param name="attribute">
        ///    attribute that needs to be applied to Behavior
        /// </param>
        /// <param name="obj">
        ///    value to apply
        /// </param>
        protected void SetBehaviorStyle(String attribute, Object obj)
        {
            Debug.Assert (obj != null, "null object passed in!");
            Debug.Assert (_behaviorAttributes != null);

            // here we cache the value;
            // Note that the value is cached even if Behavior is not available,
            // this is because this method could be called between Behavior
            // detached and attached events, we want to re-apply these lost
            // attributes when Behavior is attached again.
            _behaviorAttributes[attribute] = obj;

            if (Behavior == null)
            {
                return;
            }
            Behavior.SetStyleAttribute(attribute, true, obj, true);
        }

        /// <summary>
        ///    This method will be called only once when the control is first created.
        /// </summary>
        protected virtual void SetControlDefaultAppearance()
        {
            // Default border appearance
            SetBehaviorStyle("borderWidth", "1px");
            SetBehaviorStyle("borderColor", ColorTranslator.ToHtml(SystemColors.ControlDark));

            // Default margin, paddings for container controls.
            SetBehaviorStyle("paddingTop", "8px");
            SetBehaviorStyle("paddingBottom", "8px");
            SetBehaviorStyle("paddingRight", "4px");
            SetBehaviorStyle("paddingLeft", "5px");
            SetBehaviorStyle("marginTop", "3px");
            SetBehaviorStyle("marginBottom", "3px");
            SetBehaviorStyle("marginRight", "5px");
            SetBehaviorStyle("marginLeft", "5px");

            // Setup background parameters
            SetBehaviorStyle("backgroundRepeat", "no-repeat");
            SetBehaviorStyle("backgroundAttachment", "fixed");
            SetBehaviorStyle("backgroundPositionX", "left");
            SetBehaviorStyle("backgroundPositionY", "top");

            // Container sze info.
            SetBehaviorStyle("height", GetDefaultSize().Height);
            SetBehaviorStyle("width", GetDefaultSize().Width);
        }

        /// <summary>
        ///   Update the designtime rendering for the container control
        /// </summary>
        public void UpdateRendering()
        {
            _mobileControl.RefreshStyle();
            ApplyPropertyToBehavior(null);
        }

        /// <summary>
        ///   Update the designtime rendering for the container control and all controls
        ///   inside this container control.
        /// </summary>
        private void UpdateRenderingRecursive()
        {
            UpdateRendering();

            if (IMobileWebFormServices != null)
            {
                IMobileWebFormServices.UpdateRenderingRecursive(_mobileControl);
            }
        }
    }
}