示例#1
0
        private static TopDict[] LoadTopDicts(FontSource p, uint offset, ByteSegment[] cffIndex, ByteSegment[] strings)
        {
            var arr = new TopDict[cffIndex.Length];

            for (var i = 0; i < cffIndex.Length; i++)
            {
                var bsi           = cffIndex[i];
                var topDict       = CffDictParser.LoadTopDict(p.Bytes, bsi.Offset, bsi.Count, strings);
                var privateSize   = topDict.Private[0];
                var privateOffset = topDict.Private[1];
                if (privateSize != 0 && privateOffset != 0)
                {
                    var privateDict =
                        CffDictParser.LoadPrivateDict(p.Bytes, privateOffset + offset, privateSize);
                    topDict.DefaultWidthX = privateDict.DefaultWidthX;
                    topDict.NormalWidthX  = privateDict.NormalWidthX;
                    if (privateDict.Subrs != 0)
                    {
                        var subrOffset = privateOffset + privateDict.Subrs;
                        p.Offset = subrOffset + offset;
                        var subrIndex = LoadIndexData(p);
                        topDict.Subrs     = subrIndex;
                        topDict.SubrsBias = GetSubrBias(topDict.Subrs.Length);
                    }

                    topDict.PrivateDict = privateDict;
                }

                arr[i] = topDict;
            }
            return(arr);
        }
示例#2
0
        FontContent ProcessFont(LocaleSource input, KeyboardLayoutContent keyboardLayoutContent, ContentProcessorContext context)
        {
            // Get all code points used by this keyboard layout
            List <char> codePoints = new List <char>();

            VirtualKeyContent[] keys = keyboardLayoutContent.Keys;
            foreach (VirtualKeyContent key in keys)
            {
                if (key == null)
                {
                    continue;
                }

                foreach (VirtualKeyValue value in key.ShiftStates)
                {
                    if (value != VirtualKeyValue.Empty)
                    {
                        GetCodePointsFromCharacters(value.Characters.ToCharArray(), codePoints);
                    }
                }
            }

            foreach (DeadKey deadKey in keyboardLayoutContent.DeadKeys.Values)
            {
                GetCodePointsFromCharacters(deadKey.CombinedCharacters, codePoints);
            }

            codePoints.Sort();
            context.Logger.LogMessage("Keyboard layout for locale {0} requires {1} code points", input.CultureInfo.Name, codePoints.Count);
            FontSource fs = new FontSource(input.FontName, codePoints.ToArray());

            return(context.Convert <FontSource, FontContent>(fs, "FontProcessor"));
        }
示例#3
0
        private static ByteSegment[] LoadIndexData(FontSource p)
        {
            var count = p.ReadUShort();

            if (count <= 0)
            {
                return(null);
            }

            var offSize = p.ReadByte();
            var offsets = new uint[count + 1];

            for (var i = 0; i < offsets.Length; i++)
            {
                offsets[i] = p.ReadUInt(offSize);
            }
            var segments = new ByteSegment[count];

            for (var i = 0; i < offsets.Length - 1; i++)
            {
                segments[i] = new ByteSegment(p.Offset + offsets[i] - 1, offsets[i + 1] - offsets[i]);
            }
            p.Offset += offsets[offsets.Length - 1] - 1;
            return(segments);
        }
示例#4
0
 static FontCache()
 {
     using (Stream fontStream = ...)
     {
         FontCache.MyCoolFontSource = new FontSource(fontStream);
     }
 }
示例#5
0
        private void LoadFontList()
        {
            if (!_IsFontLoading)
            {
                _IsFontLoading = true;
                FontSource.Clear();

                //폰트 콤보
                FontHelper.LoadAllFont(FontSource, FontTypes.All, () =>
                {
                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        var selected = FontSource.FirstOrDefault(x => x.Key == Settings.Subtitle.FontFamily);
                        if (selected == null)
                        {
                            Settings.Subtitle.FontFamily = Settings.FONT_FAMILY_DEFAUT;
                            selected = FontSource.FirstOrDefault(x => x.Key == Settings.Subtitle.FontFamily);
                        }

                        FontFamily     = selected;
                        _IsFontLoading = false;
                    });
                });
            }
        }
示例#6
0
 public TrueTypeFontMarkerSymbol(FontSource fontSource, string fontFamily, int charCode, double fontSize)
 {
     _fontSource       = fontSource;
     _fontFamily       = fontFamily;
     _charCode         = charCode;
     _fontSize         = fontSize;
     _originalFontSize = _fontSize;
     BuildUIElement();
 }
 private void LoadedFontListCommandExecute(object arg)
 {
     FontSource.Clear();
     FontHelper.LoadAllFont(FontSource, FontTypes.CustomFont, () =>
     {
         DispatcherHelper.CheckBeginInvokeOnUI(() =>
         {
             RaisePropertyChanged("FontSource");
         });
     });
 }
