コード例 #1
0
        public PersonViewModel(int personId, PhoneApplicationPage page)
            : base(page)
        {
            this.Person = Ctx.Persons.SingleOrDefault(x => x.Id == personId);

            if (!String.IsNullOrEmpty(this.Person.FileName))
                this.Person.Image = Storage.ReadImageFromIsolatedStorageToWriteableBitmap(string.Format("ProfilePicture\\{0}", this.Person.FileName)); //GeneralMethods.ResizeImageToThumbnail(Storage.ReadImageFromIsolatedStorageAsStream(this.Person.FileName), 150);
            else
                this.Person.Image = Storage.ReadImageFromContent("./Images/ChoosePhoto.jpg");

            foreach (Date date in this.Person.Dates)
                ChronoGrouping.MarkDate(date);

            this.GroupedDateList =
            (from obj in this.Person.Dates
             orderby (int)obj.ChronoGroupKey ascending, obj.DateOfMeeting ascending
             group obj by obj.ChronoGroupKey.ToDescription() into grouped
             select new Grouping<string, Date>(grouped)).ToList();

            Interests = (from i in Ctx.Interests select new { Description = i.Description, FontSize = i.Weighting * 15, Interest = i }).AsEnumerable()
             .Select(t => new TagCloudItem()
             {
                 Description = t.Description,
                 FontSize = t.FontSize,
                 Margin = new System.Windows.Thickness { Top = GetRandomInt(1, 20, t.FontSize / 15), Left = 10, Right = 10 },
                 Interest = t.Interest
             }).ToList();
        }
コード例 #2
0
        public static void RestoreState(PhoneApplicationPage page)
        {
            foreach (PropertyInfo tombstoneProperty in FindTombstoneProperties(page.DataContext))
            {
                string key = "ViewModel." + tombstoneProperty.Name;

                if (page.State.ContainsKey(key))
                {
                    tombstoneProperty.SetValue(page.DataContext, page.State[key], null);
                }
            }

            if (page.State.ContainsKey("FocusedControl.Name"))
            {
                string focusedControlName = (string)page.State["FocusedControl.Name"];
                Control focusedControl = (Control)page.FindName(focusedControlName);

                if (focusedControl != null)
                {
                    page.Loaded += delegate
                    {
                        focusedControl.Focus();
                    };
                }
            }
        }
コード例 #3
0
 private void LanguageControlLoaded(object sender, RoutedEventArgs e)
 {
     DependencyObject parent = Parent;
     while (!(parent is PhoneApplicationPage))
         parent = ((FrameworkElement)parent).Parent;
     parentPage = ((PhoneApplicationPage)parent);
 }
コード例 #4
0
        public CEDateViewModel(PhoneApplicationPage page, int? dateId = null)
            : base(page)
        {
            DateRep = new Repository<Date>(this.Ctx);
            VenueRep = new Repository<Venue>(this.Ctx);

            this.IsEditing = dateId.HasValue;

            if (this.IsEditing)
            {
                this.TheDate = Ctx.Dates.Where(x => x.Id == dateId).SingleOrDefault();
                this.ThePerson = this.TheDate.Person;
                this.TheVenue = this.TheDate.Venue;

                this.Date = DateTime.Parse(this.TheDate.DateOfMeeting.ToShortDateString());
                this.Time = this.Date + this.TheDate.DateOfMeeting.TimeOfDay;
            }
            else
            {
                this.TheDate = new Date();
                this.TheVenue = new Venue();

                this.Date = DateTime.Parse(DateTime.Now.ToShortDateString());
                this.Time = this.Date + DateTime.Now.TimeOfDay;
            }

            this.People = new List<CustomListBoxItem<Person>>();
            this.People.Add(new CustomListBoxItem<Person>() { Key = -1, Value = "Choose ...", Item = null, ShowItem = Visibility.Collapsed });
            this.People.AddRange((from p in Ctx.Persons orderby p.FirstName ascending select new CustomListBoxItem<Person>() { Key = p.Id, Value = p.FullName, Item = p, ShowItem = Visibility.Visible }).ToList());

            // the first one is the Choose item
            foreach (CustomListBoxItem<Person> person in this.People.Skip(1))
                person.Image = Storage.ReadImageFromIsolatedStorageToWriteableBitmap(string.Format("ProfileThumbnail\\{0}", person.Item.FileName));
        }
コード例 #5
0
ファイル: RhodesApp.cs プロジェクト: artemk/rhodes
        public void Init(WebBrowser browser, PhoneApplicationPage appMainPage)
        {
            initAppUrls();
            RhoLogger.InitRhoLog();
            LOG.INFO("Init");

            CRhoFile.recursiveCreateDir(CFilePath.join(getBlobsDirPath()," "));

            m_webBrowser = browser;
            m_appMainPage = appMainPage;
            m_appMainPage.ApplicationBar = null;
            m_httpServer = new CHttpServer(CFilePath.join(getRhoRootPath(), "apps"));
            CRhoResourceMap.deployContent();
            RhoRuby.Init(m_webBrowser);

            DBAdapter.initAttrManager();

            LOG.INFO("Starting sync engine...");
            SyncThread sync = null;
            try{
	        	sync = SyncThread.Create();
	        	
	        }catch(Exception exc){
	        	LOG.ERROR("Create sync failed.", exc);
	        }
	        if (sync != null) {
	        	//sync.setStatusListener(this);
	        }
	        
	        RhoRuby.InitApp();
	        RhoRuby.call_config_conflicts();
            RHOCONF().conflictsResolved();
        }
コード例 #6
0
ファイル: SystemTrayHelper.cs プロジェクト: JulianMH/DoIt
        internal static void Hide(PhoneApplicationPage page)
        {
            SystemTray.SetIsVisible(page, false);
            SystemTray.SetOpacity(page, 1);
            SystemTray.SetProgressIndicator(page, null);

        }
コード例 #7
0
        /// <summary>
        /// Determines whether [has some thing to do before go to main page].
        /// </summary>
        /// <returns>
        ///   <c>true</c> if [has some thing to do before go to main page]; otherwise, <c>false</c>.
        /// </returns>
        public static bool HasSomeThingToDoBeforeGoToMainPage(PhoneApplicationPage fromPage)
        {
            try
            {
                if (HasSomeThingToDo && App.SeniorVersion == "1530.1222")
                {
                    fromPage.BusyForWork(AppResources.UpgratingUnderProcess);

                    IsolatedAppSetingsHelper.ShowTipsByVerion("DoSomethingOnce", () =>
                    {
                        ViewModelLocator.ScheduleManagerViewModel.SetupPlanningFirstTime();
                        Repayment.UpdateTableStructureAtV1_9_8(ViewModelLocator.AccountBookDataContext, ViewModels.BorrowLeanManager.BorrowLeanViewModel.EnsureStatus);
                    });

                    fromPage.WorkDone();
                }

            }
            catch (Exception)
            {

            }

            return HasSomeThingToDo;
        }
コード例 #8
0
ファイル: SpinnerDialog.cs プロジェクト: demoode/app5
        public void show(string options)
        {
            string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
            string title = args[0];
            string message = args[1];

            if (message == null)
            {
                message = title;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {

                if (progressIndicator == null)
                {
                    progressIndicator = new ProgressIndicator() { IsIndeterminate = true };
                }
                progressIndicator.Text = message;
                progressIndicator.IsVisible = true;

                if (page == null)
                {
                    page = (Application.Current.RootVisual as PhoneApplicationFrame).Content as PhoneApplicationPage;
                }

                SystemTray.SetProgressIndicator(page, progressIndicator);

            });
        }
