public InvariantTestCase
   ( IMessageSink diagnosticMessageSink
   , TestMethodDisplay defaultMethodDisplay
   , ITestMethod testMethod
   , Invariant inv
   , object[] testMethodArguments = null
   )
     : base
     ( diagnosticMessageSink
     , defaultMethodDisplay
     , testMethod
     , testMethodArguments
     )
 {
     Inv = inv;
 }
Exemplo n.º 2
0
 public static IStreamable <Empty, TPayload> ToCleanStreamable <TPayload>(this StreamEvent <TPayload>[] input)
 {
     Invariant.IsNotNull(input, "input");
     return(input.OrderBy(v => v.SyncTime).ToArray().ToStreamable());
 }
Exemplo n.º 3
0
 protected void AddNicToVm(IVm vm, VirtualNicType nicType, string vswitchName, NicConnectionStatus nicStatus, string nicGuid, int VLan)
 {
     using (IVirtualSystemManagementService managmentService = VirtualSystemManagementService.GetVirtualSystemManagmentService(this._Host))
     {
         using (IVirtualEthernetSwitch virtualEthernetSwitch = VirtualEthernetSwitch.Query(this._Host, "ElementName='{0}'", (object)vswitchName).FirstOrDefault <IVirtualEthernetSwitch>())
         {
             if (virtualEthernetSwitch == null)
             {
                 throw new HyperVException("Virtual Ethernet switch '" + vswitchName + "' not found");
             }
             using (IVirtualSystemSettingData systemSettingData = ((IVmInternals)vm).ComputerSystem.GetVirtualSystemSettingData())
             {
                 ICommonEthernetPortSettingData ethernetPortSettingData;
                 if (nicType != VirtualNicType.Legacy)
                 {
                     if (nicType != VirtualNicType.Synthetic)
                     {
                         throw new HyperVException("I don't know about the nic type " + nicType.ToString());
                     }
                     ethernetPortSettingData = (ICommonEthernetPortSettingData)SyntheticEthernetPortSettingData.GetDefaultSyntheticAdapter(this._Host);
                     ((ISyntheticEthernetPortSettingData)ethernetPortSettingData).VirtualSystemIdentifiers = new string[1]
                     {
                         nicGuid
                     };
                     ethernetPortSettingData.ElementName = "Synthetic Network Adapter";
                 }
                 else
                 {
                     ethernetPortSettingData             = (ICommonEthernetPortSettingData)EmulatedEthernetPortSettingData.GetDefaultLegacyAdapter(this._Host);
                     ethernetPortSettingData.ElementName = "Legacy Network Adapter";
                 }
                 using (ethernetPortSettingData)
                 {
                     ethernetPortSettingData.StaticMacAddress = false;
                     using (IResourceAllocationSettingData allocationSettingData1 = managmentService.AddResourceSettings(systemSettingData, new string[1]
                     {
                         ((IWMICommon)ethernetPortSettingData).Object.GetText(TextFormat.WmiDtd20)
                     }).FirstOrDefault <IResourceAllocationSettingData>())
                     {
                         if (nicStatus != NicConnectionStatus.Connected)
                         {
                             return;
                         }
                         using (IEthernetPortAllocationSettingData allocationSettingData2 = EthernetPortAllocationSettingData.GetDefaultEthernetPortAllocationSettingData(this._Host))
                         {
                             using (IVirtualSwitch virtualSwitchByName = this.GetVirtualSwitchByName(vswitchName))
                             {
                                 Invariant.ArgumentNotNull((object)allocationSettingData2, "Switch port not found");
                                 Invariant.ArgumentNotNull((object)virtualSwitchByName, "Virtual switch '" + vswitchName + "' not found");
                                 allocationSettingData2.Parent       = ((IWMICommon)allocationSettingData1).Object.Path.Path;
                                 allocationSettingData2.HostResource = new string[1]
                                 {
                                     virtualSwitchByName.Object.Path.Path
                                 };
                                 managmentService.AddResourceSettings(systemSettingData, new string[1]
                                 {
                                     ((IWMICommon)allocationSettingData2).Object.GetText(TextFormat.WmiDtd20)
                                 }).FirstOrDefault <IResourceAllocationSettingData>().TryDispose();
                             }
                         }
                     }
                 }
             }
         }
     }
 }
        private object _GetSaveHistoryBytesDelegate(object arg)
        {
            bool flag = (bool)arg;

            ApplicationProxyInternal.SaveHistoryReturnInfo saveHistoryReturnInfo = new ApplicationProxyInternal.SaveHistoryReturnInfo();
            if (this._serviceProvider == null)
            {
                return(null);
            }
            if (Application.IsApplicationObjectShuttingDown)
            {
                return(null);
            }
            Invariant.Assert(this._rbw.Value != null, "BrowserJournalingError: _rbw should not be null");
            Journal journal = this._rbw.Value.Journal;

            Invariant.Assert(journal != null, "BrowserJournalingError: Could not get internal journal for the window");
            JournalEntry journalEntry;

            if (flag)
            {
                NavigationService navigationService = this._rbw.Value.NavigationService;
                try
                {
                    navigationService.RequestCustomContentStateOnAppShutdown();
                }
                catch (Exception ex)
                {
                    if (CriticalExceptions.IsCriticalException(ex))
                    {
                        throw;
                    }
                }
                journal.PruneKeepAliveEntries();
                journalEntry = navigationService.MakeJournalEntry(JournalReason.NewContentNavigation);
                if (journalEntry != null && !journalEntry.IsAlive())
                {
                    if (journalEntry.JEGroupState.JournalDataStreams != null)
                    {
                        journalEntry.JEGroupState.JournalDataStreams.PrepareForSerialization();
                    }
                    journal.UpdateCurrentEntry(journalEntry);
                }
                else
                {
                    journalEntry = journal.GetGoBackEntry();
                }
            }
            else
            {
                journalEntry = journal.CurrentEntry;
            }
            if (journalEntry != null)
            {
                saveHistoryReturnInfo.title   = journalEntry.Name;
                saveHistoryReturnInfo.entryId = journalEntry.Id;
            }
            else
            {
                saveHistoryReturnInfo.title = this._rbw.Value.Title;
            }
            saveHistoryReturnInfo.uri = BindUriHelper.UriToString(this.Uri);
            MemoryStream memoryStream = new MemoryStream();

            memoryStream.Seek(0L, SeekOrigin.Begin);
            if (flag)
            {
                ApplicationProxyInternal.BrowserJournal browserJournal = new ApplicationProxyInternal.BrowserJournal(journal, BindUriHelper.BaseUri);
                new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert();
                try
                {
                    memoryStream.WriteByte(2);
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(memoryStream, browserJournal);
                    goto IL_1A6;
                }
                catch (Exception ex2)
                {
                    if (CriticalExceptions.IsCriticalException(ex2))
                    {
                        throw;
                    }
                    Invariant.Assert(false, "Failed to serialize the navigation journal: " + ex2);
                    goto IL_1A6;
                }
                finally
                {
                    CodeAccessPermission.RevertAll();
                }
            }
            memoryStream.WriteByte(1);
            ApplicationProxyInternal.WriteInt32(memoryStream, saveHistoryReturnInfo.entryId);
IL_1A6:
            saveHistoryReturnInfo.saveByteArray = memoryStream.ToArray();
            ((IDisposable)memoryStream).Dispose();
            return(saveHistoryReturnInfo);
        }
Exemplo n.º 5
0
        //------------------------------------------------------
        //
        //  Internal Methods
        //
        //------------------------------------------------------

        #region Internal Methods

        //-------------------------------------------------------------------
        // GetParaProperties
        //-------------------------------------------------------------------
        internal override void GetParaProperties(
            ref PTS.FSPAP fspap)     // OUT: paragraph properties
        {
            Invariant.Assert(false); // No para properties for row.
        }
Exemplo n.º 6
0
 public static QuantileStream NewStream(Invariant invariant)
 {
     return new QuantileStream(new SampleStream(invariant), new List<Sample> {Capacity = 500}, true);
 }
Exemplo n.º 7
0
 public void CheckInvariantAdmissibility(Invariant inv) {
   DeclaringMember = inv;
   StateStack = new System.Collections.Stack();
   ResetCurrentState();
   this.VisitExpression(inv.Condition);
 }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NinjectAdapter"/> class.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        public NinjectAdapter(IKernel kernel)
        {
            Invariant.IsNotNull(kernel, "kernel");

            Kernel = kernel;
        }