示例#8
0
 internal void LoadFontList()
 {
     FontSource.Clear();
     FontHelper.LoadFonts(FontSource, FontTypes.All, null, () =>
     {
         DispatcherHelper.CheckBeginInvokeOnUI(() =>
         {
             Settings.ClosedCaption.OnPropertyChanged("CCFontFamily");
         });
     });
 }
示例#9
0
        /// <summary>
        /// Init this instance to
        /// </summary>
        public static void Init()
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            FontLoader.LoadFonts(assemblies, (fontName, s) => {
                fontName       = fontName.ToLowerInvariant();
                var copyStream = new MemoryStream();
                s.CopyTo(copyStream);
                Typefaces[fontName] = new FontSource(copyStream);
            });
        }
示例#10
0
        public static OffsetTable Load(FontSource data)
        {
            var sfntVersion = data.ReadUInt();
            var numTables   = data.ReadUShort();

            // Skip search range
            // Skip entry selector
            // Skip range shift
            data.Offset += 6;
            return(new OffsetTable(numTables, sfntVersion));
        }
示例#11
0
        public static TableRecord Load(FontSource data)
        {
            var tag = data.ReadTag().Trim();

            // Skip check sum
            data.Offset += 4;
            var offset = data.ReadUInt();

            // Skip length
            data.Offset += 4;
            return(new TableRecord(tag, offset));
        }
        protected override void SetupMainPage(MainPage mainPage)
        {
            mPage = mainPage;
            FontSource fontSource = new FontSource(Application.GetResourceStream(new Uri("SoshiLandSilverLight;component/Content/nobile.ttf", UriKind.Relative)).Stream);
            FontFamily fontFamily = new FontFamily("Nobile");

            ContentManager.SilverlightFontTranslation("SpriteFont1", new SpriteFontTTF(fontSource, fontFamily, 14));

            ChangeGameState(GameState.InGame);

            // Start the app by prompting User Name
            //ChangeGameState(GameState.EnterUserName);
        }
示例#13
0
        /// <param name="fontSize">Font size in points.</param>
        public SpriteFontTTF(FontSource source, FontFamily family, int fontSize)
        {
            this.FontFamily = family;
            this.FontSource = source;
            this.FontSize   = fontSize * pointsToPixels;

            measuringTextBlock = new TextBlock()
            {
                FontSize   = FontSize,
                FontFamily = FontFamily,
                FontSource = FontSource
            };
        }
示例#14
0
        protected override void SetupMainPage(MainPage mainPage)
        {
            FontSource uiFontSource = new FontSource(Application.GetResourceStream(
                                                         new Uri("/CatGirls;component/Content/NGO_____.TTF", UriKind.Relative)).Stream);
            FontFamily uiFontFamily = new FontFamily("News Gothic");

            ContentManager.SilverlightFontTranslation("UIFont", new SpriteFontTTF(uiFontSource, uiFontFamily, 16));


            var game = new CatGirlsGame(NamedScreenSizes.Get("web"));

            mainPage.Children.Add(game);
            game.Play();
        }
示例#15
0
        public static EncodingRecord Load(FontSource source, uint tableOffset)
        {
            var platformID           = source.ReadUShort();
            var encodingID           = source.ReadUShort();
            var encodingRecordOffset = source.ReadUInt();

            var offset = source.Offset;

            source.Offset = tableOffset + encodingRecordOffset;
            var subTableFormat = source.ReadUShort();

            source.Offset = offset;

            return(new EncodingRecord(platformID, encodingID, encodingRecordOffset, subTableFormat));
        }
示例#16
0
        private void DeleteFontCommandExecute(RoutedEventArgs args)
        {
            var element = args.OriginalSource as FrameworkElement;

            if (element != null && element.DataContext is PickerItem <string, string> )
            {
                var listView   = Lime.Xaml.Helpers.ElementHelper.FindVisualParent <ListView>(element);
                var pickerItem = element.DataContext as PickerItem <string, string>;

                var fonts = new List <PickerItem <string, string> >(FontSource.Where(x => x.Payload2 == pickerItem.Payload2));

                //자막 설정의 폰트 리스트 삭제
                MessengerInstance.Send(new Message("DeleteFonts", fonts), SubtitleSettingViewModel.NAME);
                //폰트 삭제
                FontHelper.RemoveFont(listView, FontSource, pickerItem);
            }
        }
