Ejemplo n.º 1
0
        private async void appBarIconBtnPreview_Click(object sender, EventArgs e)
        {
            await Task.Delay(10);

            ApplicationBar.IsVisible      = false;
            LoadingProgressBar.Visibility = System.Windows.Visibility.Visible;
            LoadingText.Text = AppResources.MsgCreatingPreview;

            LockscreenData data = new LockscreenData(false)
            {
                BackgroundBitmap = GetCropImage(),
                DayList          = VsCalendar.GetCalendarOfMonth(DateTime.Now, DateTime.Now, true, true),
                LiveWeather      = SettingHelper.Get(Constants.WEATHER_LIVE_RESULT) as LiveWeather,
                Forecasts        = SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT) as Forecasts
            };

            if ((bool)SettingHelper.Get(Constants.CALENDAR_SHOW_APPOINTMENT))
            {
                Appointments appointments = new Appointments();
                appointments.SearchCompleted += (s, se) =>
                {
                    VsCalendar.MergeCalendar(data.DayList, se.Results);
                    LockscreenHelper.RenderLayoutToBitmap(data);
                    DisplayPreview(data.BackgroundBitmap);
                };
                appointments.SearchAsync(data.DayList[7].DateTime, data.DayList[data.DayList.Count - 1].DateTime, null);
            }
            else
            {
                LockscreenHelper.RenderLayoutToBitmap(data);
                DisplayPreview(data.BackgroundBitmap);
            }
        }
Ejemplo n.º 2
0
        public static void RenderLayoutToBitmap(LockscreenData data)
        {
            Size areaSize;

            if (data.IsWVGA)
            {
                //함성할 영역
                areaSize = LockscreenHelper.GetDisplayAreaSize(Size);
            }
            else
            {
                //함성할 영역
                areaSize = LockscreenHelper.DisplayAreaSize;
            }
            data.Canvas.Width  = areaSize.Width;
            data.Canvas.Height = areaSize.Width / 2;

            double    width  = 0;
            double    height = 0;
            LiveItems item;
            Thickness innerMargin;

            LockscreenItemInfo[] lockinfo = data.Items;

            for (int i = 0; i < lockinfo.Length; i++)
            {
                item        = lockinfo[i].LockscreenItem;
                innerMargin = new Thickness(0, 0, 5, 0);
                Canvas panel = null;

                if (lockinfo[i].Column == 1)
                {
                    innerMargin.Left  = 5;
                    innerMargin.Right = 0;
                }

                if (lockinfo[i].RowSpan < 3)
                {
                    if (lockinfo[i].Row == 0)
                    {
                        innerMargin.Bottom = 5;
                    }
                    else
                    {
                        innerMargin.Top = 5;
                    }
                }

                width  = data.Canvas.Width / 2 - (lockinfo[i].Column == 0 ? innerMargin.Right : innerMargin.Left);
                height = data.Canvas.Height / 3 * lockinfo[i].RowSpan - (lockinfo[i].RowSpan < 3 ? (lockinfo[i].Row == 0 ? innerMargin.Bottom : innerMargin.Top) : 0);

                switch (item)
                {
                case LiveItems.Calendar:
                    panel = LockscreenHelper.GetCalendarCanvas(width, height, data);
                    break;

                case LiveItems.Battery:
                    panel = LockscreenHelper.GetBatteryCanvas(width, height, data);
                    break;

                case LiveItems.Weather:
                case LiveItems.NoForecast:
                    if (lockinfo.Any(x => x.LockscreenItem == LiveItems.NoForecast))
                    {
                        //날씨나 배터리... (RowSpan이 3이 아닌경우이면서, items.Length 가 3보다 작은 경우
                        data.Forecasts = null;
                    }
                    panel = LockscreenHelper.GetWeatherCanvas(width, height, data);
                    break;
                }

                if ((bool)SettingHelper.Get(Constants.LOCKSCREEN_BACKGROUND_USE_SEPARATION))
                {
                    Canvas backPanel = new Canvas()
                    {
                        Background = data.BackgroundBrush,
                        Opacity    = data.BackgroundOpacity,
                        Width      = panel.Width,
                        Height     = panel.Height
                    };
                    panel.Children.Insert(0, backPanel);
                    //panel.Background = data.BackgroundBrush;
                    //panel.Opacity = data.BackgroundOpacity;
                }

                if (lockinfo[i].Column == 1)
                {
                    Canvas.SetLeft(panel, width + innerMargin.Left * 2);
                }

                if (lockinfo[i].Row > 0)
                {
                    //총 아이템이 두개 또는 하나이면서 날씨인 경우
                    if (((lockinfo.Length <= 2 && lockinfo[i].RowSpan == 2) ||
                         !(bool)SettingHelper.Get(Constants.LOCKSCREEN_BACKGROUND_USE_SEPARATION)) &&
                        (lockinfo[i].LockscreenItem == LiveItems.Weather || lockinfo[i].LockscreenItem == LiveItems.NoForecast))
                    {
                        //날씨만 또는 날씨와 달력의 경우 날씨의 상단 여백을 -20
                        //날씨가 배터리 밑에 있고, 배경분리를 사용하지 않는 경우 날씨의 상단여백을 -20
                        Canvas.SetTop(panel, data.Canvas.Height - height - 20);
                    }
                    else
                    {
                        Canvas.SetTop(panel, data.Canvas.Height - height);
                    }
                }
                else if (lockinfo[i].RowSpan == 2 && (lockinfo[i].LockscreenItem == LiveItems.Weather || lockinfo[i].LockscreenItem == LiveItems.NoForecast) &&
                         !(bool)SettingHelper.Get(Constants.LOCKSCREEN_BACKGROUND_USE_SEPARATION))
                {
                    //날씨가 배터리 위에 있는 경우 상단 여백을 10 추가
                    Canvas.SetTop(panel, 10);
                }

                if (lockinfo[i].ColSpan == 2)
                {
                    data.Canvas.Width = panel.Width;
                }

                data.Canvas.Children.Add(panel);

                //날씨만을 표시하는 경우
                if (lockinfo.Length == 1 && lockinfo[i].LockscreenItem == LiveItems.NoForecast)
                {
                    Canvas weatherCanvas = (data.Canvas.Children[0] as Canvas);
                    data.Canvas.Height = data.Canvas.Height / 3 * 2
                                         + (double)weatherCanvas.GetValue(Canvas.TopProperty)
                                         + (double)weatherCanvas.Children[0].GetValue(Canvas.TopProperty);
                }
            }

            Thickness areaMargin;

            if (data.IsWVGA)
            {
                areaMargin = LockscreenHelper.GetDisplayAreaMargin(new Size(480, 800));
            }
            else
            {
                areaMargin = LockscreenHelper.DisplayAreaMargin;
            }

            if (data.BackgroundPanel != null)
            {
                data.BackgroundPanel.Width  = data.Canvas.Width;
                data.BackgroundPanel.Height = data.Canvas.Height;
            }

            Size            size     = new Size(data.Canvas.Width, data.Canvas.Height);
            WriteableBitmap canvasWb = new WriteableBitmap((int)data.Canvas.Width, (int)data.Canvas.Height);

            canvasWb.Render(data.Canvas, null);
            canvasWb.Invalidate();

            if (data.BackgroundBitmap != null)
            {
                data.BackgroundBitmap.Blit(new Rect(new Point(areaMargin.Left, areaMargin.Top), size), canvasWb, new Rect(new Point(), size));
            }
        }