Exemplo n.º 9
0
        void IFilter.GetText(ref uint bufCharacterCount, IntPtr pBuffer)
        {
            if (_filter == null)
            {
                throw new COMException(SR.Get(SRID.FileToFilterNotLoaded),
                                       (int)FilterErrorCode.FILTER_E_ACCESS);
            }

            // NULL is not an acceptable value for pBuffer
            if (pBuffer == IntPtr.Zero)
            {
                throw new NullReferenceException(SR.Get(SRID.FilterNullGetTextBufferPointer));
            }

            // If there is 0 byte to write, this is a no-op.
            if (bufCharacterCount == 0)
            {
                return;
            }

            // Because we should always return the string with null terminator, a buffer size
            // of one character can hold the null terminator only, we can always write the
            // terminator to the buffer and return directly.
            if (bufCharacterCount == 1)
            {
                Marshal.WriteInt16(pBuffer, 0);
                return;
            }

            // Record the original buffer size. bufCharacterCount may be changed later.
            // The original buffer size will be used to identify a special
            // case later.
            uint origianlBufferSize = bufCharacterCount;

            // Normalize the buffer size, for a very large size could be due to a bug or an attempted attack.
            if (bufCharacterCount > _maxTextBufferSizeInCharacters)
            {
                bufCharacterCount = _maxTextBufferSizeInCharacters;
            }

            // Memorize the buffer size.
            // We need to reserve a character for the terminator because we don't know
            // whether the underlying layer will take care of it.
            uint maxSpaceForContent = --bufCharacterCount;

            // Retrieve the result and its size.
            _filter.GetText(ref bufCharacterCount, pBuffer);

            // An increase in the in/out size parameter would be anomalous, and could be ill-intentioned.
            if (bufCharacterCount > maxSpaceForContent)
            {
                throw new COMException(SR.Get(SRID.AuxiliaryFilterReturnedAnomalousCountOfCharacters),
                                       (int)FilterErrorCode.FILTER_E_ACCESS);
            }

            // We need to handle a tricky case if the input buffer size is 2 characters.
            //
            // In this case, we actually request 1 character from the underlying layer
            // because we always reserve one character for the terminator.
            //
            // There are two possible scenarios for the returned character in the buffer:
            // 1.   If the underlying layer will pad the returning string
            // with the null terminator, then the returned character in the buffer is null.
            // In this case we cannot return anything useful to the user, which is not expected.
            // What the users would expect is getting a string with one character
            // and one null terminator when passing a buffer with size of 2 characters to us.
            // 2.   If the underlying layer will NOT pad the returning string
            // with the null terminator, then we have a useful character returned.
            // Then we pad the buffer with string terminator null, and give back to the user.
            // This case meets the users' expectation.
            //
            // So we need to discover the behavior of the underlying layer and act properly.
            // Following is a solution:
            // 1.   Check the returned character in the buffer.
            //      If it's a null, then we have scenario 1. Goto step 2.
            //      If it's not a null, then we have scenario 2. Goto step 3.
            // 2.   Call the underlying layer's GetText() again, but passing buffer size of 2.
            // 3.   Pad the buffer with null string terminator and return.
            if (origianlBufferSize == 2)
            {
                short shCharacter = Marshal.ReadInt16(pBuffer);
                if (shCharacter == '\0')
                {
                    // Scenario 1. Call underlying layer again with the actual buffer size.
                    bufCharacterCount = 2;
                    _filter.GetText(ref bufCharacterCount, pBuffer);

                    // An increase in the in/out size parameter would be anomalous, and could be ill-intentioned.
                    if (bufCharacterCount > 2)
                    {
                        throw new COMException(SR.Get(SRID.AuxiliaryFilterReturnedAnomalousCountOfCharacters),
                                               (int)FilterErrorCode.FILTER_E_ACCESS);
                    }

                    if (bufCharacterCount == 2)
                    {
                        // If the underlying layer GetText() returns 2 characters, we need to check
                        // whether the second character is null. If it's not, then its behavior
                        // does not match the scenario 1, we cannot handle it.
                        shCharacter = Marshal.ReadInt16(pBuffer, _int16Size);

                        // We don't throw exception because such a behavior violation is not acceptable.
                        // We'd better terminate the entire process.
                        Invariant.Assert(shCharacter == '\0');

                        // Then we adjust the point where we should put our null terminator.
                        bufCharacterCount = 1;
                    }
                    // If the underlying layer GetText() returns 0 or 1 character, we
                    // don't need to do anything.
                }
            }
            // If the buffer size is bigger than 2, then we don't care the behavior of the
            // underlying layer. The string buffer we return may contain 2 null terminators
            // if the underlying layer also pads the terminator. But there will be at least one
            // non-null character in the buffer if there is any text to get. So the users will get
            // something useful.
            //
            // One possible proposal is to generalize the special case: why not make the returned
            // string more uniform, in which there is only one terminator always? We discussed this
            // proposal. To achieve this, we must know the behavior of the underlying layer.
            // We need to call the underlying layer twice.

            // The first call is to request for one character to test the behavior.
            // If the returned character is null, then the underlying
            // layer is a conforming filter, which will pad a null terminator for the string it
            // returns. Otherwise, the underlying layer is non-conforming.
            //
            // Suppose the input buffer size is N, then if underlying layer is conforming, we make
            // a second call to it requesting for N characters. Then we can return.
            //
            // If the underlying layer is non-conforming, things are tricky.
            // First, the character returned
            // by the first call is useful and we cannot discard it. We should let it sit at the
            // beginning of the input buffer. So when we make the second call requesting for (N-2)
            // charaters, we have to use a temporary buffer. The reason is: the input buffer is
            // specified as an IntPtr. We cannot change its offset like a pointer without using
            // unsafe context, which we want to avoid. So we need to copy the characters in the
            // temporary buffer to the input buffer when the call returns, which might be expensive.
            //
            // Second, a side effect of making 2 calls to the underlying layer
            // is the second call may trigger a FILTER_E_NO_MORE_TEXT exception if the first call
            // exhausts all texts in the stream. We need to catch this exception, otherwise the COM
            // will catch it and return an error HRESULT to the user, which sould not happen. So,
            // we need to add a try-catch block for the second call to the non-conforming underlying
            // layer, which is expensive.
            //
            // Given the overheads that can incur, we dropped this idea eventhough it provides a
            // cleaner string format returned to the user. If the filter interface requires
            // the underlying filter to provide a property field indicating its behavior, then
            // we can implement this idea much cheaper.

            // Make sure the returned buffer always contains a terminating zero.
            //    Note the conversion of uint to int involves no risk of an arithmetic overflow thanks
            // to the truncations performed above.
            //    Provided pBuffer points to a buffer of size the minimum of _maxTextBufferSizeInCharacters
            // and the initial value of bufCharacterCount, the following write occurs within range.
            Marshal.WriteInt16(pBuffer, (int)bufCharacterCount * _int16Size, 0);

            // Count the terminator in the size that is returned.
            bufCharacterCount++;
        }
Exemplo n.º 10
0
    private void ParseInvariant(TypeNode parentType, AttributeList attributes, TokenList modifierTokens, SourceContextList modifierContexts, SourceContext sctx, TokenSet followers){
      Debug.Assert(this.currentToken == Token.Invariant);
      bool savedParsingStatement = this.parsingStatement;
      if (this.currentToken != Token.EndOfFile) this.parsingStatement = true;

      for(int i = 0, n = modifierTokens.Length; i < n; i++){
        switch(modifierTokens[i]){
          case Token.Static: break;
          default:
           // Token.New, Token.Public, Token.Protected, Token.Internal, Token.Private, Token.Abstract,
           // Token.Sealed, Token.Readonly, Token.Volatile, Token.Virtual, Token.Override, Token.Extern,
           //Token.Unsafe
            this.HandleError(modifierContexts[i], Error.InvalidModifier, modifierContexts[i].SourceText);
            break;
        }
      }

      SourceContext sctxt = this.scanner.CurrentSourceContext;
      this.GetNextToken();
      Expression condition = this.ParseExpression(followers|Token.Semicolon);
      int endPos = this.scanner.endPos;
      this.SkipSemiColon(followers);

      if (!(parentType is Class || parentType is Struct)){
        this.HandleError(sctxt, Error.OnlyStructsAndClassesCanHaveInvariants);
        if (this.currentToken != Token.EndOfFile) this.parsingStatement = savedParsingStatement;
        return;
      }

      EnsureHasInvariantMethod(parentType);
      TypeContract contract = parentType.Contract;
      Identifier name = Identifier.For("invariant" + (InvariantCt++));
      Invariant inv = new Invariant(parentType, attributes, name);
      inv.SourceContext = sctxt;
      inv.Flags = this.GetMethodFlags(modifierTokens, modifierContexts, parentType, inv)|MethodFlags.HideBySig;

      if ((inv.Flags & MethodFlags.Static) != 0 && parentType is Interface){
        this.HandleError(sctx, Error.InvalidModifier, "static");
        inv.Flags &= ~MethodFlags.Static;
      }
      if ((inv.Flags & MethodFlags.Static) == 0)
        inv.CallingConvention = CallingConventionFlags.HasThis;
      inv.Documentation = this.LastDocComment;
      inv.SourceContext.EndPos = endPos;
      inv.Condition = condition;
      contract.Invariants.Add(inv);
      if (this.currentToken != Token.EndOfFile) this.parsingStatement = savedParsingStatement;
    }
Exemplo n.º 11
0
 public SampleStream(Invariant invariant)
 {
     _invariant = invariant;
 }
Exemplo n.º 12
0
 public override Invariant VisitInvariant(Invariant inv) {
   if (inv == null) return null;
   SpecSharpCompilerOptions options = this.currentOptions as SpecSharpCompilerOptions;
   if (options != null && options.CheckContractAdmissibility) {
     AdmissibilityChecker checker = new AdmissibilityChecker(this);
     this.TransferStateTo(checker);
     checker.CheckInvariantAdmissibility(inv);
   }
   return base.VisitInvariant(inv);
 }
Exemplo n.º 13
0
 public override Invariant VisitInvariant(Invariant @invariant){
   Scope savedScope = this.scope;
   Method savedMethod = this.currentMethod;
   this.currentMethod = this.currentType.Contract.InvariantMethod;
   this.scope = this.currentMethod.Scope;
   this.AddToAllScopes(this.scope);
   Invariant inv = base.VisitInvariant (@invariant);
   this.scope = savedScope;
   this.currentMethod = savedMethod;
   return inv;
 }
Exemplo n.º 14
0
 public override void VisitInvariant(Invariant invariant)
 {
     seenDup = false;
     seenConstructArray = false;
     base.VisitInvariant(invariant);
 }