コード例 #9
0
 private void Insert()
 {
     // Make an assumption that this is within a phone application that is developed "normally"
     var frame = Application.Current.RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame;
     _page = frame.Content as PhoneApplicationPage;
     _page.BackKeyPress += Page_BackKeyPress;
     // assume the child is a Grid, span all of the rows
     var grid = System.Windows.Media.VisualTreeHelper.GetChild(_page, 0) as Grid;
     if (grid.RowDefinitions.Count > 0)
     {
         Grid.SetRowSpan(this, grid.RowDefinitions.Count);
     }
     grid.Children.Add(this);
     // Create a transition like the regular MessageBox
     SwivelTransition transitionIn = new SwivelTransition();
     transitionIn.Mode = SwivelTransitionMode.BackwardIn;
     // Transition only the MessagePanel
     ITransition transition = transitionIn.GetTransition(MessagePanel);
     transition.Completed += (s, e) => transition.Stop();
     transition.Begin();
     if (_page.ApplicationBar != null)
     {
         // Hide the app bar so they cannot open more message boxes
         _page.ApplicationBar.IsVisible = false;
     }
 }
        public void TriggerInvokesCallbacksAfterProcessingReceivedNotifications()
        {
            string notificationReceived = "Foo";
            var callbackInvoked = 0;
            var callbackCallsWhenNotificationIsHandled = 0;
            var page = new PhoneApplicationPage();
            var myNotificationAwareObject = new MyNotificationAwareClass();
            var binding = new Binding("InteractionRequest") { Source = myNotificationAwareObject, Mode = BindingMode.OneWay };
            var trigger = new MyTriggerClass
            {
                RequestBinding = binding,
                NotifyAction = c => { notificationReceived = c.Title; callbackCallsWhenNotificationIsHandled = callbackInvoked; }
            };
            Interaction.GetBehaviors(page).Add(trigger);
            var initialState = notificationReceived;
            myNotificationAwareObject.InteractionRequest.Raise(new Notification { Title = "Bar" }, n => callbackInvoked++);
            var barState = notificationReceived;
            myNotificationAwareObject.InteractionRequest.Raise(new Notification { Title = "Finish" }, n => callbackInvoked++);
            var finalState = notificationReceived;

            Assert.AreEqual("Foo", initialState);
            Assert.AreEqual("Bar", barState);
            Assert.AreEqual("Finish", finalState);
            Assert.AreEqual(2, callbackInvoked);
            Assert.AreEqual(1, callbackCallsWhenNotificationIsHandled);
        }
コード例 #11
0
        public VenueSearchViewModel(PhoneApplicationPage page)
            : base(page)
        {
            this.Page = page;

            ViewOnMapCommand = new RelayCommand(DoViewOnMap, CanViewOnMap);
        }
コード例 #12
0
 public PopupCotainer(PhoneApplicationPage basePage)
 {
     InitializeComponent();
     this.Loaded += new RoutedEventHandler(PopupCotainer_Loaded);
     _BasePage = basePage;
     _BasePage.BackKeyPress += BasePage_BackKeyPress;
 }
コード例 #13
0
ファイル: OrientationHelper.cs プロジェクト: 5nophilwu/S1Nyan
        public void UpdateOrientation(PhoneApplicationPage page)
        {
            if (page == null) return;

            //BUG: Auto Rotate >> Landscape >> Disable Auto Rotate >> Still LandScape
            page.SupportedOrientations = Views.SettingView.IsAutoRotate ? SupportedPageOrientation.PortraitOrLandscape : SupportedPageOrientation.Portrait;
        }
コード例 #14
0
ファイル: BusyOverlay.cs プロジェクト: karbazol/FBReaderCS
        public BusyOverlay(bool closable, string content = null, bool hideAppBar = true)
        {
            _closable = closable;
            _page = (PhoneApplicationPage)((PhoneApplicationFrame)Application.Current.RootVisual).Content;
            _hideAppBar = hideAppBar;

            _popup = new RadWindow()
            {
                IsAnimationEnabled = false,
                IsClosedOnOutsideTap = false,
                Content = _border = new Border()
                {
                    Opacity = 0.5,
                    Width = _page.ActualWidth,
                    Height = _page.ActualHeight,
                    Background = new SolidColorBrush(_overlayBackgroundColor),
                    Child = new RadBusyIndicator()
                    {
                        IsRunning = true,
                        AnimationStyle = AnimationStyle.AnimationStyle9,
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        Content = content
                    }
                }
            };

        }
コード例 #15
0
ファイル: SignInPage.cs プロジェクト: stevehansen/vidyano_v1
        protected internal SignInPage(PhoneApplicationPage page)
            : base(page)
        {
            SignIn = new SimpleActionCommand(_ => SelectServiceProvider.Execute(ClientData.VidyanoServiceProvider));
            RetryConnect = new SimpleActionCommand(async _ =>
            {
                if (State == SignInPageState.NoInternet)
                    await Connect();
            });
            SelectServiceProvider = new SimpleActionCommand(provider =>
            {
                selectedProvider = (ServiceProvider)provider;
                promptServiceProviderWaiter.Set();
            });

            Page.BackKeyPress += (_, e) =>
            {
                promptServiceProviderWaiter.Set();
                if (oauthBrowserWaiter != null)
                    oauthBrowserWaiter.Set();

                if (ClientData != null && !String.IsNullOrEmpty(ClientData.DefaultUserName))
                    e.Cancel = true;
            };
        }
コード例 #16
0
 public ApplicationBarHelper(PhoneApplicationPage targetPage)
 {
     this.textBoxs = new List<TextBox>();
     this.pageAttached = targetPage;
     this.OriginalBar = pageAttached.ApplicationBar;
     InitializeEditingBar();
 }
        public void CommandBehaviorMonitorsCanExecuteChangedToUpdateEnabledWhenCanExecuteChangedIsRaised()
        {
            var page = new PhoneApplicationPage();
            var bar = new ApplicationBar();
            var button = new ApplicationBarIconButton(new Uri("/foo.png", UriKind.Relative));
            button.Text = "Foo";
            bar.Buttons.Add(button);
            page.ApplicationBar = bar;
            var command = new ApplicationBarButtonCommand();
            command.ButtonText = "Foo";
            var bindingSource = new MyCommandHolder();
            command.CommandBinding = bindingSource.Command;
            Interaction.GetBehaviors(page).Add(command);

            bindingSource.CanExecute = true;

            var initialState = button.IsEnabled;

            bindingSource.CanExecute = false;

            var finalState = button.IsEnabled;

            Assert.IsTrue(initialState);
            Assert.IsFalse(finalState);
        }
コード例 #18
0
ファイル: CommonUtils.cs プロジェクト: uvbs/MyProjects
 public static void ClearApplicationBar(PhoneApplicationPage page)
 {
     while (page.ApplicationBar.Buttons.Count > 0)
     {
         page.ApplicationBar.Buttons.RemoveAt(0);
     }
 }
コード例 #19
0
        public Hit(PhoneApplicationPage page)
        {
            this.Title = page.Title;
            this.Path = page.GetType().Name;

            Events = new List<Event>();
        }
コード例 #20
0
        public EditPersonViewModel(PhoneApplicationPage page)
            : base(page)
        {
            //this.Countries = new ObservableCollection<CustomListBoxItem<Country>>();

            IsolatedDatabaseCall isolatedCall = new IsolatedDatabaseCall();
            isolatedCall.CallCompleted += isolatedCall_CallCompleted;

            Func<bool> finished = () =>
            {
                this.Person = (from p in Ctx.Persons where p.Id == ((Person)AppContext.Instance.PassedData).Id select p).SingleOrDefault();

                if (this.Person != null)
                    return true;
                else
                    return false;
            };

            isolatedCall.FetchData(finished);

            //this.Person = person;

            this.DateOfBirth = this.Person.DateOfBirth;

            //this.Countries.Add(new CustomListBoxItem<Country>() { Key = -1, Value = "Choose ...", Item = null, ShowItem = Visibility.Collapsed });
        }
コード例 #21
0
        public static void Go(PhoneApplicationPage fromPage, Category category)
        {
            SelectionHandler = new PageActionHandler<Category>();
            SelectionHandler.AfterSelected = delegate(Category item)
            {
                if ((item != null) && (item.Id != category.ParentCategoryId))
                {
                    if (category.ParentCategory != null)
                    {
                        category.ParentCategory.Childrens.Remove(category);
                    }

                    category.ParentCategory = item;
                    if (item.Childrens.Count(p => p.Name == category.Name) == 0)
                    {
                        // reset order.
                        category.Order = item.Childrens
                            .Select(p => (int)p.Order).ToList().Max(p => p) + 1;

                        item.Childrens.Add(category);
                    }

                    ((System.Collections.Generic.IEnumerable<AccountItem>)category.AccountItems).ForEach<AccountItem>(p =>
                    {
                        p.RaisePropertyChangd("NameInfo");
                    });
                    ViewModelLocator.CategoryViewModel.Update(category);
                }
            };
            fromPage.NavigateTo("/pages/CategoryManager/SelectParentCategoryPage.xaml?id={0}&currentName={1}&type={2}&childName={3}", new object[] { category.ParentCategoryId, category.ParentCategory == null ? "N/A" : category.ParentCategory.Name, category.CategoryType, category.Name });
        }