示例#17
0
        /// <summary>
        /// Creates DXFont from params
        /// </summary>
        public void CreateDXFont()
        {
            switch (FontSource)
            {
            case GuiFontType.SystemFont:
            {
                string name = "Tahoma";
                float  size = 12.0f;
                System.Drawing.FontStyle style = System.Drawing.FontStyle.Regular;

                if (FontParams.ContainsKey("FontName"))
                {
                    name = FontParams["FontName"];
                }
                if (FontParams.ContainsKey("FontSize"))
                {
                    float.TryParse(FontParams["FontSize"], out size);
                }
                if (FontParams.ContainsKey("FontStyle"))
                {
                    style = (System.Drawing.FontStyle)System.Drawing.FontStyle.Parse(style.GetType(), FontParams["FontStyle"]);
                }

                this.dxFont = new Microsoft.DirectX.Direct3D.Font(GameEngine.Instance.RenderEngine.Device,
                                                                  new System.Drawing.Font(name, size, style));

                break;
            }

            default:
            {
                this.dxFont = new Microsoft.DirectX.Direct3D.Font(GameEngine.Instance.RenderEngine.Device, GameEngine.Instance.Target.Font);
                Console.Write("\t\tUnknown FontSource: " + FontSource.ToString());

                break;
            }
            }
        }
示例#18
0
 private void RegisterMessages()
 {
     MessengerInstance.Register <Message>(this, NAME, (msg) =>
     {
         switch (msg.Key)
         {
         case "DeleteFonts":
             var fonts = msg.GetValue <List <PickerItem <string, string> > >();
             for (int i = FontSource.Count - 1; i >= 0; i--)
             {
                 var storageFile = FontSource[i].Payload2 as StorageFile;
                 if (storageFile != null)
                 {
                     if (fonts.Any(x => (x.Payload2 as StorageFile).Path == storageFile.Path))
                     {
                         FontSource.RemoveAt(i);
                     }
                 }
             }
             break;
         }
     });
 }
示例#19
0
    private void Start()
    {
        var source = new FontSource(_font.bytes);

        var fontModel = FontModel.Load(source);

        var codePoints = UnicodeUtility.ToCodePoints(_text);

        _contourPoints = new List <GlyphContourInfoV2>(codePoints.Length);

        var offset = 0f;

        for (var i = 0; i < codePoints.Length; i++)
        {
            try
            {
                var codePoint = codePoints[i];
                var glyph     = fontModel.GetGlyph(codePoint, source);
                var con       = glyph.ToVector2(fontModel, source);
                ShowPoint(con, offset);
                offset += con.AdvancedWidth;
                _contourPoints.Add(con);
            }
            catch (FontException e)
            {
                Debug.LogWarning(e);

                // Replace with a tofu glyph.
                var glyph = fontModel.GetNotDefGlyph(source);
                var con   = glyph.ToVector2(fontModel, source);
                ShowPoint(con, offset);
                offset += con.AdvancedWidth;
                _contourPoints.Add(con);
            }
        }
    }
示例#20
0
        static RectRegion BuildUI()
        {
            var fs = new FontSource();

            var tr = new TextRegion()
            {
                Text      = Lorem.Text,
                GridColor = new Color4(0.7f, 0.7f, 0.7f, 1.0f),
                FontSize  = 36,
            };

            var list = new ListRegion <FontInfo>(fs);

            list.SelectionChanged += () =>
            {
                tr.Style.Font = list.Selected;
            };

            return(new HorizontalSplitter
            {
                Left = list,
                Right = tr,
            });
        }
示例#21
0
        private static byte[] LoadFdSelect(FontSource p, uint offset, uint glyphCount, uint fdArrayCount)
        {
            var fdSelect = new List <byte>();

            p.Offset = offset;
            var format = p.ReadByte();

            if (format == 0)
            {
                // Simple list of nGlyphs elements
                for (var i = 0; i < glyphCount; i++)
                {
                    var fdIndex = p.ReadByte();
                    if (fdIndex >= fdArrayCount)
                    {
                        throw new FontException($"Invalid value: FDIndex={fdIndex}, FDArrayCount={fdArrayCount}");
                    }
                    fdSelect.Add(fdIndex);
                }
            }
            else if (format == 3)
            {
                // Ranges
                var nRanges = p.ReadUShort();
                var first   = p.ReadUShort();
                if (first != 0)
                {
                    throw new FontException($"Invalid value: first={first}");
                }
                ushort next = 0;
                for (var i = 0; i < nRanges; i++)
                {
                    var fdIndex = p.ReadByte();
                    next = p.ReadUShort();
                    if (fdIndex > fdArrayCount)
                    {
                        throw new FontException($"Invalid value: FDIndex={fdIndex}, FDArrayCount={fdArrayCount}");
                    }
                    if (next > glyphCount)
                    {
                        throw new FontException($"Invalid value: next={next}, glyphCount={glyphCount}");
                    }
                    while (first < next)
                    {
                        fdSelect.Add(fdIndex);
                        first++;
                    }

                    first = next;
                }

                if (next != glyphCount)
                {
                    throw new FontException($"Invalid value: next={next}, glyphCount={glyphCount}");
                }
            }
            else
            {
                throw new FontException($"Unsupported format: {format}");
            }

            return(fdSelect.ToArray());
        }