Exemplo n.º 15
0
        internal static void GetAssemblyNameAndPart(Uri uri, out string partName, out string assemblyName, out string assemblyVersion, out string assemblyKey)
        {
            Invariant.Assert(uri != null && uri.IsAbsoluteUri == false, "This method accepts relative uri only.");

            string original = uri.ToString(); // only relative Uri here (enforced by Package)

            // Start and end points for the first segment in the Uri.
            int start = 0;
            int end;

            if (original[0] == '/')
            {
                start = 1;
            }

            partName = original.Substring(start);

            assemblyName    = string.Empty;
            assemblyVersion = string.Empty;
            assemblyKey     = string.Empty;

            end = original.IndexOf('/', start);

            string firstSegment  = String.Empty;
            bool   fHasComponent = false;

            if (end > 0)
            {
                // get the first section
                firstSegment = original.Substring(start, end - start);

                // The resource comes from dll
                if (firstSegment.EndsWith(COMPONENT, StringComparison.OrdinalIgnoreCase))
                {
                    partName      = original.Substring(end + 1);
                    fHasComponent = true;
                }
            }

            if (fHasComponent)
            {
                string[] assemblyInfo = firstSegment.Split(new char[] { COMPONENT_DELIMITER });

                int count = assemblyInfo.Length;

                if ((count > 4) || (count < 2))
                {
                    throw new UriFormatException(SR.Get(SRID.WrongFirstSegment));
                }

                //
                // if the uri contains escaping character,
                // Convert it back to normal unicode string
                // so that the string as assembly name can be
                // recognized by Assembly.Load later.
                //
                assemblyName = Uri.UnescapeDataString(assemblyInfo[0]);

                for (int i = 1; i < count - 1; i++)
                {
                    if (assemblyInfo[i].StartsWith(VERSION, StringComparison.OrdinalIgnoreCase))
                    {
                        if (string.IsNullOrEmpty(assemblyVersion))
                        {
                            assemblyVersion = assemblyInfo[i].Substring(1);  // Get rid of the leading "v"
                        }
                        else
                        {
                            throw new UriFormatException(SR.Get(SRID.WrongFirstSegment));
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(assemblyKey))
                        {
                            assemblyKey = assemblyInfo[i];
                        }
                        else
                        {
                            throw new UriFormatException(SR.Get(SRID.WrongFirstSegment));
                        }
                    }
                } // end of for loop
            }     // end of if fHasComponent
        }
Exemplo n.º 16
0
        /// <summary>
        /// Opens the specified file with the specified mode..
        /// This can return any of the STG_E_* error codes, along
        /// with S_OK, E_OUTOFMEMORY, and E_FAIL.
        /// </summary>
        /// <param name="pszFileName">
        /// A zero-terminated string containing the absolute path of the file to open.
        /// </param>
        /// <param name="dwMode">The mode in which to open pszFileName. </param>
        void IPersistFile.Load(string pszFileName, int dwMode)
        {
            FileMode   fileMode;
            FileAccess fileAccess;
            FileShare  fileSharing;

            // Check argument.
            if (pszFileName == null || pszFileName == String.Empty)
            {
                throw new ArgumentException(SR.Get(SRID.FileNameNullOrEmpty), "pszFileName");
            }

            // Convert mode information in flag.
            switch ((STGM_FLAGS)(dwMode & (int)STGM_FLAGS.MODE))
            {
            case STGM_FLAGS.CREATE:
                throw new ArgumentException(SR.Get(SRID.FilterLoadInvalidModeFlag), "dwMode");

            default:
                fileMode = FileMode.Open;
                break;
            }

            // Convert access flag.
            switch ((STGM_FLAGS)(dwMode & (int)STGM_FLAGS.ACCESS))
            {
            case STGM_FLAGS.READ:
            case STGM_FLAGS.READWRITE:
                fileAccess = FileAccess.Read;
                break;

            default:
                throw new ArgumentException(SR.Get(SRID.FilterLoadInvalidModeFlag), "dwMode");
            }

            // Sharing flags are ignored. Since managed filters do not have the equivalent
            // of a destructor to release locks on files as soon as they get disposed of from
            // unmanaged code, the option taken is not to lock at all while filtering.
            // (See call to FileToStream further down.)
            fileSharing = FileShare.ReadWrite;

            // Only one of _package and _encryptedPackage can be non-null at a time.
            Invariant.Assert(_package == null || _encryptedPackage == null);

            // If there has been a previous call to Load, reinitialize everything.
            // Note closing a closed stream does not cause any exception.
            ReleaseResources();

            _filter      = null;
            _xpsFileName = null;

            bool encrypted = EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(pszFileName);

            try
            {
                // opens to MemoryStream or just returns FileStream if file exceeds _maxMemoryStreamBuffer
                _packageStream = FileToStream(pszFileName, fileMode, fileAccess, fileSharing, _maxMemoryStreamBuffer);

                if (encrypted)
                {
                    // Open the encrypted package.
                    _encryptedPackage = EncryptedPackageEnvelope.Open(_packageStream);
                    _filter           = new EncryptedPackageFilter(_encryptedPackage);
                }
                else
                {
                    // Open the package.
                    _package = Package.Open(_packageStream);
                    _filter  = new PackageFilter(_package);
                }
            }
            catch (IOException ex)
            {
                throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_ACCESS);
            }
            catch (FileFormatException ex)
            {
                throw new COMException(ex.Message, (int)FilterErrorCode.FILTER_E_UNKNOWNFORMAT);
            }
            finally
            {
                // failure?
                if (_filter == null)
                {
                    // clean up
                    ReleaseResources();
                }
            }

            _xpsFileName = pszFileName;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Compute a shaped glyph run object from specified glyph-based info
        /// </summary>
        internal sealed override GlyphRun ComputeShapedGlyphRun(
            Point origin,
            char[]                   characterString,
            ushort[]                 clusterMap,
            ushort[]                 glyphIndices,
            IList <double> glyphAdvances,
            IList <Point> glyphOffsets,
            bool rightToLeft,
            bool sideways
            )
        {
            Invariant.Assert(_shapeTypeface != null);
            Invariant.Assert(glyphIndices != null);
            // Device fonts are only used through the LS non-glyphed code path. Only when a DigitCulture is set
            // will a potential device font be ignored and come through shaping.
            Invariant.Assert(_shapeTypeface.DeviceFont == null || _textItem.DigitCulture != null);

            bool[] caretStops = null;

            if (clusterMap != null &&
                (HasExtendedCharacter || NeedsCaretInfo)
                )
            {
                caretStops = new bool[clusterMap.Length + 1];

                // caret stops at cluster boundaries, the first and the last entries are always set
                caretStops[0] = true;
                caretStops[clusterMap.Length] = true;

                ushort lastGlyph = clusterMap[0];

                for (int i = 1; i < clusterMap.Length; i++)
                {
                    ushort glyph = clusterMap[i];

                    if (glyph != lastGlyph)
                    {
                        caretStops[i] = true;
                        lastGlyph     = glyph;
                    }
                }
            }

            return(GlyphRun.TryCreate(
                       _shapeTypeface.GlyphTypeface,
                       (rightToLeft ? 1 : 0),
                       sideways,
                       _emSize,
                       (float)_properties.PixelsPerDip,
                       glyphIndices,
                       origin,
                       glyphAdvances,
                       glyphOffsets,
                       characterString,
                       null,
                       clusterMap,
                       caretStops,
                       XmlLanguage.GetLanguage(CultureMapper.GetSpecificCulture(_properties.CultureInfo).IetfLanguageTag),
                       _textFormattingMode
                       ));
        }
 public override IDisposable?PrepareForHandleLost()
 {
     Invariant.Require(!this._preparedForHandleLost);
     this._preparedForHandleLost = true;
     return(new HandleLostScope(this));
 }
Exemplo n.º 19
0
        // ------------------------------------------------------------------
        //  Hit tests to the correct ContentElement within the line.
        //
        //      offset - offset within the line.
        //
        // Returns: ContentElement which has been hit.
        // ------------------------------------------------------------------
        internal override IInputElement InputHitTest(double offset)
        {
            TextContainer      tree;
            DependencyObject   element;
            CharacterHit       charHit;
            TextPointer        position;
            TextPointerContext type = TextPointerContext.None;

            element = null;

            // We can only support hittesting text elements in a TextContainer.
            // If the TextContainer is not a TextContainer, return null which higher up the stack
            // will be converted into a reference to the control itself.
            tree = _owner.TextContainer as TextContainer;

            // Adjusted offset for shift due to trailing spaces rendering
            double delta = CalculateXOffsetShift();

            if (tree != null)
            {
                if (_line.HasOverflowed && _owner.ParagraphProperties.TextTrimming != TextTrimming.None)
                {
                    // We should not shift offset in this case
                    Invariant.Assert(DoubleUtil.AreClose(delta, 0));
                    System.Windows.Media.TextFormatting.TextLine line = _line.Collapse(GetCollapsingProps(_wrappingWidth, _owner.ParagraphProperties));
                    Invariant.Assert(line.HasCollapsed, "Line has not been collapsed");

                    // Get TextPointer from specified distance.
                    charHit = line.GetCharacterHitFromDistance(offset);
                }
                else
                {
                    charHit = _line.GetCharacterHitFromDistance(offset - delta);
                }

                position = new TextPointer(_owner.ContentStart, CalcPositionOffset(charHit), LogicalDirection.Forward);

                if (position != null)
                {
                    if (charHit.TrailingLength == 0)
                    {
                        // Start of character. Look forward
                        type = position.GetPointerContext(LogicalDirection.Forward);
                    }
                    else
                    {
                        // End of character. Look backward
                        type = position.GetPointerContext(LogicalDirection.Backward);
                    }

                    // Get element only for Text & Start/End element, for all other positions
                    // return null (it means that the line owner has been hit).
                    if (type == TextPointerContext.Text || type == TextPointerContext.ElementEnd)
                    {
                        element = position.Parent as TextElement;
                    }
                    else if (type == TextPointerContext.ElementStart)
                    {
                        element = position.GetAdjacentElementFromOuterPosition(LogicalDirection.Forward);
                    }
                }
            }

            return(element as IInputElement);
        }
 public override void PerformAdditionalCleanupForHandleAbandonment()
 {
     Invariant.Require(this._preparedForHandleAbandonment);
     Thread.Sleep(TimeSpan.FromSeconds(.5));
 }
Exemplo n.º 21
0
        public RemoveWww(HttpContextBase httpContext)
        {
            Invariant.IsNotNull(httpContext, "httpContext");

            this.httpContext = httpContext;
        }