コード例 #22
0
 public QCodeKitAdUC(PhoneApplicationPage parentPage = null)
 {
     _curParentPage = parentPage;
     InitializeComponent();
     this.Loaded += QCodeKitAdUC_Loaded;
     this.Unloaded += QCodeKitAdUC_Unloaded;
 }
コード例 #23
0
ファイル: PermissionChecker.cs プロジェクト: cpmcgrath/Bankr
        void Hide(PhoneApplicationPage instance)
        {
            instance.Opacity = 0;
            instance.BackKeyPress += HidePopup;

            if (instance.ApplicationBar != null)
                instance.ApplicationBar.IsVisible = false;
        }
コード例 #24
0
 public BorrowLoanInfoViewer(PhoneApplicationPage page)
 {
     this.InitializeComponent();
     base.DataContext = this;
     this.associatedPage = page;
     this.borrowLoanViewModel = ViewModelLocator.BorrowLeanViewModel;
     this.DetailsPivot.Header = AppResources.Details.ToLowerInvariant().Trim();
 }
コード例 #25
0
ファイル: OrientationHelper.cs プロジェクト: lite/yebob_wp
        public OrientationHelper(WebBrowser yebobBrowser, PhoneApplicationPage gapPage)
        {
            this.yebobBrowser = yebobBrowser;
            page = gapPage;

            page.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(page_OrientationChanged);
            yebobBrowser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(yebobBrowser_LoadCompleted);
        }
コード例 #26
0
        // private PageOrientation CurrentOrientation = PageOrientation.PortraitUp;
        //private PageOrientation[] SupportedOrientations; // TODO:
        public OrientationHelper(WebBrowser browser, PhoneApplicationPage page)
        {
            CordovaBrowser = browser;
            Page = page;

            Page.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(page_OrientationChanged);
            CordovaBrowser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);
        }
コード例 #27
0
        public FavouritePeopleViewModel(PhoneApplicationPage page)
            : base(page)
        {
            this.People = new ObservableCollection<Person>((from p in Ctx.Persons where p.IsFavourite == true orderby p.FirstName ascending select p).ToList());

            foreach (Person person in this.People)
                person.Image = Storage.ReadImageFromIsolatedStorageToWriteableBitmap(string.Format("ProfileThumbnail\\{0}", person.FileName));
        }
コード例 #28
0
        public AddNoteViewModel(int dateId, PhoneApplicationPage page)
            : base(page)
        {
            this.Note = new Note();

            Date date = Ctx.Dates.Single(d => d.Id == dateId);
            date.Notes.Add(this.Note);
        }
コード例 #29
0
 void SetApplicationBarState(PhoneApplicationPage page, bool isEnabled)
 {
     foreach (var button in page.ApplicationBar.Buttons)
     {
         (button as ApplicationBarIconButton).IsEnabled = isEnabled;
     }
     page.ApplicationBar.IsMenuEnabled = isEnabled;
 }
コード例 #30
0
 internal override void SwapAppBar(PhoneApplicationPage _parent)
 {
     if (_parent.ApplicationBar != null && _parent.ApplicationBar.IsVisible)
     {
         _appBar = _parent.ApplicationBar;
         _appBar.IsVisible = false;
     }
 }
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        public void startPlaying(string filePath)
        {
            if (this.recorder != null)
            {
                InvokeCallback(MediaError, MediaErrorRecordModeSet, false);
                //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet),false);
                return;
            }


            if (this.player == null || this.player.Source.AbsolutePath.LastIndexOf(filePath) < 0)
            {
                try
                {
                    // this.player is a MediaElement, it must be added to the visual tree in order to play
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                this.player = grid.FindName("playerMediaElement") as MediaElement;
                                if (this.player == null) // still null ?
                                {
                                    this.player      = new MediaElement();
                                    this.player.Name = "playerMediaElement";
                                    grid.Children.Add(this.player);
                                    this.player.Visibility = Visibility.Visible;
                                }
                                if (this.player.CurrentState == System.Windows.Media.MediaElementState.Playing)
                                {
                                    this.player.Stop(); // stop it!
                                }

                                this.player.Source       = null; // Garbage collect it.
                                this.player.MediaOpened += MediaOpened;
                                this.player.MediaEnded  += MediaEnded;
                                this.player.MediaFailed += MediaFailed;
                            }
                        }
                    }

                    this.audioFile = filePath;

                    Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        this.player.Source = uri;
                    }
                    else
                    {
                        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (!isoFile.FileExists(filePath))
                            {
                                // try to unpack it from the dll into isolated storage
                                StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
                                if (fileResourceStreamInfo != null)
                                {
                                    using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
                                    {
                                        byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);

                                        string[] dirParts = filePath.Split('/');
                                        string   dirName  = "";
                                        for (int n = 0; n < dirParts.Length - 1; n++)
                                        {
                                            dirName += dirParts[n] + "/";
                                        }
                                        if (!isoFile.DirectoryExists(dirName))
                                        {
                                            isoFile.CreateDirectory(dirName);
                                        }

                                        using (IsolatedStorageFileStream outFile = isoFile.OpenFile(filePath, FileMode.Create))
                                        {
                                            using (BinaryWriter writer = new BinaryWriter(outFile))
                                            {
                                                writer.Write(data);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isoFile.FileExists(filePath))
                            {
                                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile))
                                {
                                    this.player.SetSource(stream);
                                }
                            }
                            else
                            {
                                InvokeCallback(MediaError, MediaErrorPlayModeSet, false);
                                //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, 1), false);
                                return;
                            }
                        }
                    }
                    this.SetState(PlayerState_Starting);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in AudioPlayer::startPlaying : " + e.Message);
                    InvokeCallback(MediaError, MediaErrorStartingPlayback, false);
                    //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback),false);
                }
            }
            else
            {
                if (this.state != PlayerState_Running)
                {
                    this.player.Play();
                    this.SetState(PlayerState_Running);
                }
                else
                {
                    InvokeCallback(MediaError, MediaErrorResumeState, false);
                    //this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState),false);
                }
            }
        }
コード例 #32
0
        /// <summary>
        /// Show the settings pane as a popup
        /// </summary>
        /// <param name="page">the current phone application page</param>
        /// <param name="parent">the parent panel on the page (typically the
        /// LayoutRoot Grid)</param>
        /// <param name="pauseVideo">true to pause the video when the popup is
        /// shown and play it when the popup is hidden.</param>
        public void ShowSettingsPopup(PhoneApplicationPage page, Panel parent, bool pauseVideo = false)
        {
            if (this.popup != null && this.popup.IsOpen)
            {
                return;
            }

            this.pauseVideo = pauseVideo;

            bool isEnabled = false;

            object value;

            if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(CaptionSettingsPage.OverrideDefaultKey, out value))
            {
                isEnabled = (bool)value;
            }

            if (this.Settings == null)
            {
                this.Activate();

                this.Settings.PropertyChanged += this.Settings_PropertyChanged;
            }

            if (!isEnabled)
            {
                this.Settings.BackgroundColor = null;
                this.Settings.FontColor       = null;
                this.Settings.FontFamily      = Model.FontFamily.Default;
                this.Settings.FontSize        = null;
                this.Settings.FontStyle       = Model.FontStyle.Default;
                this.Settings.WindowColor     = null;
            }

            Border border = null;

            if (this.popup == null)
            {
                page.BackKeyPress += this.OnBackKeyPress;

                this.control = new CaptionSettingsControl
                {
                    ApplyCaptionSettings = this.ApplyCaptionSettings,
                    Settings             = this.Settings,
                    Page               = page,
                    Width              = page.ActualWidth,
                    Height             = page.ActualHeight,
                    Style              = this.CaptionSettingsControlStyle,
                    IsOverrideDefaults = isEnabled
                };

                this.popup = new Popup
                {
                    Child = new Border
                    {
                        Child = this.control
                    }
                };

                this.popup.Opened += delegate(object sender, EventArgs e)
                {
                    if (this.MediaPlayer != null)
                    {
                        this.MediaPlayer.IsEnabled = false;

                        if (this.pauseVideo)
                        {
                            if (this.MediaPlayer.CurrentState == MediaElementState.Playing)
                            {
                                this.MediaPlayer.Pause();
                            }
                        }
                    }

                    this.IsPopupOpen = true;
                };

                this.popup.Closed += delegate(object sender, EventArgs e)
                {
                    if (this.MediaPlayer != null)
                    {
                        this.MediaPlayer.IsEnabled = true;

                        if (this.pauseVideo)
                        {
                            if (this.MediaPlayer.CurrentState == MediaElementState.Paused)
                            {
                                this.MediaPlayer.Play();
                            }
                        }
                    }

                    this.IsPopupOpen = false;

                    if (this.PopupClosed != null)
                    {
                        this.PopupClosed(this, e);
                    }
                };

                if (parent != null)
                {
                    parent.Children.Add(this.popup);
                }

                border = this.popup.Child as Border;
            }
            else
            {
                border = this.popup.Child as Border;

                var control = border.Child as CaptionSettingsControl;

                control.Page  = page;
                control.Style = this.CaptionSettingsControlStyle;
                control.IsOverrideDefaults = isEnabled;
            }

            if (this.MediaPlayer == null)
            {
                border.Background = new SolidColorBrush(Colors.Black);
            }
            else
            {
                border.Background = null;
            }

            this.popup.IsOpen = true;
        }