示例#22
0
        protected override void RegisterEventHandler()
        {
            //폰트 변경시 재로드
            FontHelper.FontFamilyListChanged += (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) =>
            {
                if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                {
                    foreach (KeyName item in e.NewItems)
                    {
                        if (!FontSource.Contains(item))
                        {
                            FontSource.Add(item);
                        }
                    }
                }
                else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
                {
                    foreach (KeyName item in e.OldItems)
                    {
                        if (!FontSource.Contains(item))
                        {
                            FontSource.Remove(item);
                        }
                    }

                    if (e.OldItems.Cast <KeyName>().Any(x => x.Key.ToString() == Settings.ClosedCaption.CCFontFamily))
                    {
                        Settings.ClosedCaption.CCFontFamily = FontHelper.FONT_FAMILY_DEFAUT;
                        //폰트가 삭제되어 선택이 사라지는 현상을 제거하기 위해 저장
                        _SettingDAO.Replace(Settings);
                    }
                }

                Settings.ClosedCaption.OnPropertyChanged("CCFontFamily");
            };

            SampleImageSizeChangedEventHandler = (sender, args) =>
            {
                if (args.NewSize.Width != 0 && args.NewSize.Height != 0)
                {
                    SampleImageSize = args.NewSize;
                }
            };

            SampleImageOpenedEventHandler = (sender, args) =>
            {
                if (SampleSubtitleData == null)
                {
                    var resource = ResourceLoader.GetForCurrentView();

                    JsonObject obj = new JsonObject()
                    {
                        ["Pts"] = JsonValue.CreateNumberValue(0),
                        ["StartDisplayTime"] = JsonValue.CreateNumberValue(0),
                        ["EndDisplayTime"]   = JsonValue.CreateNumberValue(0),
                        ["Format"]           = JsonValue.CreateNumberValue(1),
                        ["NumRects"]         = JsonValue.CreateNumberValue(1),
                        ["Rects"]            = new JsonArray()
                        {
                            new JsonObject()
                            {
                                ["Guid"]  = JsonValue.CreateStringValue(""),
                                ["Type"]  = JsonValue.CreateNumberValue(3),
                                ["Text"]  = JsonValue.CreateStringValue(""),
                                ["Ass"]   = JsonValue.CreateStringValue(resource.GetString("Sample/Subtitle/Text")),
                                ["Style"] = new JsonObject()
                                {
                                    ["Name"]             = JsonValue.CreateStringValue(""),
                                    ["FontSize"]         = JsonValue.CreateStringValue(resource.GetString("Sample/Subtitle/BaseFontSize")),
                                    ["BorderStyle"]      = JsonValue.CreateStringValue("1"),
                                    ["OutlineThickness"] = JsonValue.CreateNumberValue(1),
                                    ["ShadowThickness"]  = JsonValue.CreateNumberValue(1.5),
                                    ["MarginLeft"]       = JsonValue.CreateStringValue("6"),
                                    ["MarginRight"]      = JsonValue.CreateStringValue("6"),
                                    ["MarginBottom"]     = JsonValue.CreateStringValue("24")
                                }
                            }
                        }
                    };

                    SampleSubtitleData = obj;
                }

                var img        = sender as Image;
                var storyboard = img.Resources["FadeInStoryboard"] as Storyboard;
                storyboard.Begin();
            };

            ImageRefreshTappedEventHandler = (sender, args) =>
            {
                if (!_SampleImageUriEnumerator.MoveNext())
                {
                    _SampleImageUriEnumerator.Reset();
                    _SampleImageUriEnumerator.MoveNext();
                }

                SampleImageSource = new BitmapImage(_SampleImageUriEnumerator.Current as Uri);
            };

            FontFamilyComboBoxLoadedEventHandler = (sender, args) =>
            {
                _FontFamilyComboBox = sender as ComboBox;
                //폰트 로드
                if (FontSource.Count == 0)
                {
                    LoadFontList();
                }
            };
        }