Exemplo n.º 22
0
        /// <summary>
        /// Returns the index of the roman marker that will have largest width, i.e. most letters
        /// </summary>
        /// <param name="startIndex">
        /// Start index of the list
        /// </param>
        /// <param name="highestIndex">
        /// Highest-numbered index in the list
        /// </param>
        private static int GetIndexForLargestRomanMarker(int startIndex, int highestIndex)
        {
            int largestIndex = 0;

            if (startIndex == 1)
            {
                // Do quick search by looking only at size increments
                int thousands = highestIndex / 1000;
                highestIndex = highestIndex % 1000;
                for (int i = 0; i < RomanNumericSizeIncrements.Length; i++)
                {
                    Invariant.Assert(highestIndex >= RomanNumericSizeIncrements[i]);
                    if (highestIndex == RomanNumericSizeIncrements[i])
                    {
                        // This is the largest index.
                        largestIndex = highestIndex;
                        break;
                    }
                    else
                    {
                        Invariant.Assert(highestIndex > RomanNumericSizeIncrements[i]);
                        if (i < RomanNumericSizeIncrements.Length - 1)
                        {
                            if (highestIndex >= RomanNumericSizeIncrements[i + 1])
                            {
                                // Size does not lie within this increment range. Keep searching
                                continue;
                            }
                        }

                        // Size is either larger than the largest increment value,
                        // or lies between two increment values in which case we
                        // take the lower one
                        largestIndex = RomanNumericSizeIncrements[i];
                        break;
                    }
                }
                if (thousands > 0)
                {
                    // M's will be added to largest index for extra thousands
                    largestIndex = thousands * 1000 + largestIndex;
                }
            }
            else
            {
                // Quick search will not work. Look at each index
                int largestIndexSize = 0;
                for (int i = startIndex; i <= highestIndex; i++)
                {
                    // Format as roman string. It does not matter if we use upper or lowercase formatting here since
                    // we are only counting number of letters in each string. This is not strictly correct -
                    // III might be smaller than XX in some fonts - but we cannot format text each time.
                    string romanString = ConvertNumberToRomanString(i, true);
                    if (romanString.Length > largestIndexSize)
                    {
                        largestIndex     = i;
                        largestIndexSize = romanString.Length;
                    }
                }
            }

            Invariant.Assert(largestIndex > 0);
            return(largestIndex);
        }