コード例 #33
0
        // Display an inderminate progress indicator
        public void showWebPage(string options)
        {
            BrowserOptions opts = JSON.JsonHelper.Deserialize <BrowserOptions>(options);

            Uri loc = new Uri(opts.url);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (browser != null)
                {
                    browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                    browser.Navigate(loc);
                }
                else
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                browser = new WebBrowser();
                                browser.Navigate(loc);

                                browser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);

                                browser.Navigating          += new EventHandler <NavigatingEventArgs>(browser_Navigating);
                                browser.NavigationFailed    += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
                                browser.Navigated           += new EventHandler <System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
                                browser.IsScriptEnabled      = true;
                                browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                                grid.Children.Add(browser);
                            }

                            ApplicationBar bar  = new ApplicationBar();
                            bar.BackgroundColor = Colors.Black;
                            bar.IsMenuEnabled   = false;

                            backButton           = new ApplicationBarIconButton();
                            backButton.Text      = "Back";
                            backButton.IconUri   = new Uri("/Images/appbar.back.rest.png", UriKind.Relative);
                            backButton.Click    += new EventHandler(backButton_Click);
                            backButton.IsEnabled = false;
                            bar.Buttons.Add(backButton);


                            fwdButton           = new ApplicationBarIconButton();
                            fwdButton.Text      = "Forward";
                            fwdButton.IconUri   = new Uri("/Images/appbar.next.rest.png", UriKind.Relative);
                            fwdButton.Click    += new EventHandler(fwdButton_Click);
                            fwdButton.IsEnabled = false;
                            bar.Buttons.Add(fwdButton);

                            ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
                            closeBtn.Text    = "Close";
                            closeBtn.IconUri = new Uri("/Images/appbar.close.rest.png", UriKind.Relative);
                            closeBtn.Click  += new EventHandler(closeBtn_Click);
                            bar.Buttons.Add(closeBtn);

                            page.ApplicationBar = bar;
                        }
                    }
                }
            });
        }
コード例 #34
0
        /// Helper method to copy all relevant cookies from the WebBrowser control into a header on
        /// the HttpWebRequest
        /// </summary>
        /// <param name="browser">The source browser to copy the cookies from</param>
        /// <param name="webRequest">The destination HttpWebRequest to add the cookie header to</param>
        /// <returns>Nothing</returns>
        private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest)
        {
            var tcs = new TaskCompletionSource <object>();

            // Accessing WebBrowser needs to happen on the UI thread
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                // Get the WebBrowser control
                if (this.browser == null)
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            CordovaView cView = page.FindName("CordovaView") as CordovaView;
                            if (cView != null)
                            {
                                this.browser = cView.Browser;
                            }
                        }
                    }
                }

                try
                {
                    // Only copy the cookies if the scheme and host match (to avoid any issues with secure/insecure cookies)
                    // NOTE: since the returned CookieCollection appears to munge the original cookie's domain value in favor of the actual Source domain,
                    // we can't know for sure whether the cookies would be applicable to any other hosts, so best to play it safe and skip for now.
                    if (this.browser != null && this.browser.Source.IsAbsoluteUri == true &&
                        this.browser.Source.Scheme == webRequest.RequestUri.Scheme && this.browser.Source.Host == webRequest.RequestUri.Host)
                    {
                        string cookieHeader      = "";
                        string requestPath       = webRequest.RequestUri.PathAndQuery;
                        CookieCollection cookies = this.browser.GetCookies();

                        // Iterate over the cookies and add to the header
                        foreach (Cookie cookie in cookies)
                        {
                            // Check that the path is allowed, first
                            // NOTE: Path always seems to be empty for now, even if the cookie has a path set by the server.
                            if (cookie.Path.Length == 0 || requestPath.IndexOf(cookie.Path, StringComparison.InvariantCultureIgnoreCase) == 0)
                            {
                                cookieHeader += cookie.Name + "=" + cookie.Value + "; ";
                            }
                        }

                        // Finally, set the header if we found any cookies
                        if (cookieHeader.Length > 0)
                        {
                            webRequest.Headers["Cookie"] = cookieHeader;
                        }
                    }
                }
                catch (Exception)
                {
                    // Swallow the exception
                }

                // Complete the task
                tcs.SetResult(Type.Missing);
            });

            await tcs.Task;
        }
コード例 #35
0
        public static Uri GetUri <T>(this PhoneApplicationPage currentPage) where T : PhoneApplicationPage
        {
            var targetPageType = typeof(T);

            return(new Uri("/" + targetPageType.Namespace + ";component/" + targetPageType.Name + ".xaml", UriKind.Relative));
        }
コード例 #36
0
 public ViewModelBase(PhoneApplicationPage page)
 {
     this.Ctx  = new DatingAppContext(AppContext.Instance.ConnectionString);
     this.Page = page;
 }
コード例 #37
0
 public VideoCaptureProvider(PhoneApplicationPage page)
 {
     Page = page;
 }
コード例 #38
0
 public RegisterViewModel(PhoneApplicationPage page) : base(page)
 {
 }
コード例 #39
0
 private static bool GetHasEventsWired(PhoneApplicationPage obj)
 {
     return((bool)obj.GetValue(HasEventsWiredProperty));
 }
コード例 #40
0
 private static void SetHasEventsWired(PhoneApplicationPage obj, bool value)
 {
     obj.SetValue(HasEventsWiredProperty, value);
 }
コード例 #41
0
        private void ShowInAppBrowser(string url)
        {
            Uri loc = new Uri(url, UriKind.RelativeOrAbsolute);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (browser != null)
                {
                    //browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                    browser.Navigate2(loc);
                }
                else
                {
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;

                        string baseImageUrl = "Images/";

                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                browser = new WebBrowser();
                                browser.IsScriptEnabled = true;
                                browser.LoadCompleted  += new System.Windows.Navigation.LoadCompletedEventHandler(browser_LoadCompleted);

                                browser.Navigating       += new EventHandler <NavigatingEventArgs>(browser_Navigating);
                                browser.NavigationFailed += new System.Windows.Navigation.NavigationFailedEventHandler(browser_NavigationFailed);
                                browser.Navigated        += new EventHandler <System.Windows.Navigation.NavigationEventArgs>(browser_Navigated);
                                browser.Navigate2(loc);

                                if (StartHidden)
                                {
                                    browser.Visibility = Visibility.Collapsed;
                                }

                                //browser.IsGeolocationEnabled = opts.isGeolocationEnabled;
                                grid.Children.Add(browser);
                            }

                            ApplicationBar bar = new ApplicationBar();
                            /// bar.BackgroundColor = Colors.Gray;
                            bar.BackgroundColor = Colors.Black;
                            bar.IsMenuEnabled   = false;

                            backButton = new ApplicationBarIconButton();
                            /// backButton.Text = "Back";
                            backButton.Text = "";
                            /// backButton.IconUri = new Uri(baseImageUrl + "appbar.back.rest.png", UriKind.Relative);
                            backButton.Click += new EventHandler(backButton_Click);
                            /// bar.Buttons.Add(backButton);


                            fwdButton = new ApplicationBarIconButton();
                            /// fwdButton.Text = "Forward";
                            fwdButton.Text = "";
                            /// fwdButton.IconUri = new Uri(baseImageUrl + "appbar.next.rest.png", UriKind.Relative);
                            fwdButton.Click += new EventHandler(fwdButton_Click);
                            /// bar.Buttons.Add(fwdButton);

                            ApplicationBarIconButton closeBtn = new ApplicationBarIconButton();
                            /// closeBtn.Text = "Close";
                            closeBtn.Text = "";
                            /// closeBtn.IconUri = new Uri(baseImageUrl + "appbar.close.rest.png", UriKind.Relative);
                            closeBtn.Click += new EventHandler(closeBtn_Click);
                            /// bar.Buttons.Add(closeBtn);

                            page.ApplicationBar = bar;
                            //bar.IsVisible = !StartHidden;
                            bar.IsVisible = false;
                            AppBar        = bar;

                            page.BackKeyPress += page_BackKeyPress;
                        }
                    }
                }
            });
        }