Ejemplo n.º 3
0
        public static Canvas GetCalendarCanvas(double width, double height, LockscreenData data)
        {
            Canvas calendarCanvas = new Canvas();

            calendarCanvas.Width  = width;
            calendarCanvas.Height = height;
            SolidColorBrush phoneInactiveBrush        = (SolidColorBrush)Application.Current.Resources["PhoneInactiveBrush"];
            SolidColorBrush phoneSemitransparentBrush = (SolidColorBrush)Application.Current.Resources["PhoneSemitransparentBrush"];

            int rowNum = -1, colNum = 0;;

            for (int i = 0; i < data.DayList.Count; i++)
            {
                if (i % 7 == 0)
                {
                    rowNum++;
                    colNum = 0;
                }
                ChameleonLib.Api.Calendar.Model.Day day = data.DayList[i];

                Canvas dayPanel = new Canvas()
                {
                    Width  = calendarCanvas.Width / 7,
                    Height = calendarCanvas.Height / 7,
                };

                TextBlock dayTxt = new TextBlock()
                {
                    Text       = day.DayName,
                    FontSize   = day.FontSize * data.FontRatio,
                    Foreground = day.ForegroundBrush.Color == phoneInactiveBrush.Color ? phoneSemitransparentBrush : day.ForegroundBrush,
                    FontWeight = data.FontWeight
                };

                if (day.DateTime.ToLongDateString() == DateTime.Today.ToLongDateString())
                {
                    Ellipse ellipse = new Ellipse()
                    {
                        Width  = dayTxt.ActualHeight * 1.08,
                        Height = dayTxt.ActualHeight * 1.08,
                        Fill   = day.BackgroundBrush,
                    };

                    dayPanel.Children.Add(ellipse);
                    Canvas.SetLeft(ellipse, (dayPanel.Width - ellipse.Width) / 2);
                    Canvas.SetTop(ellipse, (dayPanel.Height - ellipse.Width) / 2 - 0.5);
                }

                if (data.DayList[i].AppointmentList != null && data.DayList[i].AppointmentList.Count > 0)
                {
                    TextBlock appCnt = new TextBlock()
                    {
                        FontSize   = day.FontSize * data.FontRatio * 0.5,
                        Text       = data.DayList[i].AppointmentList.Count.ToString(),
                        Foreground = day.DateTime.ToLongDateString() == DateTime.Now.ToLongDateString() ? day.BackgroundBrush : day.ForegroundBrush,
                        FontWeight = day.ForegroundBrush.Color == phoneInactiveBrush.Color ? FontWeights.Normal : FontWeights.Bold
                    };
                    dayPanel.Children.Add(appCnt);
                    Canvas.SetLeft(appCnt, (dayPanel.Width - appCnt.ActualWidth - 5));
                    Canvas.SetTop(appCnt, -appCnt.ActualHeight / 3);
                }

                dayPanel.Margin = new Thickness((colNum++) * dayPanel.Width, rowNum * dayPanel.Height, 0, 0);

                dayPanel.Children.Add(dayTxt);
                Canvas.SetLeft(dayTxt, (dayPanel.Width - dayTxt.ActualWidth) / 2);
                Canvas.SetTop(dayTxt, (dayPanel.Height - dayTxt.ActualHeight) / 2);
                calendarCanvas.Children.Add(dayPanel);
            }
            return(calendarCanvas);
        }