Exemplo n.º 23
0
        internal unsafe void GetCells(
            int cCells,
            IntPtr *rgnmCell,
            PTS.FSTABLEKCELLMERGE *rgkcellmerge)
        {
            Invariant.Assert(cCells == Row.FormatCellCount);

            // To protect against a buffer overflow, we must check that we aren't writing more
            // cells than were allocated.  So we check against the cell count we have -
            // Row.FormatCellCount.  But that's calculated elsewhere.  What if it's stale?
            // There aren't any direct values available to compare against at the start of
            // this function, so we need two separate asserts.  Bug 1149633.
            Invariant.Assert(cCells >= Row.Cells.Count); // Protect against buffer overflow


            int i = 0;

            //  first, submit all non vertically merged cells
            for (int j = 0; j < Row.Cells.Count; ++j)
            {
                TableCell cell = Row.Cells[j];
                if (cell.RowSpan == 1)
                {
                    rgnmCell[i]     = _cellParagraphs[j].Handle;
                    rgkcellmerge[i] = PTS.FSTABLEKCELLMERGE.fskcellmergeNo;
                    i++;
                }
            }

            // i now contains the exact number of non-rowspan cells on this row.  Use it to verify
            // total number of cells, before we possibly write off end of allocated array.
            Invariant.Assert(cCells == i + _spannedCells.Length); // Protect against buffer overflow

            //  second, submit all vertically merged cells
            if (_spannedCells.Length > 0)
            {
                bool lastRow = Row.Index == Row.RowGroup.Rows.Count - 1;

                for (int j = 0; j < _spannedCells.Length; ++j)
                {
                    Debug.Assert(_spannedCells[j] != null);

                    TableCell cell = _spannedCells[j].Cell;
                    rgnmCell[i] = _spannedCells[j].Handle;

                    if (cell.RowIndex == Row.Index)
                    {
                        rgkcellmerge[i] = lastRow
                            ? PTS.FSTABLEKCELLMERGE.fskcellmergeNo
                            : PTS.FSTABLEKCELLMERGE.fskcellmergeFirst;
                    }
                    else if (Row.Index - cell.RowIndex + 1 < cell.RowSpan)
                    {
                        rgkcellmerge[i] = lastRow
                            ? PTS.FSTABLEKCELLMERGE.fskcellmergeLast
                            : PTS.FSTABLEKCELLMERGE.fskcellmergeMiddle;
                    }
                    else
                    {
                        Debug.Assert(Row.Index - cell.RowIndex + 1 == cell.RowSpan);
                        rgkcellmerge[i] = PTS.FSTABLEKCELLMERGE.fskcellmergeLast;
                    }

                    i++;
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Returns FormattedText for the largets marker in a list
        /// </summary>
        /// <param name="list">
        /// List element for which formatted marker is to be calculated
        /// </param>
        private static FormattedText GetFormattedMarker(List list)
        {
            string        markerString = "";
            FormattedText formattedMarker;

            if (IsKnownSymbolMarkerStyle(list.MarkerStyle))
            {
                switch (list.MarkerStyle)
                {
                case TextMarkerStyle.Disc:
                    markerString = "\x9f";
                    break;

                case TextMarkerStyle.Circle:
                    markerString = "\xa1";
                    break;

                case TextMarkerStyle.Square:
                    markerString = "\x71";
                    break;

                case TextMarkerStyle.Box:
                    markerString = "\xa7";
                    break;
                }

                // Create new formatted text with typeface using a symbol font, e.g. Wingdings
                Typeface typeface = DynamicPropertyReader.GetModifiedTypeface(list, new FontFamily("Wingdings"));

                formattedMarker = new FormattedText(markerString, DynamicPropertyReader.GetCultureInfo(list), list.FlowDirection,
                                                    typeface, list.FontSize, list.Foreground);
            }
            else if (IsKnownIndexMarkerStyle(list.MarkerStyle))
            {
                // Assume at least one element will be added and format accordingly
                int startIndex = list.StartIndex;
                Invariant.Assert(startIndex > 0);
                int size = list.ListItems.Count;
                int highestIndex;
                if (int.MaxValue - size < startIndex)
                {
                    // Highest index will exceed max value of int. Clamp to int.MaxValue
                    highestIndex = int.MaxValue;
                }
                else
                {
                    highestIndex = (size == 0) ? startIndex : startIndex + size - 1;
                }
                switch (list.MarkerStyle)
                {
                case TextMarkerStyle.Decimal:
                    markerString = ConvertNumberToString(highestIndex, false, DecimalNumerics);
                    break;

                case TextMarkerStyle.LowerLatin:
                    markerString = ConvertNumberToString(highestIndex, true, LowerLatinNumerics);
                    break;

                case TextMarkerStyle.UpperLatin:
                    markerString = ConvertNumberToString(highestIndex, true, UpperLatinNumerics);
                    break;

                case TextMarkerStyle.LowerRoman:
                    markerString = GetStringForLargestRomanMarker(startIndex, highestIndex, false);
                    break;

                case TextMarkerStyle.UpperRoman:
                    markerString = GetStringForLargestRomanMarker(startIndex, highestIndex, true);
                    break;
                }

                // Create new formatted text using List defaulls
                formattedMarker = new FormattedText(markerString, DynamicPropertyReader.GetCultureInfo(list), list.FlowDirection,
                                                    DynamicPropertyReader.GetTypeface(list), list.FontSize, list.Foreground);
            }
            else
            {
                // Assume a disc
                markerString = "\x9f";
                // Create new formatted text with typeface using a symbol font, e.g. Wingdings
                Typeface typeface = DynamicPropertyReader.GetModifiedTypeface(list, new FontFamily("Wingdings"));

                formattedMarker = new FormattedText(markerString, DynamicPropertyReader.GetCultureInfo(list), list.FlowDirection,
                                                    typeface, list.FontSize, list.Foreground);
            }

            return(formattedMarker);
        }
Exemplo n.º 25
0
 public EventingVisitor(Action<Invariant> visitInvariant) { VisitedInvariant += visitInvariant; } public event Action<Invariant> VisitedInvariant; public override Invariant VisitInvariant(Invariant invariant) { if (VisitedInvariant != null) VisitedInvariant(invariant); return base.VisitInvariant(invariant); }
Exemplo n.º 26
0
            /// <summary>
            /// If the logical end precedes the physical end, delete invalidated pieces
            /// and rename the logical end to a name containing ".last".
            /// </summary>
            private void UpdatePhysicalEndIfNecessary()
            {
                if (!_logicalEndPrecedesPhysicalEnd)
                {
                    return;
                }

                // Delete invalidated pieces.
                int pieceNumber = _lastPieceIndex + 1;

                while (pieceNumber < _sortedPieceInfoList.Count)
                {
                    _zipArchive.DeleteFile(_sortedPieceInfoList[pieceNumber].ZipFileInfo.Name);
                    pieceNumber++;
                }

                _sortedPieceInfoList.RemoveRange(_lastPieceIndex + 1, _sortedPieceInfoList.Count - (_lastPieceIndex + 1));

                // Since there is no rename in Zip I/O, getting the last piece to have .last
                // in its name necessarily involves creating a new piece. The simplest and most
                // effective solution consists in adding an empty terminal piece.

                // Number of the new physical last piece.
                int lastPiece = _lastPieceIndex + 1;

                // Record the compression parameters of the first piece to apply them to the new piece.
                // (Though this part will be created as empty, it may grow later.)
                ZipFileInfo           firstPieceInfo    = _sortedPieceInfoList[0].ZipFileInfo;
                CompressionMethodEnum compressionMethod = firstPieceInfo.CompressionMethod;
                DeflateOptionEnum     deflateOption     = firstPieceInfo.DeflateOption;

                // We have to special-case SetLength(0), because in that case, there is no nonempty
                // piece at all; and only the last piece is allowed to be empty.
                if (_lastPieceIndex == 0 && _pieceStreamInfoList[0].Stream.Length == 0)
                {
                    _zipArchive.DeleteFile(firstPieceInfo.Name);

                    // The list of piece descriptors now becomes totally empty.
                    // This temporarily violates an invariant that should obtain again
                    // on exiting this function.
                    _indexOfLastPieceStreamInfoAccessed = -1;
                    //Remove all the items in the list
                    _pieceStreamInfoList.Clear();
                    lastPiece = 0; // Create "[0].last.piece"
                }

                string newLastPieceFileName = PieceNameHelper.CreatePieceName(
                    _sortedPieceInfoList[0].PrefixName,
                    lastPiece,
                    true /* last piece */);

                ZipFileInfo newLastPieceInfo = _zipArchive.AddFile(newLastPieceFileName,
                                                                   compressionMethod, deflateOption);

                _lastPieceIndex = lastPiece;

                //We need to update the _sortedPieceInfoList with this new last piece information
                _sortedPieceInfoList.Add(
                    new PieceInfo(
                        newLastPieceInfo,
                        _sortedPieceInfoList[0].PartUri,
                        _sortedPieceInfoList[0].PrefixName,
                        _lastPieceIndex,
                        true /* last piece */));

                // If we have been creating [0].last.piece, create a stream descriptor for it.
                // (In other cases, create on demand, as usual.)
                if (lastPiece == 0)
                {
                    Stream pieceStream = newLastPieceInfo.GetStream(_fileMode, _fileAccess);
                    _indexOfLastPieceStreamInfoAccessed = 0;

                    //The list should be empty at this point
                    Invariant.Assert(_pieceStreamInfoList.Count == 0);
                    _pieceStreamInfoList.Add(new PieceStreamInfo(pieceStream, 0 /*startOffset*/));
                }

                // Mark update complete.
                _logicalEndPrecedesPhysicalEnd = false;
            }
Exemplo n.º 27
0
        /// <summary>
        /// Acquire a free TextFormatter context for complex line operation
        /// </summary>
        /// <param name="owner">object that becomes the owner of LS context once acquired</param>
        /// <param name="ploc">matching PLOC</param>
        /// <returns>Active LS context</returns>
        /// <SecurityNotes>
        /// Critical - this sets the owner of the context
        /// Safe     - this doesn't expose critical info
        /// </SecurityNotes>
        internal TextFormatterContext AcquireContext(
            object owner,
            IntPtr ploc
            )
        {
            Invariant.Assert(owner != null);

            TextFormatterContext context = null;

            int c;
            int contextCount = _contextList.Count;

            for (c = 0; c < contextCount; c++)
            {
                context = (TextFormatterContext)_contextList[c];

                if (ploc == IntPtr.Zero)
                {
                    if (context.Owner == null)
                    {
                        break;
                    }
                }
                else if (ploc == context.Ploc.Value)
                {
                    // LS requires that we use the exact same context for line
                    // destruction or hittesting (part of the reason is that LS
                    // actually caches some run info in the context). So here
                    // we use the actual PLSC as the context signature so we
                    // locate the one we want.

                    Debug.Assert(context.Owner == null);
                    break;
                }
            }

            if (c == contextCount)
            {
                if (contextCount == 0 || !_multipleContextProhibited)
                {
                    //  no free one exists, create a new one
                    context = new TextFormatterContext();
                    _contextList.Add(context);
                }
                else
                {
                    // This instance of TextFormatter only allows a single context, reentering the
                    // same TextFormatter in this case is not allowed.
                    //
                    // This requirement is currently enforced only during optimal break computation.
                    // Client implementing nesting of optimal break content inside another must create
                    // a separate TextFormatter instance for each content in different nesting level.
                    throw new InvalidOperationException(SR.Get(SRID.TextFormatterReentranceProhibited));
                }
            }

            Debug.Assert(context != null);

            context.Owner = owner;
            return(context);
        }
Exemplo n.º 28
0
        internal void Update(IEnumerable enumerable)
        {
            IList <object> list = Items;
            int            index1 = -1, index2 = -1;
            int            n      = list.Count;
            Change         change = Change.None;
            int            index  = 0;
            object         target = Unset;

            // determine what kind of change occurred

            // first match each item in the enumerator against the cached list
            foreach (object o in enumerable)
            {
                // skip over matching items
                if (index < n && Object.Equals(o, list[index]))
                {
                    ++index;
                    continue;
                }

                // mismatch - what happens next depends on previous history
                switch (change)
                {
                case Change.None:       // this is the first mismatch
                    if (index + 1 < n && Object.Equals(o, list[index + 1]))
                    {
                        // enumerator matches the next list item,
                        // provisionally mark this as Remove (might be Move)
                        change = Change.Remove;
                        index1 = index;
                        target = list[index];
                        index  = index + 2;
                    }
                    else
                    {
                        // enumerator doesn't match next list item,
                        // provisionally mark this as Add (might be Move or Replace)
                        change = Change.Add;
                        index1 = index;
                        target = o;
                    }
                    break;

                case Change.Add:        // previous mismatch was provisionally Add
                    if (index + 1 < n && Object.Equals(o, list[index + 1]))
                    {
                        // enumerator matches next list item;  check current
                        // list item

                        if (Object.Equals(target, list[index]))
                        {
                            // current matches "added" element from enumerator,
                            // change this to Move
                            change = Change.Move;
                            index2 = index1;
                            index1 = index;
                        }
                        else if (index < n && index == index1)
                        {
                            // current item was replaced
                            change = Change.Replace;
                        }
                        else
                        {
                            // two mismatches, not part of a known pattern
                            change = Change.Reset;
                        }

                        index = index + 2;
                    }
                    else
                    {
                        // enumerator doesn't match next list item;  no pattern
                        change = Change.Reset;
                    }
                    break;

                case Change.Remove:     // previous mismatch was provisionally Remove
                    if (Object.Equals(o, target))
                    {
                        // enumerator matches "removed" item from list;
                        // change this to Move
                        change = Change.Move;
                        index2 = index - 1;
                    }
                    else
                    {
                        // enumerator does not match "removed" item;  no pattern
                        change = Change.Reset;
                    }
                    break;

                default:        // any other previous mismatch implies no pattern
                    change = Change.Reset;
                    break;
                }

                // once we eliminate known patterns, no reason to keep looking
                if (change == Change.Reset)
                {
                    break;
                }
            }

            // Next, account for any leftover items in the list (if any)
            if (index == n - 1)
            {
                // exactly one leftover item - possibly part of a simple pattern
                switch (change)
                {
                case Change.None:           // no previous change - last item was removed
                    change = Change.Remove;
                    index1 = index;
                    break;

                case Change.Add:            // provisional Add, might be Move or Replace
                    if (Object.Equals(target, list[index]))
                    {
                        // a single extra item matches the "added" item;  change this to Move
                        change = Change.Move;
                        index2 = index1;
                        index1 = index;
                    }
                    else if (index1 == n - 1)
                    {
                        // a single extra item mismatches the last item;  change this to Replace
                        change = Change.Replace;
                    }
                    else
                    {
                        // anything else means no pattern
                        change = Change.Reset;
                    }
                    break;

                default:                    // anything else means no pattern
                    change = Change.Reset;
                    break;
                }
            }
            else if (index != n)
            {
                // two or more leftover items - no pattern
                change = Change.Reset;
            }

            // Finally, make the appropriate change to the list
            switch (change)
            {
            case Change.None:
                break;

            case Change.Add:
                Invariant.Assert(target != Unset);
                Insert(index1, target);
                break;

            case Change.Remove:
                RemoveAt(index1);
                break;

            case Change.Move:
                Move(index1, index2);
                break;

            case Change.Replace:
                Invariant.Assert(target != Unset);
                this[index1] = target;
                break;

            case Change.Reset:
                Reload(enumerable);
                break;
            }
        }
Exemplo n.º 29
0
 public static StreamEvent <TPayload>[] ToStreamEventArray <TPayload>(this IStreamable <Empty, TPayload> input)
 {
     Invariant.IsNotNull(input, "input");
     return(input.ToStreamEventObservable().ToEnumerable().ToArray());
 }
Exemplo n.º 30
0
        //-------------------------------------------------------------------
        //
        // Private Methods
        //
        //-------------------------------------------------------------------

        #region Private Methods

        /// <summary>
        /// Changed handler for the Text property.
        /// </summary>
        /// <param name="d">The source of the event.</param>
        /// <param name="e">A PropertyChangedEventArgs that contains the event data.</param>
        /// <remarks>
        /// We can't assume the value is a string here -- it may be a DeferredRunTextReference.
        /// </remarks>
        private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Run run = (Run)d;

            // Return if this update was caused by a TextContainer change or a reentrant change.
            if (run._changeEventNestingCount > 0)
            {
                return;
            }

            Invariant.Assert(!e.NewEntry.IsDeferredReference);

            // CoerceText will have already converted null -> String.Empty, but our default
            // CoerceValueCallback could be overridden by a derived class.  So check again here.
            string newText = (string)e.NewValue;

            if (newText == null)
            {
                newText = String.Empty;
            }

            // Run.TextProperty has changed. Update the backing store.
            run._changeEventNestingCount++;
            try
            {
                TextContainer textContainer = run.TextContainer;
                textContainer.BeginChange();

                try
                {
                    TextPointer contentStart = run.ContentStart;
                    if (!run.IsEmpty)
                    {
                        textContainer.DeleteContentInternal(contentStart, run.ContentEnd);
                    }
                    contentStart.InsertTextInRun(newText);
                }
                finally
                {
                    textContainer.EndChange();
                }
            }
            finally
            {
                run._changeEventNestingCount--;
            }

            // We need to clear undo stack if we are in a RichTextBox and the value comes from
            // data binding or some other expression.
            FlowDocument document = run.TextContainer.Parent as FlowDocument;

            if (document != null)
            {
                RichTextBox rtb = document.Parent as RichTextBox;
                if (rtb != null && run.HasExpression(run.LookupEntry(Run.TextProperty.GlobalIndex), Run.TextProperty))
                {
                    UndoManager undoManager = rtb.TextEditor._GetUndoManager();
                    if (undoManager != null && undoManager.IsEnabled)
                    {
                        undoManager.Clear();
                    }
                }
            }
        }
Exemplo n.º 31
0
        internal static NativeMethods.IconHandle CreateIconCursor(
            byte[] colorArray,
            int width,
            int height,
            int xHotspot,
            int yHotspot,
            bool isIcon)
        {
            //   1. We are going to generate a WIN32 color bitmap which represents the color cursor.
            //   2. Then we need to create a monochrome bitmap which is used as the cursor mask.
            //   3. At last we create a WIN32 HICON from the above two bitmaps
            NativeMethods.BitmapHandle colorBitmap = null;
            NativeMethods.BitmapHandle maskBitmap  = null;

            try
            {
                // 1) Create the color bitmap using colorArray
                // Fill in the header information
                NativeMethods.BITMAPINFO bi = new NativeMethods.BITMAPINFO(
                    width,                                      // width
                    -height,                                    // A negative value indicates the bitmap is top-down DIB
                    32                                          // biBitCount
                    );
                bi.bmiHeader_biCompression = NativeMethods.BI_RGB;

                IntPtr bits = IntPtr.Zero;
                colorBitmap = MS.Win32.UnsafeNativeMethods.CreateDIBSection(
                    new HandleRef(null, IntPtr.Zero),                // A device context. Pass null in if no DIB_PAL_COLORS is used.
                    ref bi,                                          // A BITMAPINFO structure which specifies the dimensions and colors.
                    NativeMethods.DIB_RGB_COLORS,                    // Specifies the type of data contained in the bmiColors array member of the BITMAPINFO structure
                    ref bits,                                        // An out Pointer to a variable that receives a pointer to the location of the DIB bit values
                    null,                                            // Handle to a file-mapping object that the function will use to create the DIB. This parameter can be null.
                    0                                                // dwOffset. This value is ignored if hSection is NULL
                    );

                if (colorBitmap.IsInvalid || bits == IntPtr.Zero)
                {
                    // Note we will release the GDI resources in the finally block.
                    return(NativeMethods.IconHandle.GetInvalidIcon());
                }

                // Copy the color bits to the win32 bitmap
                Marshal.Copy(colorArray, 0, bits, colorArray.Length);


                // 2) Now create the mask bitmap which is monochrome
                byte[] maskArray = GenerateMaskArray(width, height, colorArray);
                Invariant.Assert(maskArray != null);

                maskBitmap = UnsafeNativeMethods.CreateBitmap(width, height, 1, 1, maskArray);
                if (maskBitmap.IsInvalid)
                {
                    // Note we will release the GDI resources in the finally block.
                    return(NativeMethods.IconHandle.GetInvalidIcon());
                }

                // Now create HICON from two bitmaps.
                NativeMethods.ICONINFO iconInfo = new NativeMethods.ICONINFO();
                iconInfo.fIcon    = isIcon;         // fIcon == ture means creating an Icon, otherwise Cursor
                iconInfo.xHotspot = xHotspot;
                iconInfo.yHotspot = yHotspot;
                iconInfo.hbmMask  = maskBitmap;
                iconInfo.hbmColor = colorBitmap;

                return(UnsafeNativeMethods.CreateIconIndirect(iconInfo));
            }
            finally
            {
                if (colorBitmap != null)
                {
                    colorBitmap.Dispose();
                    colorBitmap = null;
                }

                if (maskBitmap != null)
                {
                    maskBitmap.Dispose();
                    maskBitmap = null;
                }
            }
        }
 // Token: 0x06006275 RID: 25205 RVA: 0x001B9E24 File Offset: 0x001B8024
 private void ReadAttributes(XmlReader reader)
 {
     Invariant.Assert(reader != null, "No reader passed in.");
     while (reader.MoveToNextAttribute())
     {
         string value = reader.Value;
         if (!string.IsNullOrEmpty(value))
         {
             string localName = reader.LocalName;
             if (!(localName == "Id"))
             {
                 if (!(localName == "CreationTime"))
                 {
                     if (!(localName == "LastModificationTime"))
                     {
                         if (!(localName == "Type"))
                         {
                             if (!Annotation.IsNamespaceDeclaration(reader))
                             {
                                 throw new XmlException(SR.Get("UnexpectedAttribute", new object[]
                                 {
                                     reader.LocalName,
                                     "Annotation"
                                 }));
                             }
                         }
                         else
                         {
                             string[] array = value.Split(Annotation._Colon);
                             if (array.Length == 1)
                             {
                                 array[0] = array[0].Trim();
                                 if (string.IsNullOrEmpty(array[0]))
                                 {
                                     throw new FormatException(SR.Get("InvalidAttributeValue", new object[]
                                     {
                                         "Type"
                                     }));
                                 }
                                 this._typeName = new XmlQualifiedName(array[0]);
                             }
                             else
                             {
                                 if (array.Length != 2)
                                 {
                                     throw new FormatException(SR.Get("InvalidAttributeValue", new object[]
                                     {
                                         "Type"
                                     }));
                                 }
                                 array[0] = array[0].Trim();
                                 array[1] = array[1].Trim();
                                 if (string.IsNullOrEmpty(array[0]) || string.IsNullOrEmpty(array[1]))
                                 {
                                     throw new FormatException(SR.Get("InvalidAttributeValue", new object[]
                                     {
                                         "Type"
                                     }));
                                 }
                                 this._typeName = new XmlQualifiedName(array[1], reader.LookupNamespace(array[0]));
                             }
                         }
                     }
                     else
                     {
                         this._modified = XmlConvert.ToDateTime(value);
                     }
                 }
                 else
                 {
                     this._created = XmlConvert.ToDateTime(value);
                 }
             }
             else
             {
                 this._id = XmlConvert.ToGuid(value);
             }
         }
     }
     if (this._id.Equals(Guid.Empty))
     {
         throw new XmlException(SR.Get("RequiredAttributeMissing", new object[]
         {
             "Id",
             "Annotation"
         }));
     }
     if (this._created.Equals(DateTime.MinValue))
     {
         throw new XmlException(SR.Get("RequiredAttributeMissing", new object[]
         {
             "CreationTime",
             "Annotation"
         }));
     }
     if (this._modified.Equals(DateTime.MinValue))
     {
         throw new XmlException(SR.Get("RequiredAttributeMissing", new object[]
         {
             "LastModificationTime",
             "Annotation"
         }));
     }
     if (this._typeName == null)
     {
         throw new XmlException(SR.Get("RequiredAttributeMissing", new object[]
         {
             "Type",
             "Annotation"
         }));
     }
     reader.MoveToContent();
 }
Exemplo n.º 33
0
        private void WriteAsciiChar(int ptr, int charOffset, char ch)
        {
            Invariant.Assert(IsAscii(ch));

            _byteData[ptr + charOffset] = (byte)(ch & 0xFF);
        }
        // Token: 0x06007862 RID: 30818 RVA: 0x00224C48 File Offset: 0x00222E48
        private void UpdateContent(StickyNoteControl snc, bool updateAnnotation, XmlToken token)
        {
            Invariant.Assert(snc != null, "Sticky Note Control is null.");
            Invariant.Assert((token & (XmlToken.Text | XmlToken.Ink)) > (XmlToken)0, "No token specified.");
            StickyNoteContentControl content = snc.Content;

            if (content == null)
            {
                return;
            }
            if ((token == XmlToken.Ink && content.Type != StickyNoteType.Ink) || (token == XmlToken.Text && content.Type != StickyNoteType.Text))
            {
                return;
            }
            XmlElement xmlElement = null;

            if (updateAnnotation)
            {
                AnnotationResource annotationResource = null;
                bool flag  = false;
                bool flag2 = false;
                if (!content.IsEmpty)
                {
                    SNCAnnotation.GetCargoAndRoot(this, token, out annotationResource, out xmlElement, out flag2, out flag);
                    content.Save(xmlElement);
                }
                else
                {
                    string cargoName = SNCAnnotation.GetCargoName(token);
                    annotationResource = this.FindCargo(cargoName);
                    if (annotationResource != null)
                    {
                        this._annotation.Cargos.Remove(annotationResource);
                        this._cachedXmlElements.Remove(token);
                    }
                }
                if (flag)
                {
                    Invariant.Assert(xmlElement != null, "XmlElement should have been created.");
                    Invariant.Assert(annotationResource != null, "Cargo should have been retrieved.");
                    annotationResource.Contents.Add(xmlElement);
                }
                if (flag2)
                {
                    Invariant.Assert(annotationResource != null, "Cargo should have been created.");
                    this._annotation.Cargos.Add(annotationResource);
                    return;
                }
            }
            else
            {
                XmlElement xmlElement2 = (XmlElement)this.FindData(token);
                if (xmlElement2 != null)
                {
                    content.Load(xmlElement2);
                    return;
                }
                if (!content.IsEmpty)
                {
                    content.Clear();
                }
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// Get advance widths of unshaped characters
        /// </summary>
        internal sealed override unsafe void GetAdvanceWidthsUnshaped(
            char *characterString,
            int characterLength,
            double scalingFactor,
            int *advanceWidthsUnshaped
            )
        {
            if (!IsShapingRequired)
            {
                if ((_shapeTypeface != null) &&
                    (_shapeTypeface.DeviceFont != null))
                {
                    // Use device font to compute advance widths
                    _shapeTypeface.DeviceFont.GetAdvanceWidths(
                        characterString,
                        characterLength,
                        _emSize * scalingFactor,
                        advanceWidthsUnshaped
                        );
                }
                else
                {
                    bool          nullFont;
                    GlyphTypeface glyphTypeface = GetGlyphTypeface(out nullFont);
                    Invariant.Assert(glyphTypeface != null);

                    glyphTypeface.GetAdvanceWidthsUnshaped(
                        characterString,
                        characterLength,
                        _emSize,
                        (float)_properties.PixelsPerDip,
                        scalingFactor,
                        advanceWidthsUnshaped,
                        nullFont,
                        _textFormattingMode,
                        _isSideways
                        );
                }
            }
            else
            {
                GlyphTypeface glyphTypeface = _shapeTypeface.GlyphTypeface;

                Invariant.Assert(glyphTypeface != null);
                Invariant.Assert(characterLength > 0);

                CharacterBufferRange newBuffer = new CharacterBufferRange(characterString, characterLength);
                MS.Internal.Text.TextInterface.GlyphMetrics[] glyphMetrics = BufferCache.GetGlyphMetrics(characterLength);

                glyphTypeface.GetGlyphMetricsOptimized(newBuffer,
                                                       _emSize,
                                                       (float)_properties.PixelsPerDip,
                                                       _textFormattingMode,
                                                       _isSideways,
                                                       glyphMetrics
                                                       );

                if (_textFormattingMode == TextFormattingMode.Display &&
                    TextFormatterContext.IsSpecialCharacter(*characterString))
                {
                    // If the run starts with a special character (in
                    // the LineServices sense), we apply display-mode rounding now,
                    // as we won't get another chance.   This assumes that the characters
                    // in a run are either all special or all non-special;  that assumption
                    // is valid in the current LS implementation.
                    double designToEm   = _emSize / glyphTypeface.DesignEmHeight;
                    double pixelsPerDip = _properties.PixelsPerDip;

                    for (int i = 0; i < characterLength; i++)
                    {
                        advanceWidthsUnshaped[i] = (int)Math.Round(TextFormatterImp.RoundDipForDisplayMode(glyphMetrics[i].AdvanceWidth * designToEm, pixelsPerDip) * scalingFactor);
                    }
                }
                else
                {
                    // For the normal case, rounding is applied later on when LS
                    // invokes the callback GetGlyphPositions, so that adjustments
                    // due to justification and shaping are taken into account.
                    double designToEm = _emSize * scalingFactor / glyphTypeface.DesignEmHeight;

                    for (int i = 0; i < characterLength; i++)
                    {
                        advanceWidthsUnshaped[i] = (int)Math.Round(glyphMetrics[i].AdvanceWidth * designToEm);
                    }
                }


                BufferCache.ReleaseGlyphMetrics(glyphMetrics);
            }
        }
 // Token: 0x06007855 RID: 30805 RVA: 0x002244C0 File Offset: 0x002226C0
 public static void UpdateStickyNoteControl(XmlToken token, StickyNoteControl snc, SNCAnnotation sncAnnotation)
 {
     Invariant.Assert((token & (XmlToken.Left | XmlToken.Top | XmlToken.XOffset | XmlToken.YOffset | XmlToken.Width | XmlToken.Height | XmlToken.IsExpanded | XmlToken.Author | XmlToken.Text | XmlToken.Ink | XmlToken.ZOrder)) > (XmlToken)0, "No token specified.");
     Invariant.Assert(snc != null, "Sticky Note Control is null.");
     Invariant.Assert(sncAnnotation != null, "Annotation is null.");
     if ((token & XmlToken.Ink) != (XmlToken)0 && sncAnnotation.HasInkData)
     {
         sncAnnotation.UpdateContent(snc, false, XmlToken.Ink);
     }
     if ((token & XmlToken.Text) != (XmlToken)0 && sncAnnotation.HasTextData)
     {
         sncAnnotation.UpdateContent(snc, false, XmlToken.Text);
     }
     if ((token & XmlToken.Author) != (XmlToken)0)
     {
         int    count         = sncAnnotation._annotation.Authors.Count;
         string listSeparator = snc.Language.GetSpecificCulture().TextInfo.ListSeparator;
         string text          = string.Empty;
         for (int i = 0; i < count; i++)
         {
             if (i != 0)
             {
                 text = text + listSeparator + sncAnnotation._annotation.Authors[i];
             }
             else
             {
                 text += sncAnnotation._annotation.Authors[i];
             }
         }
         snc.SetValue(StickyNoteControl.AuthorPropertyKey, text);
     }
     if ((token & XmlToken.Height) != (XmlToken)0)
     {
         XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.Height);
         if (xmlAttribute != null)
         {
             double num = Convert.ToDouble(xmlAttribute.Value, CultureInfo.InvariantCulture);
             snc.SetValue(FrameworkElement.HeightProperty, num);
         }
         else
         {
             snc.ClearValue(FrameworkElement.HeightProperty);
         }
     }
     if ((token & XmlToken.Width) != (XmlToken)0)
     {
         XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.Width);
         if (xmlAttribute != null)
         {
             double num2 = Convert.ToDouble(xmlAttribute.Value, CultureInfo.InvariantCulture);
             snc.SetValue(FrameworkElement.WidthProperty, num2);
         }
         else
         {
             snc.ClearValue(FrameworkElement.WidthProperty);
         }
     }
     if ((token & XmlToken.IsExpanded) != (XmlToken)0)
     {
         XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.IsExpanded);
         if (xmlAttribute != null)
         {
             bool isExpanded = Convert.ToBoolean(xmlAttribute.Value, CultureInfo.InvariantCulture);
             snc.IsExpanded = isExpanded;
         }
         else
         {
             snc.ClearValue(StickyNoteControl.IsExpandedProperty);
         }
     }
     if ((token & XmlToken.ZOrder) != (XmlToken)0)
     {
         XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.ZOrder);
         if (xmlAttribute != null)
         {
             ((IAnnotationComponent)snc).ZOrder = Convert.ToInt32(xmlAttribute.Value, CultureInfo.InvariantCulture);
         }
     }
     if ((token & (XmlToken.Left | XmlToken.Top | XmlToken.XOffset | XmlToken.YOffset)) != (XmlToken)0)
     {
         TranslateTransform translateTransform = new TranslateTransform();
         if ((token & XmlToken.Left) != (XmlToken)0)
         {
             XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.Left);
             if (xmlAttribute != null)
             {
                 double num3 = Convert.ToDouble(xmlAttribute.Value, CultureInfo.InvariantCulture);
                 if (snc.FlipBothOrigins)
                 {
                     num3 = -(num3 + snc.Width);
                 }
                 translateTransform.X = num3;
             }
         }
         if ((token & XmlToken.Top) != (XmlToken)0)
         {
             XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.Top);
             if (xmlAttribute != null)
             {
                 double y = Convert.ToDouble(xmlAttribute.Value, CultureInfo.InvariantCulture);
                 translateTransform.Y = y;
             }
         }
         if ((token & XmlToken.XOffset) != (XmlToken)0)
         {
             XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.XOffset);
             if (xmlAttribute != null)
             {
                 snc.XOffset = Convert.ToDouble(xmlAttribute.Value, CultureInfo.InvariantCulture);
             }
         }
         if ((token & XmlToken.YOffset) != (XmlToken)0)
         {
             XmlAttribute xmlAttribute = (XmlAttribute)sncAnnotation.FindData(XmlToken.YOffset);
             if (xmlAttribute != null)
             {
                 snc.YOffset = Convert.ToDouble(xmlAttribute.Value, CultureInfo.InvariantCulture);
             }
         }
         snc.PositionTransform = translateTransform;
     }
 }