示例#23
0
        private CompactFontFormatTable(FontSource source, FontModel font)
        {
            var tableOffset = source.Offset;

            // Header
            // Skip h_major, h_minor, h_hdrSize, h_offSize
            source.Offset += 4;

            // Ignore Name Index
            LoadIndexData(source);

            // Top Dict Index
            var topDictIndex = LoadIndexData(source);

            // String Index
            var stringIndex = LoadIndexData(source);

            var globalSubrIndex = LoadIndexData(source);

            if (globalSubrIndex != null)
            {
                font.GSubrs     = globalSubrIndex;
                font.GSubrsBias = GetSubrBias(font.GSubrs.Length);
            }

            var topDictArray = LoadTopDicts(source, tableOffset, topDictIndex, stringIndex);

            if (topDictArray.Length != 1)
            {
                throw new FontException($"Too Many TopDict: {topDictArray.Length}");
            }

            font.TopDict = topDictArray[0];

            if (font.TopDict.PrivateDict != null)
            {
                font.DefaultWidthX = font.TopDict.PrivateDict.DefaultWidthX;
                font.NormalWidthX  = font.TopDict.PrivateDict.NormalWidthX;
            }

            font.IsCidFont = font.TopDict.ROS.Item1 != null && font.TopDict.ROS.Item2 != null;

            if (font.IsCidFont)
            {
                if (!font.TopDict.FDArrayIndex.HasValue || font.TopDict.FDArrayIndex.Value == 0)
                {
                    throw new FontException("FDArray is missing.");
                }

                if (!font.TopDict.FDSelectIndex.HasValue || font.TopDict.FDSelectIndex.Value == 0)
                {
                    throw new FontException("FDSelect is missing");
                }

                var fdArrayOffset  = tableOffset + font.TopDict.FDArrayIndex.Value;
                var fdSelectOffset = tableOffset + font.TopDict.FDSelectIndex.Value;

                source.Offset = fdArrayOffset;
                var fdArrayIndex = LoadIndexData(source);
                font.TopDict.FDArray =
                    LoadTopDicts(source, tableOffset, fdArrayIndex, stringIndex);
                font.TopDict.FDSelect =
                    LoadFdSelect(source, fdSelectOffset, font.GlyphCount, (uint)font.TopDict.FDArray.Length);
            }

            var privateDictOffset = tableOffset + font.TopDict.Private[1];
            var privateDict       = CffDictParser.LoadPrivateDict(source.Bytes, privateDictOffset, font.TopDict.Private[0]);

            font.DefaultWidthX = privateDict.DefaultWidthX;
            font.NormalWidthX  = privateDict.NormalWidthX;

            if (privateDict.Subrs != 0)
            {
                var subrOffset = privateDictOffset + privateDict.Subrs;
                source.Offset = subrOffset;
                var subrIndex = LoadIndexData(source);
                font.Subrs     = subrIndex;
                font.SubrsBias = GetSubrBias(font.Subrs.Length);
            }
            else
            {
                font.Subrs     = new ByteSegment[0];
                font.SubrsBias = 0;
            }

            source.Offset    = tableOffset + font.TopDict.CharStrings;
            _charStringIndex = LoadIndexData(source);
        }
示例#24
0
 public static CompactFontFormatTable Load(uint tableOffset, FontSource p, FontModel font)
 {
     p.Offset = tableOffset;
     return(new CompactFontFormatTable(p, font));
 }