Ejemplo n.º 4
0
        public static Canvas GetBatteryCanvas(double width, double height, LockscreenData data)
        {
            Canvas batteryCanvas = new Canvas();

            batteryCanvas.Width  = width;
            batteryCanvas.Height = height;

            Thickness margin = new Thickness(10 * data.FontRatio);

            Image batteryImage = new Image()
            {
                Width  = 92 * data.FontRatio,
                Height = 92 * data.FontRatio,
                Source = BitmapFactory.New(0, 0).FromContent(
                    BatteryHelper.BateryLevel <= 5 ? "Images/lockscreen/battery.empty.png" : "Images/lockscreen/battery.full.png")
            };

            batteryCanvas.Children.Add(batteryImage);

            //if (!BatteryHelper.IsCharging && BatteryHelper.BateryLevel > 5)
            if (BatteryHelper.BateryLevel > 5)
            {
                int level = 78 * BatteryHelper.BateryLevel / 100;
                (batteryImage.Source as WriteableBitmap).FillRectangle(17, 64 - 15, 17 + level, 64 + 15, Colors.White);  //128x128 이미지 일때
            }

            Canvas    batteryStatusCanvas = new Canvas();
            TextBlock batteryRemaining    = new TextBlock()
            {
                Text       = BatteryHelper.BateryLevel.ToString(),
                Foreground = data.ForegroundBrush,
                FontSize   = data.FontSizeLarge,
                FontWeight = data.FontWeight
            };

            batteryStatusCanvas.Children.Add(batteryRemaining);

            Canvas.SetLeft(batteryRemaining, margin.Left);
            Canvas.SetTop(batteryRemaining, 0);

            TextBlock batteryRemainingDesc = new TextBlock()
            {
                Text       = string.Format("% {0}", AppResources.BatteryRemaining),
                Foreground = data.ForegroundBrush,
                FontSize   = data.FontSizeMedium,
                FontWeight = data.FontWeight
            };

            batteryStatusCanvas.Children.Add(batteryRemainingDesc);

            Canvas.SetLeft(batteryRemainingDesc, batteryRemaining.ActualWidth + margin.Left);
            Canvas.SetTop(batteryRemainingDesc, data.FontSizeLarge - data.FontSizeMedium);

            TextBlock timeRemaining = new TextBlock();

            if (BatteryHelper.IsCharging)
            {
                //    timeRemaining.Text = AppResources.BatteryCharging;
            }
            else
            {
                StringBuilder tr = new StringBuilder();
                if (BatteryHelper.BatteryTime.Days > 0)
                {
                    tr.AppendFormat(AppResources.DayShortener, BatteryHelper.BatteryTime.Days);
                    tr.Append(" ");
                }
                tr.AppendFormat(AppResources.HourShortener, BatteryHelper.BatteryTime.Hours);
                tr.Append(" ");
                tr.Append(AppResources.BatteryRemaining);
                timeRemaining.Text = tr.ToString();
            }
            timeRemaining.Foreground = data.ForegroundBrush;
            timeRemaining.FontSize   = data.FontSizeMedium;
            timeRemaining.FontWeight = data.FontWeight;

            Canvas.SetLeft(timeRemaining, margin.Left);
            Canvas.SetTop(timeRemaining, batteryRemaining.ActualHeight);

            batteryStatusCanvas.Children.Add(timeRemaining);
            batteryCanvas.Children.Add(batteryStatusCanvas);

            double leftMargin = (batteryCanvas.Width - (batteryImage.Width + (Math.Max(batteryRemaining.ActualWidth + batteryRemainingDesc.ActualWidth, timeRemaining.ActualWidth)))) / 2 - margin.Left;

            Canvas.SetLeft(batteryImage, leftMargin);
            Canvas.SetTop(batteryImage, (batteryCanvas.Height - batteryImage.ActualHeight) / 2);


            Canvas.SetTop(batteryStatusCanvas, (batteryCanvas.Height - (batteryRemaining.ActualHeight + timeRemaining.ActualHeight)) / 2);
            Canvas.SetLeft(batteryStatusCanvas, leftMargin + batteryImage.Width + margin.Left);

            return(batteryCanvas);
        }