Exemplo n.º 37
0
        // ------------------------------------------------------------------
        // Arrange content of formatted line.
        //
        //      vc - Visual collection of the parent.
        //      lineOffset - Offset of the line.
        // ------------------------------------------------------------------
        internal override void Arrange(VisualCollection vc, Vector lineOffset)
        {
            // Arrange inline objects
            int runDcp = _dcp;
            IList <TextSpan <TextRun> > runs = _line.GetTextRunSpans();

            Debug.Assert(runs != null, "Cannot retrieve runs collection.");

            // Calculate offset shift due to trailing spaces
            double adjustedXOffset = lineOffset.X + CalculateXOffsetShift();

            foreach (TextSpan <TextRun> textSpan in runs)
            {
                TextRun run = textSpan.Value;
                if (run is InlineObject)
                {
                    InlineObject inlineObject = run as InlineObject;

                    // Disconnect visual from its old parent, if necessary.
                    Visual currentParent = VisualTreeHelper.GetParent(inlineObject.Element) as Visual;
                    if (currentParent != null)
                    {
                        ContainerVisual parent = currentParent as ContainerVisual;
                        Invariant.Assert(parent != null, "parent should always derives from ContainerVisual");
                        parent.Children.Remove(inlineObject.Element);
                    }

                    // Get position of inline object withing the text line.
                    FlowDirection flowDirection;
                    Rect          rect = GetBoundsFromPosition(runDcp, inlineObject.Length, out flowDirection);
                    Debug.Assert(DoubleUtil.GreaterThanOrClose(rect.Width, 0), "Negative inline object's width.");

                    ContainerVisual proxyVisual = new ContainerVisual();
                    if (inlineObject.Element is FrameworkElement)
                    {
                        FlowDirection parentFlowDirection = _owner.FlowDirection;
                        // Check parent's FlowDirection to determine if mirroring is needed

                        DependencyObject parent = ((FrameworkElement)inlineObject.Element).Parent;
                        if (parent != null)
                        {
                            parentFlowDirection = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty);
                        }

                        PtsHelper.UpdateMirroringTransform(_owner.FlowDirection, parentFlowDirection, proxyVisual, rect.Width);
                    }
                    vc.Add(proxyVisual);

                    if (_owner.UseLayoutRounding)
                    {
                        // If using layout rounding, check whether rounding needs to compensate for high DPI
                        proxyVisual.Offset = new Vector(UIElement.RoundLayoutValue(lineOffset.X + rect.Left, FrameworkElement.DpiScaleX),
                                                        UIElement.RoundLayoutValue(lineOffset.Y + rect.Top, FrameworkElement.DpiScaleY));
                    }
                    else
                    {
                        proxyVisual.Offset = new Vector(lineOffset.X + rect.Left, lineOffset.Y + rect.Top);
                    }
                    proxyVisual.Children.Add(inlineObject.Element);

                    // Combine text line offset (relative to the Text control) with inline object
                    // offset (relative to the line) and set transorm on the visual. Trailing spaces
                    // shift is not added here because it is returned by GetBoundsFromPosition
                    inlineObject.Element.Arrange(new Rect(inlineObject.Element.DesiredSize));
                }

                // Do not use TextRun.Length, because it gives total length of the run.
                // So, if the run is broken between lines, it gives incorrect value.
                // Use length of the TextSpan instead, which gives the correct length here.
                runDcp += textSpan.Length;
            }
        }