示例#25
0
文件: Value.cs 项目: ynkbt/moon
        //
        // How do we support "null" values, should the caller take care of that?
        //
        // The caller is responsible for calling value_free_value on the returned Value
        public static Value FromObject(object v, bool box_value_types)
        {
            Value value = new Value();

            unsafe {
                if (box_value_types && (v is ValueType || v is string))
                {
                    value.boxed_valuetype = GCHandle.Alloc(v);
                }

                if (v is IEasingFunction && !(v is EasingFunctionBase))
                {
                    v = new EasingFunctionWrapper(v as IEasingFunction);
                }

                if (v is INativeEventObjectWrapper)
                {
                    INativeEventObjectWrapper dov = (INativeEventObjectWrapper)v;

                    if (dov.NativeHandle == IntPtr.Zero)
                    {
                        throw new Exception(String.Format(
                                                "Object {0} has not set its native property", dov.GetType()));
                    }

                    NativeMethods.event_object_ref(dov.NativeHandle);

                    value.Kind = dov.GetKind();
                    value.u.p  = dov.NativeHandle;
                }
                else if (v is DependencyProperty)
                {
                    value.Kind = Kind.DEPENDENCYPROPERTY;
                    value.u.p  = ((DependencyProperty)v).Native;
                }
                else if (v is int || (v.GetType().IsEnum&& Enum.GetUnderlyingType(v.GetType()) == typeof(int)))
                {
                    value.Kind  = Deployment.Current.Types.TypeToKind(v.GetType());
                    value.u.i32 = (int)v;
                }
                else if (v is byte || (v.GetType().IsEnum&& Enum.GetUnderlyingType(v.GetType()) == typeof(byte)))
                {
                    value.Kind  = Deployment.Current.Types.TypeToKind(v.GetType());
                    value.u.i32 = (byte)v;
                }
                else if (v is bool)
                {
                    value.Kind  = Kind.BOOL;
                    value.u.i32 = ((bool)v) ? 1 : 0;
                }
                else if (v is double)
                {
                    value.Kind = Kind.DOUBLE;
                    value.u.d  = (double)v;
                }
                else if (v is float)
                {
                    value.Kind = Kind.FLOAT;
                    value.u.f  = (float)v;
                }
                else if (v is long)
                {
                    value.Kind  = Kind.INT64;
                    value.u.i64 = (long)v;
                }
                else if (v is TimeSpan)
                {
                    TimeSpan ts = (TimeSpan)v;
                    value.Kind  = Kind.TIMESPAN;
                    value.u.i64 = ts.Ticks;
                }
                else if (v is ulong)
                {
                    value.Kind   = Kind.UINT64;
                    value.u.ui64 = (ulong)v;
                }
                else if (v is uint)
                {
                    value.Kind   = Kind.UINT32;
                    value.u.ui32 = (uint)v;
                }
                else if (v is char)
                {
                    value.Kind   = Kind.CHAR;
                    value.u.ui32 = (uint)(char)v;
                }
                else if (v is string)
                {
                    value.Kind = Kind.STRING;

                    value.u.p = StringToIntPtr((string)v);
                }
                else if (v is Rect)
                {
                    Rect rect = (Rect)v;
                    value.Kind = Kind.RECT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Rect));
                    Marshal.StructureToPtr(rect, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is Size)
                {
                    Size size = (Size)v;
                    value.Kind = Kind.SIZE;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Size));
                    Marshal.StructureToPtr(size, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is CornerRadius)
                {
                    CornerRadius corner = (CornerRadius)v;
                    value.Kind = Kind.CORNERRADIUS;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(CornerRadius));
                    Marshal.StructureToPtr(corner, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is AudioFormat)
                {
                    AudioFormat f = (AudioFormat)v;
                    value.Kind = Kind.AUDIOFORMAT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedAudioFormat));
                    UnmanagedAudioFormat *format = (UnmanagedAudioFormat *)value.u.p;
                    format->bitsPerSample    = f.BitsPerSample;
                    format->channels         = f.Channels;
                    format->samplesPerSecond = f.SamplesPerSecond;
                    format->waveFormat       = f.WaveFormat;
                }
                else if (v is VideoFormat)
                {
                    VideoFormat f = (VideoFormat)v;
                    value.Kind = Kind.VIDEOFORMAT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedVideoFormat));
                    UnmanagedVideoFormat *format = (UnmanagedVideoFormat *)value.u.p;
                    format->framesPerSecond = f.FramesPerSecond;
                    format->height          = f.PixelHeight;
                    format->width           = f.PixelWidth;
                    format->stride          = f.Stride;
                    format->pixelFormat     = f.PixelFormat;
                }
                else if (v is Point)
                {
                    Point pnt = (Point)v;
                    value.Kind = Kind.POINT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Point));
                    Marshal.StructureToPtr(pnt, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is Thickness)
                {
                    Thickness thickness = (Thickness)v;
                    value.Kind = Kind.THICKNESS;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Thickness));
                    Marshal.StructureToPtr(thickness, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is Color)
                {
                    Color c = (Color)v;
                    value.Kind = Kind.COLOR;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedColor));
                    UnmanagedColor *color = (UnmanagedColor *)value.u.p;
                    color->r = c.R / 255.0f;
                    color->g = c.G / 255.0f;
                    color->b = c.B / 255.0f;
                    color->a = c.A / 255.0f;
                }
                else if (v is Matrix)
                {
                    // hack around the fact that managed Matrix is a struct while unmanaged Matrix is a DO
                    // i.e. the unmanaged and managed structure layouts ARE NOT equal
                    return(FromObject(new UnmanagedMatrix((Matrix)v), box_value_types));
                }
                else if (v is StylusPoint)
                {
                    return(FromObject(new UnmanagedStylusPoint((StylusPoint)v), box_value_types));
                }
                else if (v is Matrix3D)
                {
                    // hack around the fact that managed Matrix3D is a struct while unmanaged Matrix3D is a DO
                    // i.e. the unmanaged and managed structure layouts ARE NOT equal
                    return(FromObject(new UnmanagedMatrix3D((Matrix3D)v), box_value_types));
                }
                else if (v is Duration)
                {
                    Duration d = (Duration)v;
                    value.Kind = Kind.DURATION;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(Duration));
                    Marshal.StructureToPtr(d, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is KeyTime)
                {
                    KeyTime k = (KeyTime)v;
                    value.Kind = Kind.KEYTIME;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(KeyTime));
                    Marshal.StructureToPtr(k, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is RepeatBehavior)
                {
                    RepeatBehavior d = (RepeatBehavior)v;
                    value.Kind = Kind.REPEATBEHAVIOR;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(RepeatBehavior));
                    Marshal.StructureToPtr(d, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontFamily)
                {
                    FontFamily family = (FontFamily)v;
                    value.Kind = Kind.FONTFAMILY;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontFamily));
                    Marshal.StructureToPtr(family, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }

                else if (v is FontSource)
                {
                    FontSource source = (FontSource)v;

                    value.Kind = Kind.FONTSOURCE;

                    if (source.wrapper != null || source.typeface != null)
                    {
                        value.u.p = Marshal.AllocHGlobal(sizeof(UnmanagedFontSource));
                        UnmanagedFontSource *ufs = (UnmanagedFontSource *)value.u.p;
                        ufs->type = source.type;

                        switch (source.type)
                        {
                        case FontSourceType.ManagedStream:
                            ManagedStreamCallbacks callbacks = source.wrapper.GetCallbacks();
                            ufs->source.stream = Marshal.AllocHGlobal(sizeof(UnmanagedStreamCallbacks));
                            Marshal.StructureToPtr(callbacks, ufs->source.stream, false);
                            break;

                        case FontSourceType.GlyphTypeface:
                            ufs->source.typeface = source.typeface.Native;
                            break;
                        }
                    }
                    else
                    {
                        value.IsNull = true;
                    }
                }

                else if (v is PropertyPath)
                {
                    PropertyPath propertypath = (PropertyPath)v;
                    value.Kind = Kind.PROPERTYPATH;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedPropertyPath));

                    UnmanagedPropertyPath *upp = (UnmanagedPropertyPath *)value.u.p;
                    upp->property = propertypath.NativeDP;
                    if (upp->property == IntPtr.Zero)
                    {
                        upp->pathString         = StringToIntPtr(propertypath.Path);
                        upp->expandedPathString = StringToIntPtr(propertypath.ExpandedPath);
                    }
                    else
                    {
                        upp->pathString         = IntPtr.Zero;
                        upp->expandedPathString = IntPtr.Zero;
                    }
                }
                else if (v is Uri)
                {
                    Uri uri = (Uri)v;

                    value.Kind = Kind.URI;
                    value.u.p  = UriHelper.ToNativeUri(uri);
                }
                else if (v is XmlLanguage)
                {
                    XmlLanguage lang = (XmlLanguage)v;

                    value.Kind = Kind.XMLLANGUAGE;
                    value.u.p  = StringToIntPtr(lang.IetfLanguageTag);
                }
                else if (v is Cursor)
                {
                    Cursor c = (Cursor)v;

                    value.Kind  = Kind.CURSORTYPE;
                    value.u.i32 = (int)c.cursor;
                }
                else if (v is GridLength)
                {
                    GridLength gl = (GridLength)v;
                    value.Kind = Kind.GRIDLENGTH;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(GridLength));
                    Marshal.StructureToPtr(gl, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontStretch)
                {
                    FontStretch stretch = (FontStretch)v;
                    value.Kind = Kind.FONTSTRETCH;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontStretch));
                    Marshal.StructureToPtr(stretch, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontStyle)
                {
                    FontStyle style = (FontStyle)v;
                    value.Kind = Kind.FONTSTYLE;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontStyle));
                    Marshal.StructureToPtr(style, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is FontWeight)
                {
                    FontWeight weight = (FontWeight)v;
                    value.Kind = Kind.FONTWEIGHT;
                    value.u.p  = Marshal.AllocHGlobal(sizeof(UnmanagedFontWeight));
                    Marshal.StructureToPtr(weight, value.u.p, false);                      // Unmanaged and managed structure layout is equal.
                }
                else if (v is TextDecorationCollection)
                {
                    value.Kind  = Kind.TEXTDECORATIONS;
                    value.u.i32 = (int)(v as TextDecorationCollection).Kind;
                }
                else if (v is Type)
                {
                    Type t = v as Type;
                    value.Kind = Kind.MANAGEDTYPEINFO;
                    value.u.p  = NativeMethods.managed_type_info_new(Deployment.Current.Types.TypeToKind(t));
                }
                else if (v is Value)
                {
                    throw new InvalidOperationException("You can not create a Mono.Value from a Mono.Value.");
                }
                else
                {
                    //Console.WriteLine ("Do not know how to encode {0} yet, boxing it", v.GetType ());

                    // TODO: We probably need to marshal types that can animate as the
                    // corresponding type (Point, Double, Color, etc).
                    // TODO: We need to store the GCHandle somewhere so that we can free it,
                    // or register a callback on the surface for the unmanaged code to call.
                    GCHandle handle = GCHandle.Alloc(v);
                    value.IsGCHandle = true;
                    value.Kind       = Deployment.Current.Types.TypeToKind(v.GetType());
                    value.u.p        = GCHandle.ToIntPtr(handle);
                }
            }
            return(value);
        }