Ejemplo n.º 5
0
        public static Canvas GetWeatherCanvas(double width, double height, LockscreenData data)
        {
            Canvas weatherCanvas = new Canvas();

            weatherCanvas.Width  = width;
            weatherCanvas.Height = height;
            Thickness margin = new Thickness(10 * data.FontRatio);

            if (data.LiveWeather != null)
            {
                WeatherIconType type = WeatherIconMap.Instance.WeatherIconType;
                string          path = string.Format(WeatherBug.ICON_LOCAL_PATH.Substring(1), type.ToString().ToLower(), "125x105", WeatherImageIconConverter.GetIamgetName(data.LiveWeather.CurrentConditionIcon));
                //string path = string.Format(WeatherBug.ICON_LOCAL_PATH.Substring(1), "125x105", WeatherImageIconConverter.GetIamgetName(data.LiveWeather.CurrentConditionIcon));
                WriteableBitmap weatherWb = BitmapFactory.New(0, 0).FromContent(path);

                //날씨 이미지
                Image ImgLiveWeather = new Image()
                {
                    Margin = new Thickness(margin.Left, 0, 0, 0),
                    Source = weatherWb,
                    Height = 140 * data.FontRatio,
                    Width  = weatherCanvas.Width / 2
                };

                string tmp = System.Globalization.CultureInfo.CurrentCulture.Name.Split('-')[0];
                if (tmp == "ko" || tmp == "ja" || tmp == "zh")
                {
                    tmp = (string.IsNullOrEmpty(data.LiveWeather.Station.State) ? string.Empty : data.LiveWeather.Station.State + " ") + data.LiveWeather.Station.City;
                }
                else
                {
                    tmp = data.LiveWeather.Station.City + (string.IsNullOrEmpty(data.LiveWeather.Station.State) ? string.Empty : " ," + data.LiveWeather.Station.State);
                }

                //지역
                TextBlock TxtLocation = new TextBlock()
                {
                    Text       = tmp,
                    FontSize   = data.FontSizeLarge,
                    Foreground = data.ForegroundBrush,
                    Width      = ImgLiveWeather.Width * 2.1,
                    FontWeight = data.FontWeight
                };

                if (TxtLocation.ActualWidth > weatherCanvas.Width)
                {
                    TxtLocation.Text = data.LiveWeather.Station.City;
                }

                Canvas tempImageCanvas = new Canvas()
                {
                    Width  = ImgLiveWeather.Width,
                    Height = ImgLiveWeather.Height
                };

                Canvas tempTextCanvas = new Canvas()
                {
                    Width  = tempImageCanvas.Width,
                    Height = tempImageCanvas.Height
                };

                Canvas etcWeaterCanvas = new Canvas()
                {
                    Width  = weatherCanvas.Width,
                    Height = 32 * data.FontRatio
                };

                Canvas.SetLeft(TxtLocation, margin.Left);
                Canvas.SetTop(TxtLocation, margin.Top);
                Canvas.SetLeft(tempTextCanvas, margin.Left);
                Canvas.SetTop(tempTextCanvas, margin.Top + TxtLocation.ActualHeight);
                Canvas.SetLeft(tempImageCanvas, tempTextCanvas.Width - margin.Left);
                Canvas.SetTop(tempImageCanvas, margin.Top + TxtLocation.ActualHeight);
                Canvas.SetLeft(etcWeaterCanvas, margin.Left);
                Canvas.SetTop(etcWeaterCanvas, margin.Top + TxtLocation.ActualHeight + tempImageCanvas.Height);

                weatherCanvas.Children.Add(TxtLocation);
                weatherCanvas.Children.Add(tempTextCanvas);
                weatherCanvas.Children.Add(tempImageCanvas);
                weatherCanvas.Children.Add(etcWeaterCanvas);

                //기온
                string[]  temp = data.LiveWeather.Temp.Value.Value.Split('.');
                TextBlock TxtLiveWeatherTemp = new TextBlock()
                {
                    Text       = temp[0],
                    FontSize   = data.FontSizeExtraExtraLarge * 1.2,
                    Foreground = data.ForegroundBrush,
                    FontWeight = data.FontWeight
                };
                TextBlock TxtLiveWeatherTempFloat = new TextBlock()
                {
                    Text       = (temp.Length > 1) ? string.Format(".{0}", temp[1]) : ".0",
                    FontSize   = data.FontSizeMedium * 1.25,
                    Foreground = data.ForegroundBrush,
                    FontWeight = data.FontWeight
                };
                TextBlock TxtLiveWeatherTempUnits = new TextBlock()
                {
                    Text       = (WeatherUnitsConverter.ConvertOnlyUnit(data.LiveWeather.Temp.Value) as ValueUnits).Units,
                    FontSize   = data.FontSizeMedium * 1.15,
                    Foreground = data.ForegroundBrush,
                    FontWeight = data.FontWeight
                };

                double tempCanvasTopMargin  = (ImgLiveWeather.Height - TxtLiveWeatherTemp.ActualHeight) / 2;
                double tempCanvasLeftMargin = (tempTextCanvas.Width - TxtLiveWeatherTemp.ActualWidth) / 2 - TxtLiveWeatherTempUnits.ActualWidth;
                Canvas.SetLeft(TxtLiveWeatherTemp, tempCanvasLeftMargin);
                Canvas.SetTop(TxtLiveWeatherTemp, tempCanvasTopMargin);
                Canvas.SetLeft(TxtLiveWeatherTempUnits, tempCanvasLeftMargin + TxtLiveWeatherTemp.ActualWidth);
                Canvas.SetTop(TxtLiveWeatherTempUnits, tempCanvasTopMargin + (TxtLiveWeatherTempUnits.ActualHeight / 2) - 5);
                Canvas.SetLeft(TxtLiveWeatherTempFloat, tempCanvasLeftMargin + TxtLiveWeatherTemp.ActualWidth + TxtLiveWeatherTempFloat.ActualWidth / 9);
                Canvas.SetTop(TxtLiveWeatherTempFloat, tempCanvasTopMargin + (TxtLiveWeatherTempUnits.ActualHeight / 2) + TxtLiveWeatherTempUnits.ActualHeight + 5);
                tempTextCanvas.Children.Add(TxtLiveWeatherTemp);
                tempTextCanvas.Children.Add(TxtLiveWeatherTempFloat);
                tempTextCanvas.Children.Add(TxtLiveWeatherTempUnits);

                Canvas.SetLeft(ImgLiveWeather, 0);
                Canvas.SetTop(ImgLiveWeather, 0);
                tempImageCanvas.Children.Add(ImgLiveWeather);

                Image imageWater = new Image()
                {
                    Width  = 20 * data.FontRatio,
                    Height = 20 * data.FontRatio,
                    Source = BitmapFactory.New(0, 0).FromContent("Images/lockscreen/water.png")
                };

                Image imageWind = new Image()
                {
                    Width  = 32 * data.FontRatio,
                    Height = 32 * data.FontRatio,
                    Source = BitmapFactory.New(0, 0).FromContent("Images/lockscreen/wind.png")
                };
                //습도
                TextBlock TxtLiveWeatherHumidity = new TextBlock()
                {
                    Text       = data.LiveWeather.Humidity.Value.Value + data.LiveWeather.Humidity.Value.Units,
                    FontSize   = data.FontSizeMedium * 1.1,
                    Foreground = data.ForegroundBrush,
                    FontWeight = data.FontWeight
                };
                //바람
                TextBlock TxtLiveWeatherWind = new TextBlock()
                {
                    Text       = data.LiveWeather.WindSpeed.Value + data.LiveWeather.WindSpeed.Units,
                    FontSize   = data.FontSizeMedium * 1.1,
                    Foreground = data.ForegroundBrush,
                    FontWeight = data.FontWeight
                };

                Canvas.SetLeft(imageWater, tempCanvasLeftMargin);
                Canvas.SetTop(imageWater, (imageWind.Height - imageWater.Height) / 2);

                Canvas.SetLeft(TxtLiveWeatherHumidity, tempCanvasLeftMargin + imageWater.Width + margin.Left / 2);
                Canvas.SetTop(TxtLiveWeatherHumidity, (imageWind.Height - TxtLiveWeatherHumidity.ActualHeight) / 2);

                Canvas.SetLeft(imageWind, tempCanvasLeftMargin + imageWater.Width + TxtLiveWeatherHumidity.ActualWidth + 20 + margin.Left);

                Canvas.SetLeft(TxtLiveWeatherWind, tempCanvasLeftMargin + imageWater.Width + TxtLiveWeatherHumidity.ActualWidth + 20 + imageWind.Width + margin.Left * 3 / 2);
                Canvas.SetTop(TxtLiveWeatherWind, (imageWind.Height - TxtLiveWeatherWind.ActualHeight) / 2);

                etcWeaterCanvas.Children.Add(imageWater);
                etcWeaterCanvas.Children.Add(TxtLiveWeatherHumidity);
                etcWeaterCanvas.Children.Add(imageWind);
                etcWeaterCanvas.Children.Add(TxtLiveWeatherWind);

                //주간일보
                if (data.Forecasts != null)
                {
                    Canvas                forecastCanvas   = new Canvas();
                    DayNameConverter      dayNameConverter = new DayNameConverter();
                    WeatherRangeConverter tempConverter    = new WeatherRangeConverter();

                    for (int i = 0; i < 3; i++)
                    {
                        Forecast forecast = data.Forecasts.Items[i];

                        Canvas dayCanvas = new Canvas();
                        dayCanvas.Width = etcWeaterCanvas.Width / 3;

                        TextBlock dayName = new TextBlock()
                        {
                            Text       = dayNameConverter.Convert(forecast.AltTitle, null, null, System.Globalization.CultureInfo.CurrentCulture) as string,
                            FontSize   = data.FontSizeMedium * 0.85,
                            Foreground = data.ForegroundBrush,
                            FontWeight = data.FontWeight
                        };
                        dayCanvas.Children.Add(dayName);
                        Canvas.SetLeft(dayName, (dayCanvas.Width - dayName.ActualWidth) / 2);
                        Canvas.SetTop(dayName, margin.Top * 2);

                        WeatherIconType iconType          = WeatherIconMap.Instance.WeatherIconType;
                        string          forecastPath      = string.Format(WeatherBug.ICON_LOCAL_PATH.Substring(1), iconType.ToString().ToLower(), "80x67", WeatherImageIconConverter.GetIamgetName(forecast.ImageIcon));
                        WriteableBitmap forecastWeatherWb = BitmapFactory.New(0, 0).FromContent(forecastPath);

                        Image forecastImage = new Image()
                        {
                            Source = forecastWeatherWb,
                            Width  = dayCanvas.Width * 0.7,
                            Height = dayCanvas.Width * 0.7 * 0.84 //0.84는 아이콘 이미지의 원본 비율임
                        };
                        dayCanvas.Children.Add(forecastImage);
                        Canvas.SetLeft(forecastImage, (dayCanvas.Width - forecastImage.Width) / 2);
                        Canvas.SetTop(forecastImage, dayName.ActualHeight + margin.Top + margin.Top / 2);

                        TextBlock tempRange = new TextBlock()
                        {
                            Text       = tempConverter.Convert(forecast.LowHigh, null, null, System.Globalization.CultureInfo.CurrentCulture) as string,
                            FontSize   = data.FontSizeMedium * 0.8,
                            Foreground = data.ForegroundBrush,
                            FontWeight = data.FontWeight
                        };
                        dayCanvas.Children.Add(tempRange);
                        Canvas.SetLeft(tempRange, (dayCanvas.Width - tempRange.ActualWidth) / 2);
                        Canvas.SetTop(tempRange, dayName.ActualHeight + forecastImage.Height + margin.Top + margin.Top / 2);

                        forecastCanvas.Children.Add(dayCanvas);
                        Canvas.SetLeft(dayCanvas, i * dayCanvas.Width);
                    }

                    weatherCanvas.Children.Add(forecastCanvas);
                    Canvas.SetTop(forecastCanvas, TxtLocation.ActualHeight + tempTextCanvas.Height + etcWeaterCanvas.Height);
                    Canvas.SetLeft(forecastCanvas, 0);
                }
            }
            else
            {
                TextBlock TxtNoWeather = new TextBlock()
                {
                    Width        = weatherCanvas.Width * 0.85,
                    FontSize     = data.FontSizeMedium,
                    Foreground   = data.ForegroundBrush,
                    TextWrapping = TextWrapping.Wrap,
                    Text         = AppResources.LockscreenNoWeatherData
                };

                weatherCanvas.Children.Add(TxtNoWeather);
                Canvas.SetTop(TxtNoWeather, (weatherCanvas.Height - TxtNoWeather.ActualHeight) / 2);
                Canvas.SetLeft(TxtNoWeather, (weatherCanvas.Width - TxtNoWeather.ActualWidth) / 2);
            }
            return(weatherCanvas);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 예약된 작업을 실행하는 에이전트입니다.
        /// </summary>
        /// <param name="task">
        /// 호출한 작업입니다.
        /// </param>
        /// <remarks>
        /// 이 메서드는 정기적 작업 또는 리소스를 많이 사용하는 작업이 호출될 때 호출됩니다.
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            bool isLiveTileTurn = true;

            scheduleSettings = MutexedIsoStorageFile.Read <ScheduleSettings>("ScheduleSettings", Constants.MUTEX_DATA);

            //스케쥴러는 30분마다 들어온다.
            //이번이 누구 차례인가를 생성해야 한다.
            //라이브타일과 락스크린은 각각의 인터벌이 있고, 그 인터벌은 어느 순간 중복될 수 있다.
            //중복되면 라이브타일에 우선권을 부여하여 실행하며, 락스크린은 그 이후 스케줄로 밀린다.
            //판별에 사용될 변수는 1.인터벌, 2.실행대상, 3.실행대상의 최종 실행시간
#if !DEBUG_AGENT
            {
                DateTime LastRunForLivetile, LastRunForLockscreen;
                IsolatedStorageSettings.ApplicationSettings.TryGetValue <DateTime>(Constants.LAST_RUN_LIVETILE, out LastRunForLivetile);
                IsolatedStorageSettings.ApplicationSettings.TryGetValue <DateTime>(Constants.LAST_RUN_LOCKSCREEN, out LastRunForLockscreen);
                bool useLockscreenRotator;
                IsolatedStorageSettings.ApplicationSettings.TryGetValue <bool>(Constants.LOCKSCREEN_USE_ROTATOR, out useLockscreenRotator);

                double lockscreenTerm = DateTime.Now.Subtract(LastRunForLockscreen).TotalMinutes - scheduleSettings.LockscreenUpdateInterval;
                //한번도 락스크린 스케쥴러를 실행한적이 없고 락스크린이 스케쥴에서 사용되지 않는 경우는 -1로 설정하여 락스크린으로 분기되지 않도록 처리
                if (LastRunForLockscreen.Year == 1 && LastRunForLockscreen.Month == 1 && LastRunForLockscreen.Day == 1 && !useLockscreenRotator)
                {
                    lockscreenTerm = -1;
                }

                if (DateTime.Now.Subtract(LastRunForLivetile).TotalMinutes < scheduleSettings.LivetileUpdateInterval &&
                    lockscreenTerm < 0)
                {
                    System.Diagnostics.Debug.WriteLine("Too soon, stopping.");
                    NotifyComplete();
                    return;
                }
                else if (lockscreenTerm >= 0)
                {
                    isLiveTileTurn = false;
                }
            }
#else
            isLiveTileTurn = false;
#endif
            if (isLiveTileTurn)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    System.Diagnostics.Debug.WriteLine("1 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    LivetileData data = new LivetileData()
                    {
                        DayList = VsCalendar.GetCalendarOfMonth(DateTime.Now, DateTime.Now, true, true),
                    };

                    try
                    {
                        System.Diagnostics.Debug.WriteLine("타일 전 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);

                        bool hasWeather  = ShellTile.ActiveTiles.Any(x => x.NavigationUri.ToString().Contains("weather"));
                        bool hasCalendar = ShellTile.ActiveTiles.Any(x => x.NavigationUri.ToString().Contains("calendar"));

                        if (hasWeather)
                        {
                            //1. 날씨 타일이 핀되어 있다.
                            WeatherCity city   = SettingHelper.Get(Constants.WEATHER_MAIN_CITY) as WeatherCity;
                            DisplayUnit unit   = (DisplayUnit)SettingHelper.Get(Constants.WEATHER_UNIT_TYPE);
                            WeatherBug weather = new WeatherBug();
                            weather.LiveWeatherCompletedLoad += (s, r, f) =>
                            {
                                //조회된 데이터를 셋팅(없으면 저장된 날씨를 사용함)
                                SetWeatherResult(data, r, f);
                                //달력 적용 또는 직접 렌더링
                                DelegateUpdateProcess(task, data, hasCalendar);
                            };
                            weather.RequestFailed += (s, r) =>
                            {
                                //데이터를 얻는데 실패 한 경우 네트워크가 연결되지 않았다면, 이전 저장된 데이터를 사용
                                if (!DeviceNetworkInformation.IsNetworkAvailable)
                                {
                                    data.LiveWeather = (LiveWeather)SettingHelper.Get(Constants.WEATHER_LIVE_RESULT);
                                    data.Forecasts   = (Forecasts)SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT);
                                }

                                //달력 적용 또는 직접 렌더링
                                DelegateUpdateProcess(task, data, hasCalendar);
                            };

                            if (city != null)
                            {
                                weather.LiveWeather(city, unit);
                            }
                            else
                            {
                                //달력 적용 또는 직접 렌더링
                                DelegateUpdateProcess(task, data, hasCalendar);
                            }
                        }
                        else
                        {
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e.Message);
                    }
                });
            }
            else
            {
                if (!LockScreenManager.IsProvidedByCurrentApplication)
                {
                    System.Diagnostics.Debug.WriteLine("잠금화면 제공앱이 아니므로 변경할수 없음.");
                    NotifyComplete();
                    return;
                }

                if (!IsolatedStorageSettings.ApplicationSettings.Contains(Constants.LOCKSCREEN_USE_ROTATOR) ||
                    !(bool)IsolatedStorageSettings.ApplicationSettings[Constants.LOCKSCREEN_USE_ROTATOR])
                {
                    System.Diagnostics.Debug.WriteLine("로테이터 사용안함.");
                    NotifyComplete();
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    System.Diagnostics.Debug.WriteLine("1 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    LockscreenData data = new LockscreenData(true)
                    {
                        DayList = VsCalendar.GetCalendarOfMonth(DateTime.Now, DateTime.Now, true, true),
                    };

                    bool hasWeather  = false;
                    bool hasCalendar = false;

                    LockscreenItemInfo[] items = data.Items;

                    for (int i = 0; i < items.Length; i++)
                    {
                        switch (items[i].LockscreenItem)
                        {
                        case LiveItems.Weather:
                        case LiveItems.NoForecast:
                            hasWeather = true;
                            break;

                        case LiveItems.Calendar:
                            hasCalendar = true;
                            break;
                        }
                    }

                    if (hasWeather)
                    {
                        WeatherBug weather = new WeatherBug();
                        WeatherCity city   = SettingHelper.Get(Constants.WEATHER_MAIN_CITY) as WeatherCity;
                        DisplayUnit unit   = (DisplayUnit)SettingHelper.Get(Constants.WEATHER_UNIT_TYPE);

                        weather.LiveWeatherCompletedLoad += (s, r, f) =>
                        {
                            //조회된 데이터를 셋팅(없으면 저장된 날씨를 사용함)
                            SetWeatherResult(data, r, f);
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        };

                        weather.RequestFailed += (s, r) =>
                        {
                            if (!DeviceNetworkInformation.IsNetworkAvailable)
                            {
                                data.LiveWeather = (LiveWeather)SettingHelper.Get(Constants.WEATHER_LIVE_RESULT);
                                data.Forecasts   = (Forecasts)SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT);
                            }
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        };

                        if (city != null)
                        {
                            weather.LiveWeather(city, unit);
                        }
                        else
                        {
                            //달력 적용 또는 직접 렌더링
                            DelegateUpdateProcess(task, data, hasCalendar);
                        }
                    }
                    else
                    {
                        //달력 적용 또는 직접 렌더링
                        DelegateUpdateProcess(task, data, hasCalendar);
                    }
                });
            }
        }