Exemplo n.º 38
0
 /// <summary>
 /// Responds to content invalidation.
 /// </summary>
 private void HandleContentInvalidated(object sender, EventArgs e)
 {
     Invariant.Assert(sender == _formatter);
     InvalidateMeasure();
     InvalidateVisual(); //ensure re-rendering
 }
Exemplo n.º 39
0
 public virtual Invariant VisitInvariant(Invariant invariant1, Invariant invariant2){
   if (invariant1 == null) return null;
   if (invariant2 == null){
     invariant1.Condition = this.VisitExpression(invariant1.Condition, null);
   }else{
     invariant1.Condition = this.VisitExpression(invariant1.Condition, invariant2.Condition);
   }
   return invariant1;
 }
Exemplo n.º 40
0
 //-------------------------------------------------------------------
 // CreateParaclient
 //-------------------------------------------------------------------
 internal override void CreateParaclient(
     out IntPtr paraClientHandle) // OUT: opaque to PTS paragraph client
 {
     Invariant.Assert(false);     // No valid para client for a row paragraph.
     paraClientHandle = IntPtr.Zero;
 }
Exemplo n.º 41
0
 public override void VisitInvariant(Invariant invariant)
 {
     seenDup = false;
     base.VisitInvariant(invariant);
 }
Exemplo n.º 42
0
        public override Invariant VisitInvariant(Invariant invariant)
        {
            this.insideInvariant = true;

            try
            {
                return base.VisitInvariant(invariant);
            }
            finally
            {
                this.insideInvariant = false;
            }
        }