コード例 #42
0
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        public void startPlaying(string filePath)
        {
            if (this.recorder != null)
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet), false);
                return;
            }


            if (this.player == null || this.player.Source == null || this.player.Source.AbsolutePath.LastIndexOf(filePath) < 0)
            {
                try
                {
                    // this.player is a MediaElement, it must be added to the visual tree in order to play
                    PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (frame != null)
                    {
                        PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                        if (page != null)
                        {
                            Grid grid = page.FindName("LayoutRoot") as Grid;
                            if (grid != null)
                            {
                                //Microsoft.Xna.Framework.Media.MediaPlayer.Play(
                                this.player = grid.FindName("playerMediaElement") as MediaElement;
                                if (this.player == null) // still null ?
                                {
                                    this.player      = new MediaElement();
                                    this.player.Name = "playerMediaElement";
                                    grid.Children.Add(this.player);
                                    this.player.Visibility = Visibility.Visible;
                                }
                                if (this.player.CurrentState == System.Windows.Media.MediaElementState.Playing)
                                {
                                    this.player.Stop(); // stop it!
                                }

                                this.player.Source       = null; // Garbage collect it.
                                this.player.MediaOpened += MediaOpened;
                                this.player.MediaEnded  += MediaEnded;
                                this.player.MediaFailed += MediaFailed;
                            }
                        }
                    }

                    this.audioFile = filePath;

                    Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        this.player.Source = uri;
                    }
                    else
                    {
                        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (isoFile.FileExists(filePath))
                            {
                                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile))
                                {
                                    this.player.SetSource(stream);
                                }
                            }
                            else
                            {
                                Debug.WriteLine("Error: source doesn't exist :: " + filePath);
                                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, 1), false);
                                return;
                                //throw new ArgumentException("Source doesn't exist");
                            }
                        }
                    }
                    this.SetState(PlayerState_Starting);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error: " + e.Message);
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback), false);
                }
            }
            else
            {
                if (this.state != PlayerState_Running)
                {
                    this.player.Play();
                    this.SetState(PlayerState_Running);
                }
                else
                {
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState), false);
                }
            }
        }
コード例 #43
0
        /// <summary>
        /// Reveals the message box by inserting it into a popup and opening it.
        /// </summary>
        public void Show()
        {
            if (_popup != null)
            {
                if (_popup.IsOpen)
                {
                    return;
                }
            }

            LayoutUpdated += CustomMessageBox_LayoutUpdated;

            _frame = Application.Current.RootVisual as PhoneApplicationFrame;
            _page  = _frame.Content as PhoneApplicationPage;

            // Change the color of the system tray if necessary.
            if (SystemTray.IsVisible)
            {
                // Cache the original color of the system tray.
                _systemTrayColor = SystemTray.BackgroundColor;

                // Change the color of the system tray to match the message box.
                if (Background is SolidColorBrush)
                {
                    SystemTray.BackgroundColor = ((SolidColorBrush)Background).Color;
                }
                else
                {
                    SystemTray.BackgroundColor = (Color)Application.Current.Resources["PhoneChromeColor"];
                }
            }

            // Hide the application bar if necessary.
            if (_page.ApplicationBar != null)
            {
                // Cache the original visibility of the system tray.
                _hasApplicationBar = _page.ApplicationBar.IsVisible;

                // Hide it.
                if (_hasApplicationBar)
                {
                    _page.ApplicationBar.IsVisible = false;
                }
            }
            else
            {
                _hasApplicationBar = false;
            }

            // Dismiss the current message box if there is any.
            if (_currentInstance != null)
            {
                _mustRestore = false;

                var target = _currentInstance.Target as TelegramMessageBox;

                if (target != null)
                {
                    _systemTrayColor   = target._systemTrayColor;
                    _hasApplicationBar = target._hasApplicationBar;
                    target.Dismiss();
                }
            }

            _mustRestore = true;

            // Insert the overlay.
            Rectangle overlay         = new Rectangle();
            Color     backgroundColor = (Color)Application.Current.Resources["PhoneBackgroundColor"];

            overlay.Fill = new SolidColorBrush(Color.FromArgb(0x99, backgroundColor.R, backgroundColor.G, backgroundColor.B));
            _container   = new Grid();
            //_container.Children.Add(overlay);

            // Insert the message box.
            _container.Children.Add(this);

            // Create and open the popup.
            _popup       = new Popup();
            _popup.Child = _container;
            SetSizeAndOffset();
            _popup.IsOpen    = true;
            _currentInstance = new WeakReference(this);

            // Attach event handlers.
            if (_page != null)
            {
                _page.BackKeyPress       += OnBackKeyPress;
                _page.OrientationChanged += OnOrientationChanged;
            }

            if (_frame != null)
            {
                _frame.Navigating += OnNavigating;
            }
        }
コード例 #44
0
        public void Show(int totalCount, string albumId, int ind, Func <int, Image> getImageFunc, Action <int, bool> showHideOriginalImageCallback, PhotoPickerPhotos pickerPage)
        {
            if (this.IsShown)
            {
                return;
            }
            ((UIElement)this).Visibility = Visibility.Visible;
            this._indToShow = ind;
            if (this._pppVM != null)
            {
                this._pppVM.PropertyChanged -= new PropertyChangedEventHandler(this.PickerVM_PropertyChanged);
            }
            this._pppVM = pickerPage.VM;
            this._pppVM.PropertyChanged += new PropertyChangedEventHandler(this.PickerVM_PropertyChanged);
            this._pickerPage             = pickerPage;
            this._totalCount             = totalCount;
            this._savedPageAppBar        = this.Page.ApplicationBar;
            this._albumId       = albumId;
            this._imageEditorVM = this._pickerPage.VM.ImageEditor;
            ((UIElement)this.elliplseSelect).Opacity = (0.0);
            ((UIElement)this.imageSelect).Opacity    = (0.0);
            this.OnPropertyChanged("ImageEditor");
            this.InitializeImageSizes();
            PhoneApplicationPage page = this.Page;

            // ISSUE: variable of the null type
            page.ApplicationBar = (null);
            EventHandler <CancelEventArgs> eventHandler = new EventHandler <CancelEventArgs>(this.Page_BackKeyPress);

            page.BackKeyPress += (eventHandler);
            this.UpdateConfirmButtonState();
            this.imageViewer.Initialize(totalCount, (Func <int, ImageInfo>)(i =>
            {
                double num1 = 0.0;
                double num2 = 0.0;
                if (this._imageSizes.Count > i)
                {
                    Size imageSize1 = this._imageSizes[i];
                    // ISSUE: explicit reference operation
                    num1            = ((Size)@imageSize1).Width;
                    Size imageSize2 = this._imageSizes[i];
                    // ISSUE: explicit reference operation
                    num2 = ((Size)@imageSize2).Height;
                }
                ImageEffectsInfo imageEffectsInfo = this._imageEditorVM.GetImageEffectsInfo(this._albumId, this._totalCount - i - 1);
                if (imageEffectsInfo != null && imageEffectsInfo.ParsedExif != null && (imageEffectsInfo.ParsedExif.Width != 0 && imageEffectsInfo.ParsedExif.Height != 0))
                {
                    num1 = (double)imageEffectsInfo.ParsedExif.Width;
                    num2 = (double)imageEffectsInfo.ParsedExif.Height;
                    if (imageEffectsInfo.ParsedExif.Orientation == ExifOrientation.TopRight || imageEffectsInfo.ParsedExif.Orientation == ExifOrientation.BottomLeft)
                    {
                        double num3 = num1;
                        num1        = num2;
                        num2        = num3;
                    }
                }
                if (imageEffectsInfo != null && imageEffectsInfo.CropRect != null && !this._inCropMode)
                {
                    num1 = (double)imageEffectsInfo.CropRect.Width;
                    num2 = (double)imageEffectsInfo.CropRect.Height;
                }
                return(new ImageInfo()
                {
                    GetSourceFunc = (Func <bool, BitmapSource>)(allowBackgroundCreation => this._imageEditorVM.GetBitmapSource(this._albumId, this._totalCount - i - 1, allowBackgroundCreation)),
                    Width = num1,
                    Height = num2
                });
            }), getImageFunc, showHideOriginalImageCallback, (FrameworkElement)null, (Action <int>)null);
            this.IsShown = true;
            this.ShowViewer();
        }