示例#26
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maFontGetCount = delegate()
            {
                int count = 0;
                MoSync.Util.RunActionOnMainThreadSync(() => count = System.Windows.Media.Fonts.SystemTypefaces.Count);
                return(count);
            };

            ioctls.maFontGetName = delegate(int _index, int _buffer, int _bufferLen)
            {
                if (_index > ioctls.maFontGetCount())
                {
                    return(MoSync.Constants.RES_FONT_INDEX_OUT_OF_BOUNDS);
                }
                else
                {
                    String fontName = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        int count = 0;
                        System.Collections.Generic.IEnumerator <Typeface> en = System.Windows.Media.Fonts.SystemTypefaces.GetEnumerator();
                        while (count < _index)
                        {
                            en.MoveNext();
                            count++;
                        }
                        System.Windows.Media.Typeface currentTypeFace = en.Current;
                        System.Windows.Media.GlyphTypeface currentGlyph;
                        currentTypeFace.TryGetGlyphTypeface(out currentGlyph);
                        fontName = currentGlyph.FontFileName;
                        fontName = (fontName.Split('.'))[0];
                    });

                    if (fontName.Length > _bufferLen)
                    {
                        return(MoSync.Constants.RES_FONT_INSUFFICIENT_BUFFER);
                    }
                    core.GetDataMemory().WriteStringAtAddress(_buffer, fontName, _bufferLen);
                    return(MoSync.Constants.RES_FONT_OK);
                }
            };

            ioctls.maFontLoadWithName = delegate(int _postScriptName, int _size)
            {
                String        fontName      = core.GetDataMemory().ReadStringAtAddress(_postScriptName);
                Typeface      typeface      = null;
                GlyphTypeface glyphTypeface = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    int count = Fonts.SystemTypefaces.Count;
                    System.Collections.Generic.IEnumerator <Typeface> en = Fonts.SystemTypefaces.GetEnumerator();
                    while (count != 0)
                    {
                        typeface = en.Current;
                        if (typeface.TryGetGlyphTypeface(out glyphTypeface))
                        {
                            if (glyphTypeface.FontFileName.StartsWith(fontName))
                            {
                                break;
                            }
                        }
                        en.MoveNext();
                        count--;
                    }
                });

                if (glyphTypeface == null)
                {
                    return(-2);
                }

                mFonts.Add(glyphTypeface);
                return(mFonts.Count - 1);
            };

            ioctls.maFontLoadDefault = delegate(int _type, int _style, int _size)
            {
                //RES_FONT_NO_TYPE_STYLE_COMBINATION
                //RES_FONT_INVALID_SIZE

                switch (_type)
                {
                case MoSync.Constants.FONT_TYPE_MONOSPACE:
                    break;

                case MoSync.Constants.FONT_TYPE_SERIF:
                    break;

                case MoSync.Constants.FONT_TYPE_SANS_SERIF:
                    break;

                default:
                    return(MoSync.Constants.RES_FONT_NO_TYPE_STYLE_COMBINATION);
                }

                return(0);
            };

            ioctls.maFontSetCurrent = delegate(int _font)
            {
                mCurrentFont       = mFonts[_font];
                mCurrentFontSource = new System.Windows.Documents.FontSource(mCurrentFont);
                return(0);
            };
        }