Ejemplo n.º 7
0
        private void SetLockscreenImage(ScheduledTask task, LockscreenData data)
        {
            try
            {
                bool isProvider = LockScreenManager.IsProvidedByCurrentApplication;

                if (isProvider)
                {
                    int itemCount = data.Items == null ? 0 : data.Items.Length;

                    //1. 이번에 변경할 파일을 알아야 한다. 그러기 위해서 먼저 현재 락스크린 파일명을 구한다.
                    Uri    lockscreenFileUri  = null;
                    string lockscreenFileName = null;

                    try
                    {
                        lockscreenFileUri = LockScreen.GetImageUri();
                    }
                    catch (Exception)
                    {
                        ShellToast toast = new ShellToast();
                        toast.Title   = AppResources.ApplicationTitle;
                        toast.Content = AppResources.MsgFailShortGetLockscreen;
                        toast.Show();
                        return;
                    }

                    if (lockscreenFileUri != null)
                    {
                        lockscreenFileName = lockscreenFileUri.ToString()
                                             .Replace(Constants.PREFIX_APP_DATA_FOLDER, string.Empty)
                                             .Replace(Constants.LOCKSCREEN_IMAGE_A_POSTFIX, Constants.LOCKSCREEN_IMAGE_POSTFIX)
                                             .Replace(Constants.LOCKSCREEN_IMAGE_B_POSTFIX, Constants.LOCKSCREEN_IMAGE_POSTFIX);
                    }

                    //2. 이번에 변경할 파일명을 구한다.
                    using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!string.IsNullOrEmpty(lockscreenFileName))
                        {
                            lockscreenFileName = lockscreenFileName.Replace(Constants.LOCKSCREEN_IMAGE_POSTFIX, Constants.LOCKSCREEN_IMAGE_READY_POSTFIX);
                        }

                        var imgNames = from element in isoStore.GetFileNames()
                                       where element.Contains(Constants.LOCKSCREEN_IMAGE_READY_POSTFIX) &&
                                       element.CompareTo(lockscreenFileName) > 0
                                       orderby element ascending
                                       select element;

                        //이번에 업데이트 할 이미지 이름을 임시 저장
                        lockscreenFileName = imgNames.Any() ? imgNames.First() :
                                             isoStore.GetFileNames(string.Format("*{0}", Constants.LOCKSCREEN_IMAGE_READY_POSTFIX))[0];

                        using (IsolatedStorageFileStream sourceStream = isoStore.OpenFile(lockscreenFileName, FileMode.Open, FileAccess.Read))
                        {
                            data.BackgroundBitmap = BitmapFactory.New(0, 0).FromStream(sourceStream);
                        }

                        //3. 표시할 아이템들과 이미지를 합성한다. (이미지 리사이징 포함)
                        LockscreenHelper.RenderLayoutToBitmap(data);

                        GC.Collect();
                        System.Threading.Thread.Sleep(1500);
                        System.Diagnostics.Debug.WriteLine("이미지 생성 직후" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);

                        //4. 새로운 이름으로 저장하기 위해 전환 논리를 이용하여 새로운 이름을 구한다.
                        if (lockscreenFileUri != null && lockscreenFileUri.ToString().EndsWith(Constants.LOCKSCREEN_IMAGE_A_POSTFIX))
                        {
                            lockscreenFileName = lockscreenFileName.Replace(Constants.LOCKSCREEN_IMAGE_READY_POSTFIX, Constants.LOCKSCREEN_IMAGE_B_POSTFIX);
                        }
                        else
                        {
                            lockscreenFileName = lockscreenFileName.Replace(Constants.LOCKSCREEN_IMAGE_READY_POSTFIX, Constants.LOCKSCREEN_IMAGE_A_POSTFIX);
                        }

                        //5. 새로운 이름으로 이미지를 저장
                        using (IsolatedStorageFileStream targetStream = isoStore.OpenFile(lockscreenFileName, FileMode.Create, FileAccess.Write))
                        {
                            data.BackgroundBitmap.SaveJpeg(targetStream, data.BackgroundBitmap.PixelWidth, data.BackgroundBitmap.PixelHeight, 0, 100);
                            //using (MemoryStream ms = new MemoryStream())
                            //{
                            //    data.BackgroundBitmap.SaveJpeg(ms, data.BackgroundBitmap.PixelWidth, data.BackgroundBitmap.PixelHeight, 0, 100);
                            //    System.Diagnostics.Debug.WriteLine("{0}x{1}", data.BackgroundBitmap.PixelWidth, data.BackgroundBitmap.PixelHeight);
                            //    byte[] readBuffer = new byte[4096];
                            //    int bytesRead = -1;
                            //    ms.Position = 0;
                            //    targetStream.Position = 0;

                            //    while ((bytesRead = ms.Read(readBuffer, 0, readBuffer.Length)) > 0)
                            //    {
                            //        targetStream.Write(readBuffer, 0, bytesRead);
                            //    }
                            //}
                        }

                        //6. 새로운 이미지로 락스크린 업데이트
                        LockScreen.SetImageUri(new Uri(string.Format("{0}{1}", Constants.PREFIX_APP_DATA_FOLDER, lockscreenFileName), UriKind.Absolute));
                        Uri newLockscreenFileUri = LockScreen.GetImageUri();

                        //7.변경이 정상적으로 이루어진 경우 기존 파일 삭제
                        if (newLockscreenFileUri.ToString() != lockscreenFileUri.ToString())
                        {
                            if (lockscreenFileUri.ToString().Contains(Constants.PREFIX_APP_DATA_FOLDER))
                            {
                                lockscreenFileName = lockscreenFileUri.ToString().Replace(Constants.PREFIX_APP_DATA_FOLDER, string.Empty);
                                if (isoStore.FileExists(lockscreenFileName))
                                {
                                    isoStore.DeleteFile(lockscreenFileName);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LoggingError("error case 3 : \n" + e.StackTrace);
            }

            // If debugging is enabled, launch the agent again in one minute.
#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
            System.Diagnostics.Debug.WriteLine(Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);

            /*
             * ShellToast toast = new ShellToast();
             * toast.Title = AppResources.ApplicationTitle;
             * toast.Content = AppResources.MsgSuccessChangeLockscreen;
             * toast.Show();
             */
#else
            IsolatedStorageSettings.ApplicationSettings[Constants.LAST_RUN_LOCKSCREEN] = DateTime.Now;
            IsolatedStorageSettings.ApplicationSettings.Save();
#endif
        }
Ejemplo n.º 8
0
        private async Task SelectLockscreen(PhonePicture picture)
        {
            await Task.Run(async() =>
            {
                if (picture != null)
                {
                    try
                    {
                        var isProvider = LockScreenManager.IsProvidedByCurrentApplication;
                        var op         = isProvider ? LockScreenRequestResult.Granted : LockScreenRequestResult.Denied;

                        if (!isProvider)
                        {
                            // If you're not the provider, this call will prompt the user for permission.
                            // Calling RequestAccessAsync from a background agent is not allowed.
                            op = await LockScreenManager.RequestAccessAsync();
                        }

                        if (op == LockScreenRequestResult.Granted)
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                //로딩 패널 띄움
                                ShowLoadingPanel(AppResources.MsgApplyingLockscreen);

                                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    using (IsolatedStorageFileStream sourceStream = isoStore.OpenFile(picture.Name, FileMode.Open, FileAccess.Read))
                                    {
                                        WriteableBitmap wb = BitmapFactory.New(0, 0).FromStream(sourceStream);
                                        Size rSize         = ResolutionHelper.CurrentResolution;
                                        MemoryStream ms    = null;

                                        LockscreenData data = new LockscreenData(false)
                                        {
                                            DayList          = VsCalendar.GetCalendarOfMonth(DateTime.Now, DateTime.Now, true, true),
                                            LiveWeather      = SettingHelper.Get(Constants.WEATHER_LIVE_RESULT) as LiveWeather,
                                            Forecasts        = SettingHelper.Get(Constants.WEATHER_FORECAST_RESULT) as Forecasts,
                                            BackgroundBitmap = wb.Crop(new Rect((wb.PixelWidth - rSize.Width) / 2, (wb.PixelHeight - rSize.Height) / 2, rSize.Width, rSize.Height))
                                        };

                                        //편집이 필요한 이미지라면 스트림 생성 및 이미지 복사
                                        if (picture.Warnning != null)
                                        {
                                            //메모리 스트림 생성 (close 처리는 SetLockscreen에서 한다.)
                                            ms = new MemoryStream();
                                            //잘라내기가 된 이미지를 스트림에 저장
                                            data.BackgroundBitmap.SaveJpeg(ms, data.BackgroundBitmap.PixelWidth, data.BackgroundBitmap.PixelHeight, 0, 100);
                                        }

                                        if ((bool)SettingHelper.Get(Constants.CALENDAR_SHOW_APPOINTMENT))
                                        {
                                            Appointments appointments     = new Appointments();
                                            appointments.SearchCompleted += (s, se) =>
                                            {
                                                VsCalendar.MergeCalendar(data.DayList, se.Results);
                                                LockscreenHelper.RenderLayoutToBitmap(data);
                                                SetLockscreen(picture, data.BackgroundBitmap, ms);
                                            };
                                            appointments.SearchAsync(data.DayList[7].DateTime, data.DayList[data.DayList.Count - 1].DateTime, null);
                                        }
                                        else
                                        {
                                            LockscreenHelper.RenderLayoutToBitmap(data);
                                            SetLockscreen(picture, data.BackgroundBitmap, ms);
                                        }
                                    }
                                }
                            });
                        }
                    }
                    catch (System.Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }
            });
        }