コード例 #45
0
        public HideHeaderHelper(NewsfeedHeaderUC ucHeader, ViewportControl viewportControl, PhoneApplicationPage page)
        {
            this._ucHeader        = ucHeader;
            this._viewportControl = viewportControl;
            this._page            = page;
            TranslateTransform renderTransform = this._ucHeader.RenderTransform as TranslateTransform;

            if (renderTransform == null)
            {
                TranslateTransform translateTransform = new TranslateTransform();
                this._ucHeader.RenderTransform = translateTransform;
                this._translateHeader          = translateTransform;
            }
            else
            {
                this._translateHeader = renderTransform;
            }
            //this._minOffsetHeader = (-this._ucHeader.Height) + 32.0;
            //
            this._minOffsetHeader = (-this._ucHeader.Height);
            if (!VKClient.Common.Library.AppGlobalStateManager.Current.GlobalState.HideSystemTray)
            {
                this._minOffsetHeader += 32;
            }
            //
            this._maxOffsetHeader    = 0.0;
            this._minOffsetFreshNews = 0.0;
            this._ucHeader.borderFreshNews.Visibility = Visibility.Visible;
            this._translateFreshNews                        = this._ucHeader.translateFreshNews;
            this._translateFreshNews.Y                      = this._minOffsetFreshNews;
            this._viewportControl.ViewportChanged          += (new EventHandler <ViewportChangedEventArgs>(this.ViewportControl_OnViewportControlChanged));
            this._viewportControl.ManipulationStateChanged += (new EventHandler <ManipulationStateChangedEventArgs>(this.ViewportControl_OnManipulationStateChanged));
        }