Exemplo n.º 43
0
 public static void Replace(List<Property> autoprops, Invariant condition)
 {
     var v = new ReplaceAutoPropertiesWithCorrespondingFields(autoprops);
     v.Visit(condition);
 }
Exemplo n.º 44
0
            public static void Transform(ExtractorVisitor parent, Property autoProp, Invariant invariant,
                out Requires req, out Ensures ens)
            {
                var makeReq = new ChangePropertyInvariantIntoRequiresEnsures(parent, autoProp);
                req = makeReq.MakeRequires(invariant.Condition);

                var makeEns = new ChangePropertyInvariantIntoRequiresEnsures(parent, autoProp);
                ens = makeEns.MakeEnsures(invariant.Condition);

                ens.SourceContext = invariant.SourceContext;
                ens.PostCondition.SourceContext = ens.SourceContext;
                ens.ILOffset = invariant.ILOffset;

                if (ens.SourceConditionText == null)
                {
                    ens.SourceConditionText = invariant.SourceConditionText;
                }

                req.SourceContext = invariant.SourceContext;
                req.Condition.SourceContext = req.SourceContext;
                req.ILOffset = invariant.ILOffset;

                if (req.SourceConditionText == null)
                {
                    req.SourceConditionText = invariant.SourceConditionText;
                }
            }
Exemplo n.º 45
0
        private void ExtractIndividualInvariants(TypeNode type, InvariantList result, Method invariantMethod)
        {
            if (invariantMethod == null || invariantMethod.Body == null || invariantMethod.Body.Statements == null ||
                invariantMethod.Body.Statements.Count == 0)
            {
                return;
            }

            Block invariantMethodBody = invariantMethod.Body;
            int n = invariantMethodBody.Statements.Count;

            int beginning = 0;

            while (beginning < invariantMethodBody.Statements.Count &&
                   invariantMethodBody.Statements[beginning] is PreambleBlock)
            {
                beginning++;
            }

            for (int i = beginning; i < n; i++)
            {
                Block b = (Block) invariantMethodBody.Statements[i];
                int seginning = 0;
                for (int j = 0, m = b.Statements == null ? 0 : b.Statements.Count; j < m; j++)
                {
                    ExpressionStatement s = b.Statements[j] as ExpressionStatement;
                    if (s == null) continue;

                    Literal invariantName;
                    Literal sourceText;
                    Expression invariantCondition = this.contractNodes.IsInvariant(s, out invariantName, out sourceText);
                    if (invariantCondition == null)
                    {
                        Method called = HelperMethods.IsMethodCall(s);
                        if (called != null)
                        {
                            if (HelperMethods.IsVoidType(called.ReturnType))
                            {
                                this.CallErrorFound(new Error(1045,
                                    "Invariant methods must be a sequence of calls to Contract.Invariant(...)",
                                    s.SourceContext));
                                return;
                            }
                        }

                        continue;
                    }

                    // construct a clump from
                    // invariantMethodBody.Statements[beginning].Statements[seginning] to
                    // invariantMethodBody.Statements[i].Statements[j]
                    Block currentClump = new Block(HelperMethods.ExtractClump(invariantMethodBody.Statements, beginning, seginning, i, j));

                    BlockExpression be = new BlockExpression(currentClump, SystemTypes.Void);
                    Invariant inv = new Invariant(type, be, invariantMethod.Name.Name);
                    inv.UserMessage = invariantName;
                    inv.SourceConditionText = sourceText;

                    SourceContext sctx;
                    if (HelperMethods.FindContext(currentClump, s.SourceContext, out sctx))
                    {
                        inv.SourceContext = sctx;
                        inv.Condition.SourceContext = sctx;
                    }

                    inv.ILOffset = s.ILOffset;
                    inv.UsesModels = CodeInspector.UsesModel(inv.Condition, this.contractNodes);
                    if (inv.UsesModels)
                    {
                        this.HandleError(invariantMethod, 1072, "Invariants cannot refer to model members.", sctx);
                    }
                    else
                    {
                        result.Add(inv);
                    }

                    // Re-initialize current state

                    beginning = i;
                    seginning = j + 1;
                    b = (Block) invariantMethodBody.Statements[i]; // IMPORTANT! Need this to keep "b" in sync
                }
            }
        }
Exemplo n.º 46
0
        private Invariant TryLiftingPropertyInvariantToPropertyRequiresEnsures(TypeNode typeNode, Invariant invariant)
        {
            List<Member> referencedMembers;
            var autoprops = AutoPropFinder.FindAutoProperty(this, typeNode, invariant.Condition, out referencedMembers);

            if (autoprops == null || autoprops.Count == 0) return invariant;

            foreach (var autoPropertyUsed in autoprops)
            {
                var getter = HelperMethods.Unspecialize(autoPropertyUsed.Getter);
                if (!AllReferencedMembersAsVisibleAs(getter, referencedMembers)) continue;

                var setter = HelperMethods.Unspecialize(autoPropertyUsed.Setter);

                if (getter.Contract == null)
                {
                    getter.Contract = new MethodContract(getter);
                }

                if (setter.Contract == null)
                {
                    setter.Contract = new MethodContract(setter);
                }

                var ensuresList = getter.Contract.Ensures;
                if (ensuresList == null)
                {
                    getter.Contract.Ensures = ensuresList = new EnsuresList();
                }

                var requiresList = setter.Contract.Requires;
                if (requiresList == null)
                {
                    setter.Contract.Requires = requiresList = new RequiresList();
                }

                var validationList = setter.Contract.Validations;
                if (validationList == null)
                {
                    setter.Contract.Validations = validationList = new RequiresList();
                }

                Requires req;
                Ensures ens;
                ChangePropertyInvariantIntoRequiresEnsures.Transform(this, autoPropertyUsed, invariant, out req, out ens);

                requiresList.Add(req);
                validationList.Add(req);
                ensuresList.Add(ens);

                // make sure the property getter isn't visited again
                if (!this.visitedMethods.ContainsKey(autoPropertyUsed.Getter))
                {
                    this.visitedMethods.Add(autoPropertyUsed.Getter, autoPropertyUsed.Getter);
                }

                if (!this.visitedMethods.ContainsKey(autoPropertyUsed.Setter))
                {
                    this.visitedMethods.Add(autoPropertyUsed.Setter, autoPropertyUsed.Setter);
                }
            }

            ReplaceAutoPropertiesWithCorrespondingFields.Replace(autoprops, invariant);
            return invariant;
        }
Exemplo n.º 47
0
 public virtual Invariant VisitInvariant(Invariant @invariant){
   if (@invariant == null) return null;
   @invariant.Condition = VisitExpression(@invariant.Condition);
   return @invariant;
 }
Exemplo n.º 48
0
 public override Invariant VisitInvariant(Invariant @invariant) {
   if (this.currentType != null && this.currentType.Contract != null && this.currentType.Contract.InvariantMethod != null) {
     Method savedCurrentMethod = this.currentMethod;
     this.insideInvariant = true;
     this.currentMethod = this.currentType.Contract.InvariantMethod;
     @invariant.Condition = VisitBooleanExpression(@invariant.Condition);
     this.currentMethod = savedCurrentMethod;
     this.insideInvariant = false;
     return @invariant;
   } else {
     return @invariant;
   }
 }
Exemplo n.º 49
-1
 private bool EmitInvariant(Invariant invariant, bool skipQuantifiers) {
   return !CodeInspector.IsRuntimeIgnored(invariant, this.runtimeContracts.ContractNodes, null, skipQuantifiers);
 }
Exemplo n.º 50
-1
 public override Invariant VisitInvariant(Invariant @invariant) {
   if (@invariant == null) return null;
   SourceContext sctx = @invariant.SourceContext;
   if (invariant.SourceConditionText != null)
   {
     this.sourceTextOfInvariant = invariant.SourceConditionText;
   }
   else if (sctx.IsValid && sctx.Document.Text != null && sctx.Document.Text.Source != null)
   {
     this.sourceTextOfInvariant = new Literal(sctx.Document.Text.Source, SystemTypes.String);
   } else {
     this.sourceTextOfInvariant = Literal.Null;
     //this.sourceTextOfInvariant = new Literal("No other information available", SystemTypes.String);
   }
   return base.VisitInvariant(@invariant);
 }
Exemplo n.º 51
-12
 public virtual void VisitInvariant(Invariant @invariant)
 {
   if (@invariant == null) return;
   VisitExpression(@invariant.Condition);
 }