コード例 #46
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth          = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight         = System.Windows.Application.Current.Host.Content.ActualHeight;

            if ((int)screenHeight == 0)
            {
                throw new Exception("screenHeight");
            }
            PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content;

            mMainImage = new Image();


            mainPage.Width    = screenWidth;
            mainPage.Height   = screenHeight;
            mMainImage.Width  = screenWidth;
            mMainImage.Height = screenHeight;
            mainPage.Content  = mMainImage;

            mClipRect.X      = 0.0;
            mClipRect.Y      = 0.0;
            mClipRect.Width  = screenWidth;
            mClipRect.Height = screenHeight;

            // no apparent effect on memory leaks.
            runtime.RegisterCleaner(delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.Content = null;
                });
            });

            mBackBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);
            mFrontBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);

            mMainImage.Source = mFrontBuffer;

            // clear front and backbuffer.
            for (int i = 0; i < mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight; i++)
            {
                mBackBuffer.Pixels[i] = mBackBuffer.Pixels[i] = (int)(0xff << 24);
            }

            mCurrentDrawTarget = mBackBuffer;

            mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                                                                       (byte)(mCurrentColor >> 16),
                                                                       (byte)(mCurrentColor >> 8),
                                                                       (byte)(mCurrentColor));

            syscalls.maSetColor = delegate(int rgb)
            {
                int oldColor = (int)mCurrentColor;
                mCurrentColor        = 0xff000000 | (uint)(rgb & 0xffffff);
                mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                                                                           (byte)(mCurrentColor >> 16),
                                                                           (byte)(mCurrentColor >> 8),
                                                                           (byte)(mCurrentColor));
                return(oldColor & 0xffffff);
            };

            syscalls.maSetClipRect = delegate(int x, int y, int w, int h)
            {
                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                mClipRect.X      = x;
                mClipRect.Y      = y;
                mClipRect.Width  = w;
                mClipRect.Height = h;
            };

            syscalls.maGetClipRect = delegate(int cliprect)
            {
                Memory mem = core.GetDataMemory();
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.left, (int)mClipRect.X);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.top, (int)mClipRect.Y);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.width, (int)mClipRect.Width);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.height, (int)mClipRect.Height);
            };

            syscalls.maPlot = delegate(int x, int y)
            {
                mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor);
            };

            syscalls.maUpdateScreen = delegate()
            {
                //System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight);
                System.Buffer.BlockCopy(mBackBuffer.Pixels, 0, mFrontBuffer.Pixels, 0, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight * 4);
                InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
            };

            syscalls.maFillRect = delegate(int x, int y, int w, int h)
            {
                // this function has a bug (it only fills one pixel less than the image.)
                //mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    (int)mClipRect.X, (int)mClipRect.Y, (int)mClipRect.Width, (int)mClipRect.Height,
                    out x, out y, out w, out h);

                if (w <= 0 || h <= 0)
                {
                    return;
                }

                int index = x + y * mCurrentDrawTarget.PixelWidth;
                while (h-- != 0)
                {
                    int width = w;
                    while (width-- != 0)
                    {
                        mCurrentDrawTarget.Pixels[index] = (int)mCurrentColor;
                        index++;
                    }
                    index += -w + mCurrentDrawTarget.PixelWidth;
                }
            };

            syscalls.maLine = delegate(int x1, int y1, int x2, int y2)
            {
                GraphicsUtil.Point p1 = new GraphicsUtil.Point(x1, y1);
                GraphicsUtil.Point p2 = new GraphicsUtil.Point(x2, y2);
                if (!GraphicsUtil.ClipLine(p1, p2, (int)mClipRect.X, (int)(mClipRect.X + mClipRect.Width),
                                           (int)mClipRect.Y, (int)(mClipRect.Y + mClipRect.Height)))
                {
                    return;
                }

                mCurrentDrawTarget.DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, (int)mCurrentColor);
            };

            textBlock.FontSize = mCurrentFontSize;

            syscalls.maDrawText = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                if (text.Length == 0)
                {
                    return;
                }
                DrawText(text, left, top);
            };

            syscalls.maGetTextSize = delegate(int str)
            {
                String text       = core.GetDataMemory().ReadStringAtAddress(str);
                int    textWidth  = 0;
                int    textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return(MoSync.Util.CreateExtent(textWidth, textHeight));
            };

            syscalls.maDrawTextW = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                if (text.Length == 0)
                {
                    return;
                }

                DrawText(text, left, top);
            };

            syscalls.maGetTextSizeW = delegate(int str)
            {
                String text       = core.GetDataMemory().ReadWStringAtAddress(str);
                int    textWidth  = 0;
                int    textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return(MoSync.Util.CreateExtent(textWidth, textHeight));
            };

            syscalls.maFillTriangleFan = delegate(int points, int count)
            {
                int[] newPoints = new int[count * 2 + 2];
                for (int i = 0; i < count; i++)
                {
                    newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.x);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.y);
                mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor);
            };

            syscalls.maFillTriangleStrip = delegate(int points, int count)
            {
                int[] xcoords = new int[count];
                int[] ycoords = new int[count];

                for (int i = 0; i < count; i++)
                {
                    xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }

                for (int i = 2; i < count; i++)
                {
                    mCurrentDrawTarget.FillTriangle(
                        xcoords[i - 2], ycoords[i - 2],
                        xcoords[i - 1], ycoords[i - 1],
                        xcoords[i - 0], ycoords[i - 0],
                        (int)mCurrentColor);
                }
            };

            syscalls.maSetDrawTarget = delegate(int drawTarget)
            {
                int oldDrawTarget = mCurrentDrawTargetIndex;
                if (drawTarget == mCurrentDrawTargetIndex)
                {
                    return(oldDrawTarget);
                }
                if (drawTarget == MoSync.Constants.HANDLE_SCREEN)
                {
                    mCurrentDrawTarget      = mBackBuffer;
                    mCurrentDrawTargetIndex = drawTarget;
                    return(oldDrawTarget);
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget);
                mCurrentDrawTarget      = (WriteableBitmap)res.GetInternalObject();
                mCurrentDrawTargetIndex = drawTarget;
                return(oldDrawTarget);
            };

            syscalls.maGetScrSize = delegate()
            {
                int w = mBackBuffer.PixelWidth;
                int h = mBackBuffer.PixelHeight;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    // if the orientation is landscape, the with and height should be swaped
                    PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);
                    if (currentPage.Orientation == PageOrientation.Landscape ||
                        currentPage.Orientation == PageOrientation.LandscapeLeft ||
                        currentPage.Orientation == PageOrientation.LandscapeRight)
                    {
                        int aux = w;
                        w       = h;
                        h       = aux;
                    }
                });
                return(MoSync.Util.CreateExtent(w, h));
            };

            syscalls.maGetImageSize = delegate(int handle)
            {
                Resource     res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle);
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                if (src == null)
                {
                    MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource.");
                }
                int w = 0, h = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    w = src.PixelWidth;
                    h = src.PixelHeight;
                });

                return(MoSync.Util.CreateExtent(w, h));
            };

            syscalls.maDrawImage = delegate(int image, int left, int top)
            {
                Resource        res     = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src     = (WriteableBitmap)res.GetInternalObject();
                Rect            srcRect = new Rect(0, 0, src.PixelWidth, src.PixelHeight);
                Rect            dstRect = new Rect(left, top, src.PixelWidth, src.PixelHeight);
                mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);
            };

            syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode)
            {
                Resource        res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();

                Memory dataMemory = core.GetDataMemory();
                int    srcRectX   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.left);
                int    srcRectY   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.top);
                int    srcRectW   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.width);
                int    srcRectH   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.height);
                int    dstPointX  = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.x);
                int    dstPointY  = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.y);

                Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH);
                Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH);

                GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, transformMode, mClipRect);
            };

            syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                WriteableBitmap bitmap = null;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);

                    for (int i = 0; i < bitmap.PixelWidth * bitmap.PixelHeight; i++)
                    {
                        bitmap.Pixels[i] = (int)(0xff << 24);
                    }
                });

                if (bitmap == null)
                {
                    return(MoSync.Constants.RES_OUT_OF_MEMORY);
                }
                res.SetInternalObject(bitmap);
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha)
            {
                int width  = MoSync.Util.ExtentX(_size);
                int height = MoSync.Util.ExtentY(_size);

                WriteableBitmap bitmap = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);
                });

                //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height);
                bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4);
                if (_alpha == 0)
                {
                    int[] pixels    = bitmap.Pixels;
                    int   numPixels = width * height;
                    for (int i = 0; i < numPixels; i++)
                    {
                        pixels[i] = (int)((uint)pixels[i] | 0xff000000);
                    }
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder);
                res.SetInternalObject(bitmap);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength)
            {
                Memory dataMemory = core.GetDataMemory();
                int    dstX       = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.x);
                int    dstY       = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.y);
                int    srcRectX   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int    srcRectY   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int    srcRectW   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int    srcRectH   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int[]  pixels     = mCurrentDrawTarget.Pixels;
                // todo: clipRect

                _scanlength *= 4;                 // sizeof(int)

                for (int h = 0; h < srcRectH; h++)
                {
                    int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX;
                    int address    = _src + (srcRectY + h) * _scanlength;
                    for (int w = 0; w < srcRectW; w++)
                    {
                        uint srcPixel = dataMemory.ReadUInt32(address);
                        uint dstPixel = (uint)pixels[pixelIndex];

                        uint srcPixelR = (srcPixel & 0x00ff0000) >> 16;
                        uint srcPixelG = (srcPixel & 0x0000ff00) >> 8;
                        uint srcPixelB = (srcPixel & 0x000000ff) >> 0;
                        uint srcPixelA = (srcPixel & 0xff000000) >> 24;
                        uint dstPixelR = (dstPixel & 0x00ff0000) >> 16;
                        uint dstPixelG = (dstPixel & 0x0000ff00) >> 8;
                        uint dstPixelB = (dstPixel & 0x000000ff) >> 0;
                        uint dstPixelA = (dstPixel & 0xff000000) >> 24;

                        dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255;
                        dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255;
                        dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255;

                        dstPixel           = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB);
                        pixels[pixelIndex] = (int)dstPixel;

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

            syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength)
            {
                Resource        res        = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image);
                WriteableBitmap src        = (WriteableBitmap)res.GetInternalObject();
                Memory          dataMemory = core.GetDataMemory();
                int             srcRectX   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int             srcRectY   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int             srcRectW   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int             srcRectH   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int             lineDst    = _dst;
                byte[]          data       = src.ToByteArray(srcRectY * src.PixelWidth,
                                                             srcRectH * src.PixelWidth); // BlockCopy?
                byte[] coreArray = dataMemory.GetData();
                for (int y = 0; y < srcRectH; y++)
                {
                    System.Array.Copy(data, y * src.PixelWidth * 4, coreArray,
                                      lineDst, src.PixelWidth * 4);
                    lineDst += _scanlength * 4;
                }
            };

            syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                if (res == null)
                {
                    return(MoSync.Constants.RES_BAD_INPUT);
                }
                Stream bin = (Stream)res.GetInternalObject();
                if (bin == null)
                {
                    return(MoSync.Constants.RES_BAD_INPUT);
                }
                BoundedStream   s      = new BoundedStream(bin, _offset, _size);
                WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s);
                s.Close();

                if (bitmap == null)
                {
                    return(MoSync.Constants.RES_BAD_INPUT);
                }

                Resource imageRes = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder);
                imageRes.SetInternalObject(bitmap);
                imageRes.SetResourceType(MoSync.Constants.RT_IMAGE);
                return(MoSync.Constants.RES_OK);
            };
        }
コード例 #47
0
        /// <summary>
        /// Returns the set of weak references to the items
        /// that must be animated.
        /// </summary>
        /// <returns>
        /// A set of weak references to items sorted by their feathering index.
        /// </returns>
        private static IList <WeakReference> GetTargetsToAnimate()
        {
            List <WeakReference>  references;
            List <WeakReference>  targets = new List <WeakReference>();
            PhoneApplicationPage  page    = null;
            PhoneApplicationFrame frame   = Application.Current.RootVisual as PhoneApplicationFrame;

            if (frame != null)
            {
                page = frame.Content as PhoneApplicationPage;
            }

            if (page == null)
            {
                return(null);
            }

            if (!_pagesToReferences.TryGetValue(page, out references))
            {
                return(null);
            }

            foreach (WeakReference r in references)
            {
                FrameworkElement target = r.Target as FrameworkElement;

                // If target is null, skip.
                if (target == null)
                {
                    continue;
                }

                // If target is not on the screen, skip.
                if (!IsOnScreen(target))
                {
                    continue;
                }

                ListBox          listBox          = r.Target as ListBox;
                LongListSelector longListSelector = r.Target as LongListSelector;
                Pivot            pivot            = r.Target as Pivot;

                if (listBox != null)
                {
                    // If the target is a ListBox, feather its items individually.
                    ItemsControlExtensions.GetItemsInViewPort(listBox, targets);
                }
                else if (longListSelector != null)
                {
                    // If the target is a LongListSelector, feather its items individually.
                    ListBox child = TemplatedVisualTreeExtensions.GetFirstLogicalChildByType <ListBox>(longListSelector, false);

                    if (child != null)
                    {
                        ItemsControlExtensions.GetItemsInViewPort(child, targets);
                    }
                }
                else if (pivot != null)
                {
                    // If the target is a Pivot, feather the title and the headers individually.
                    ContentPresenter title = TemplatedVisualTreeExtensions.GetFirstLogicalChildByType <ContentPresenter>(pivot, false);

                    if (title != null)
                    {
                        targets.Add(new WeakReference(title));
                    }

                    PivotHeadersControl headers = TemplatedVisualTreeExtensions.GetFirstLogicalChildByType <PivotHeadersControl>(pivot, false);

                    if (headers != null)
                    {
                        targets.Add(new WeakReference(headers));
                    }
                }
                else
                {
                    // Else, feather the target as a whole.
                    targets.Add(r);
                }
            }

            return(targets);
        }
コード例 #48
0
 /// <summary>
 /// Sets the parent page of the specified dependency object.
 /// </summary>
 /// <param name="obj">The depedency object.</param>
 /// <param name="value">The page.</param>
 private static void SetParentPage(DependencyObject obj, PhoneApplicationPage value)
 {
     obj.SetValue(ParentPageProperty, value);
 }
コード例 #49
0
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        public void startPlaying(string filePath)
        {
            if (this.recorder != null)
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet));
                return;
            }


            if ((this.player == null) || (this.state == MediaStopped))
            {
                try
                {
                    if (this.player == null)
                    {
                        // this.player is a MediaElement, it must be added to the visual tree in order to play
                        PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                        if (frame != null)
                        {
                            PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                            if (page != null)
                            {
                                Grid grid = page.FindName("LayoutRoot") as Grid;
                                if (grid != null)
                                {
                                    this.player = new MediaElement();
                                    grid.Children.Add(this.player);
                                    this.player.Visibility   = Visibility.Collapsed;
                                    this.player.MediaOpened += MediaOpened;
                                    this.player.MediaEnded  += MediaEnded;
                                    this.player.MediaFailed += MediaFailed;
                                }
                            }
                        }
                    }
                    this.audioFile = filePath;

                    Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        this.player.Source = uri;
                    }
                    else
                    {
                        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (isoFile.FileExists(filePath))
                            {
                                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile))
                                {
                                    this.player.SetSource(stream);
                                }
                            }
                            else
                            {
                                throw new ArgumentException("Source doesn't exist");
                            }
                        }
                    }
                    this.SetState(MediaStarting);
                }
                catch (Exception e)
                {
                    string s = e.Message;
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback));
                }
            }
            else
            {
                if ((this.state == MediaPaused) || (this.state == MediaStarting))
                {
                    this.player.Play();
                    this.SetState(MediaRunning);
                }
                else
                {
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState));
                }
            }
        }
コード例 #50
0
 public EditNoteViewModel(int NoteId, PhoneApplicationPage page) : base(page)
 {
     this.Note = Ctx.Notes.Where(x => x.Id == NoteId).SingleOrDefault();
 }
コード例 #51
0
        public void show(string options)
        {
            ToastOptions toastOptions;

            string[] args        = JSON.JsonHelper.Deserialize <string[]>(options);
            String   jsonOptions = args[0];

            try
            {
                toastOptions = JSON.JsonHelper.Deserialize <ToastOptions>(jsonOptions);
            }
            catch (Exception)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            var message  = toastOptions.message;
            var duration = toastOptions.duration;
            var position = toastOptions.position;

            string aliasCurrentCommandCallbackId = args[1];

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                PhoneApplicationPage page = Page;
                if (page != null)
                {
                    Grid grid = page.FindName("LayoutRoot") as Grid;
                    if (grid != null)
                    {
                        TextBlock tb     = new TextBlock();
                        tb.TextWrapping  = TextWrapping.Wrap;
                        tb.TextAlignment = TextAlignment.Center;
                        tb.Text          = message;
                        tb.Foreground    = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)); // white

                        Border b              = new Border();
                        b.CornerRadius        = new CornerRadius(12);
                        b.Background          = new SolidColorBrush(Color.FromArgb(190, 55, 55, 55));
                        b.HorizontalAlignment = HorizontalAlignment.Center;

                        Grid pgrid = new Grid();
                        pgrid.HorizontalAlignment = HorizontalAlignment.Stretch;
                        pgrid.VerticalAlignment   = VerticalAlignment.Stretch;
                        pgrid.Margin = new Thickness(20);
                        pgrid.Children.Add(tb);
                        pgrid.Width = Application.Current.Host.Content.ActualWidth - 80;

                        b.Child = pgrid;
                        if (popup != null && popup.IsOpen)
                        {
                            popup.IsOpen = false;
                        }
                        popup       = new Popup();
                        popup.Child = b;

                        popup.HorizontalOffset    = 20;
                        popup.Width               = Application.Current.Host.Content.ActualWidth;
                        popup.HorizontalAlignment = HorizontalAlignment.Center;

                        if ("top".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Top;
                            popup.VerticalOffset    = 20;
                        }
                        else if ("bottom".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Bottom;
                            popup.VerticalOffset    = -100; // TODO can do better
                        }
                        else if ("center".Equals(position))
                        {
                            popup.VerticalAlignment = VerticalAlignment.Center;
                            popup.VerticalOffset    = -50; // TODO can do way better
                        }
                        else
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "invalid position. valid options are 'top', 'center' and 'bottom'"));
                            return;
                        }

                        int hideDelay = 2800;
                        if ("long".Equals(duration))
                        {
                            hideDelay = 5500;
                        }
                        else if (!"short".Equals(duration))
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "invalid duration. valid options are 'short' and 'long'"));
                            return;
                        }

                        grid.Children.Add(popup);
                        popup.IsOpen = true;
                        this.hidePopup(hideDelay);
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.INSTANTIATION_EXCEPTION));
                }
            });
        }
コード例 #52
0
            /**
             * Applies transition to the current content and calls the given delegate in a specific moment
             * (before/after animation) in order to distingues between transition applied on the current
             * "page/screen" or the next.
             *
             * @param aDelegate a delegate invoked in different moments, depending on the transition type.
             * The delegate must be responsible for switching screens/context/adding children widgets.
             * @param transitionType a transition type.
             */
            static public void doScreenTransition(Delegate_SwitchContentDelegate aDelegate, int transitionType)
            {
                if (null != aDelegate)
                {
                    TransitionElement transition     = null;
                    bool doTransitionOnCurrentScreen = false;
                    switch (transitionType)
                    {
                    case MoSync.Constants.MAW_TRANSITION_TYPE_SLIDE_RIGHT:
                        transition = new SlideTransition();
                        (transition as SlideTransition).Mode = SlideTransitionMode.SlideRightFadeIn;
                        break;

                    case MoSync.Constants.MAW_TRANSITION_TYPE_SLIDE_LEFT:
                        transition = new SlideTransition();
                        (transition as SlideTransition).Mode = SlideTransitionMode.SlideLeftFadeIn;
                        break;

                    case MoSync.Constants.MAW_TRANSITION_TYPE_SWIVEL_IN:
                        transition = new SwivelTransition();
                        (transition as SwivelTransition).Mode = SwivelTransitionMode.FullScreenIn;
                        break;

                    case MoSync.Constants.MAW_TRANSITION_TYPE_SWIVEL_OUT:
                        transition = new SwivelTransition();
                        (transition as SwivelTransition).Mode = SwivelTransitionMode.FullScreenOut;
                        doTransitionOnCurrentScreen           = true;
                        break;

                    case MoSync.Constants.MAW_TRANSITION_TYPE_TURNSTILE_FORWARD:
                        transition = new TurnstileTransition();
                        (transition as TurnstileTransition).Mode = TurnstileTransitionMode.ForwardOut;
                        doTransitionOnCurrentScreen = true;
                        break;

                    case MoSync.Constants.MAW_TRANSITION_TYPE_TURNSTILE_BACKWARD:
                        transition = new TurnstileTransition();
                        (transition as TurnstileTransition).Mode = TurnstileTransitionMode.BackwardIn;
                        break;

                    case MoSync.Constants.MAW_TRANSITION_TYPE_NONE:
                    default:
                        aDelegate();
                        return;
                    }
                    PhoneApplicationPage page = (PhoneApplicationPage)((PhoneApplicationFrame)Application.Current.RootVisual).Content;

                    ITransition transInterf = transition.GetTransition(page);
                    transInterf.Completed += delegate
                    {
                        transInterf.Stop();
                        if (doTransitionOnCurrentScreen)
                        {
                            aDelegate();
                        }
                    };
                    transInterf.Begin();
                    if (!doTransitionOnCurrentScreen)
                    {
                        aDelegate();
                    }
                }
            }