Exemple #1
0
 internal SystemHttpServer(ScriptExecutorGetter bc, int port, string robotName)
 {
     clientManager = bc;
     PortNum       = port;
     RobotName     = robotName;
     ThreadPool.QueueUserWorkItem(Init);
 }
Exemple #2
0
        void Friends_FriendOnline(object sender, FriendInfoEventArgs e)
        {
            if (!instance.GlobalSettings["show_friends_online_notifications"])
            {
                return;
            }

            ThreadPool.QueueUserWorkItem(sync =>
            {
                string name           = instance.Names.Get(e.Friend.UUID, true);
                MethodInvoker display = () =>
                {
                    DisplayNotification(e.Friend.UUID, name + " is online");
                    RefreshFriendsList();
                };

                if (InvokeRequired)
                {
                    BeginInvoke(display);
                }
                else
                {
                    display();
                }
            });
        }
        public void DoTeleport()
        {
            if (!Active)
            {
                return;
            }

            if (instance.MonoRuntime)
            {
                map?.Navigate(Path.GetDirectoryName(Application.ExecutablePath) + @"/worldmap.html");
            }

            lblStatus.Text    = "Teleporting to " + txtRegion.Text;
            prgTeleport.Style = ProgressBarStyle.Marquee;

            ThreadPool.QueueUserWorkItem(state =>
            {
                if (!client.Self.Teleport(txtRegion.Text, new Vector3((int)nudX.Value, (int)nudY.Value, (int)nudZ.Value)))
                {
                    Self_TeleportProgress(this, new TeleportEventArgs(string.Empty, TeleportStatus.Failed, TeleportFlags.Default));
                }
                InTeleport = false;
            }
                                         );
        }
        void map_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            map.DocumentCompleted         -= new WebBrowserDocumentCompletedEventHandler(map_DocumentCompleted);
            map.AllowWebBrowserDrop        = false;
            map.WebBrowserShortcutsEnabled = false;
            map.ScriptErrorsSuppressed     = true;
            map.ObjectForScripting         = this;
            map.AllowNavigation            = false;

            if (instance.MonoRuntime)
            {
                map.Navigating += new WebBrowserNavigatingEventHandler(map_Navigating);
            }

            ThreadPool.QueueUserWorkItem(sync =>
            {
                Thread.Sleep(1000);
                if (InvokeRequired && (!instance.MonoRuntime || IsHandleCreated))
                {
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        if (savedRegion != null)
                        {
                            gotoRegion(savedRegion, savedX, savedY);
                        }
                        else if (Active)
                        {
                            gotoRegion(client.Network.CurrentSim.Name, 128, 128);
                        }
                    }
                                                  ));
                }
            }
                                         );
        }
        void gotoRegion(string regionName, int simX, int simY)
        {
            savedRegion = regionName;
            savedX      = simX;
            savedY      = simY;

            if (!Visible)
            {
                return;
            }

            if (mmap != null)
            {
                if (!regionHandles.ContainsKey(regionName))
                {
                    ThreadPool.QueueUserWorkItem(sync =>
                    {
                        ManualResetEvent done = new ManualResetEvent(false);
                        EventHandler <GridRegionEventArgs> handler = (sender, e) =>
                        {
                            regionHandles[e.Region.Name] = Utils.UIntsToLong((uint)e.Region.X, (uint)e.Region.Y);
                            if (e.Region.Name == regionName)
                            {
                                done.Set();
                            }
                        };
                        client.Grid.GridRegion += handler;
                        client.Grid.RequestMapRegion(regionName, GridLayerType.Objects);
                        if (done.WaitOne(30 * 1000, false))
                        {
                            if (!instance.MonoRuntime || IsHandleCreated)
                            {
                                BeginInvoke(new MethodInvoker(() => gotoRegion(regionName, simX, simY)));
                            }
                        }
                        client.Grid.GridRegion -= handler;
                    }
                                                 );
                    return;
                }
                mmap.CenterMap(regionHandles[regionName], (uint)simX, (uint)simY, true);
                return;
            }

            if (map == null || map.Document == null)
            {
                return;
            }

            if (instance.MonoRuntime)
            {
                map.Document.InvokeScript(string.Format("gReg = \"{0}\"; gSimX = {1}; gSimY = {2}; monosucks", regionName, simX, simY));
            }
            else
            {
                map.Document.InvokeScript("gotoRegion", new object[] { regionName, simX, simY });
            }
        }
Exemple #6
0
        /// <summary>Raises the EachSimEvent event</summary>
        /// <param name="e">An EachSimEventEventArgs object containing the
        /// data returned from the data server</param>
        protected virtual void OnEachSimEvent(CogbotEvent e)
        {
            if (e.Verb == "On-Log-Message")
            {
                return;
            }
            if (ExpectConnected == false)
            {
                return;
            }
            EventHandler <EventArgs> handler = m_EachSimEvent;

            if (handler == null)
            {
                return;
            }
            List <Delegate> todo = new List <Delegate>();

            lock (m_EachSimEventLock)
            {
                handler = m_EachSimEvent;
                if (handler == null)
                {
                    return;
                }
                AddTodo(handler.GetInvocationList(), todo);
            }

            object sender = e.Sender ?? this;
            bool   async  = todo.Count > 3;

            foreach (var d in todo)
            {
                var         del  = (EventHandler <EventArgs>)d;
                ThreadStart task = () =>
                {
                    try
                    {
                        del(sender, (EventArgs)e);
                    }
                    catch (Exception ex)
                    {
                        LogException("OnEachSimEvent Worker", ex);
                    }
                };
                if (async)
                {
                    ThreadPool.QueueUserWorkItem(sync => task());
                }
                else
                {
                    task();
                }
            }
        }
Exemple #7
0
        private void btnIM_Click(object sender, EventArgs e)
        {
            if (listFriends.SelectedItems.Count == 1)
            {
                selectedFriend = (FriendInfo)listFriends.SelectedItems[0];
                instance.TabConsole.ShowIMTab(selectedFriend.UUID, selectedFriend.Name, true);
            }
            else if (listFriends.SelectedItems.Count > 1)
            {
                List <UUID> participants = new List <UUID>();
                foreach (var item in listFriends.SelectedItems)
                {
                    participants.Add(((FriendInfo)item).UUID);
                }
                UUID tmpID = UUID.Random();
                lblFriendName.Text = "Startings friends conference...";
                instance.TabConsole.DisplayNotificationInChat(lblFriendName.Text, ChatBufferTextStyle.Invisible);
                btnIM.Enabled = false;

                ThreadPool.QueueUserWorkItem(sync =>
                {
                    using (ManualResetEvent started = new ManualResetEvent(false))
                    {
                        UUID sessionID     = UUID.Zero;
                        string sessionName = string.Empty;

                        EventHandler <GroupChatJoinedEventArgs> handler = (isender, ie) =>
                        {
                            if (ie.TmpSessionID == tmpID)
                            {
                                sessionID   = ie.SessionID;
                                sessionName = ie.SessionName;
                                started.Set();
                            }
                        };

                        client.Self.GroupChatJoined += handler;
                        client.Self.StartIMConference(participants, tmpID);
                        if (started.WaitOne(30 * 1000, false))
                        {
                            instance.TabConsole.BeginInvoke(new MethodInvoker(() =>
                            {
                                instance.TabConsole.AddConferenceIMTab(sessionID, sessionName);
                                instance.TabConsole.SelectTab(sessionID.ToString());
                            }
                                                                              ));
                        }
                        client.Self.GroupChatJoined -= handler;
                        BeginInvoke(new MethodInvoker(() => RefreshFriendsList()));
                    }
                }
                                             );
            }
        }
Exemple #8
0
        /// <summary>Process an incoming packet and raise the appropriate events</summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">The EventArgs object containing the packet data</param>
        protected void CoarseLocationHandler(object sender, PacketReceivedEventArgs e)
        {
            CoarseLocationUpdatePacket coarse = (CoarseLocationUpdatePacket)e.Packet;

            // populate a dictionary from the packet, for local use
            Dictionary <UUID, Vector3> coarseEntries = new Dictionary <UUID, Vector3>();

            for (int i = 0; i < coarse.AgentData.Length; i++)
            {
                if (coarse.Location.Length > 0)
                {
                    coarseEntries[coarse.AgentData[i].AgentID] = new Vector3((int)coarse.Location[i].X, (int)coarse.Location[i].Y, (int)coarse.Location[i].Z * 4);
                }

                // the friend we are tracking on radar
                if (i == coarse.Index.Prey)
                {
                    e.Simulator.preyID = coarse.AgentData[i].AgentID;
                }
            }

            // find stale entries (people who left the sim)
            List <UUID> removedEntries = e.Simulator.avatarPositions.FindAll(delegate(UUID findID) { return(!coarseEntries.ContainsKey(findID)); });

            // anyone who was not listed in the previous update
            List <UUID> newEntries = new List <UUID>();

            lock (e.Simulator.avatarPositions.Dictionary)
            {
                // remove stale entries
                foreach (UUID trackedID in removedEntries)
                {
                    e.Simulator.avatarPositions.Dictionary.Remove(trackedID);
                }

                // add or update tracked info, and record who is new
                foreach (KeyValuePair <UUID, Vector3> entry in coarseEntries)
                {
                    if (!e.Simulator.avatarPositions.Dictionary.ContainsKey(entry.Key))
                    {
                        newEntries.Add(entry.Key);
                    }

                    e.Simulator.avatarPositions.Dictionary[entry.Key] = entry.Value;
                }
            }

            if (m_CoarseLocationUpdate != null)
            {
                ThreadPool.QueueUserWorkItem(delegate(object o)
                                             { OnCoarseLocationUpdate(new CoarseLocationUpdateEventArgs(e.Simulator, newEntries, removedEntries)); });
            }
        }
Exemple #9
0
        /// <summary>
        /// Fire the events registered for this packet type
        /// </summary>
        /// <param name="packetType">Incoming packet type</param>
        /// <param name="packet">Incoming packet</param>
        /// <param name="simulator">Simulator this packet was received from</param>
        internal void RaiseEvent(PacketType packetType, Packet packet, Simulator simulator)
        {
            PacketCallback callback;

            // Default handler first, if one exists
            if (_EventTable.TryGetValue(PacketType.Default, out callback) && callback.Callback != null)
            {
                if (callback.IsAsync)
                {
                    PacketCallbackWrapper wrapper;
                    wrapper.Callback  = callback.Callback;
                    wrapper.Packet    = packet;
                    wrapper.Simulator = simulator;
                    ThreadPool.QueueUserWorkItem(ThreadPoolDelegate, wrapper);
                }
                else
                {
                    try { callback.Callback(this, new PacketReceivedEventArgs(packet, simulator)); }
                    catch (Exception ex)
                    {
                        Logger.Log("Default packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client);
                    }
                }
            }

            if (_EventTable.TryGetValue(packetType, out callback) && callback.Callback != null)
            {
                if (callback.IsAsync)
                {
                    PacketCallbackWrapper wrapper;
                    wrapper.Callback  = callback.Callback;
                    wrapper.Packet    = packet;
                    wrapper.Simulator = simulator;
                    ThreadPool.QueueUserWorkItem(ThreadPoolDelegate, wrapper);
                }
                else
                {
                    try { callback.Callback(this, new PacketReceivedEventArgs(packet, simulator)); }
                    catch (Exception ex)
                    {
                        Logger.Log("Packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client);
                    }
                }

                return;
            }

            if (packetType != PacketType.Default && packetType != PacketType.PacketAck)
            {
                Logger.DebugLog("No handler registered for packet event " + packetType, Client);
            }
        }
        public void StartCheck()
        {
            if (client == null)
            {
                client = new WebClient();
                client.DownloadStringCompleted += OnDownloadStringCompleted;
            }

            ThreadPool.QueueUserWorkItem(state =>
            {
                client.DownloadStringAsync(new Uri(Properties.Resources.UpdateCheckUri));
            }
                                         );
        }
Exemple #11
0
        private void frmPrimWorkshop_Shown(object sender, EventArgs e)
        {
            SetupGLControl();

            ThreadPool.QueueUserWorkItem(sync =>
            {
                if (Client.Network.CurrentSim.ObjectsPrimitives.ContainsKey(RootPrimLocalID))
                {
                    UpdatePrimBlocking(Client.Network.CurrentSim.ObjectsPrimitives[RootPrimLocalID]);
                    var children = Client.Network.CurrentSim.ObjectsPrimitives.FindAll(p => p.ParentID == RootPrimLocalID);
                    children.ForEach(UpdatePrimBlocking);
                }
            }
                                         );
        }
 public void StartServer()
 {
     if (myServer != null)
     {
         return;
     }
     Console.WriteLine("starting testRDFServer");
     myServer = new PFEndpoint();
     //StringParser.Parse(prologEngine.rdfGraph, "<http://example.org/a1> <http://example.org/b1> <http://example.org/c1> .");
     prologEngine.connectMT("spindleMT", "rdfMT");
     prologEngine.connectMT("rdfMT", "baseKB");
     prologEngine.appendKB("triple(this,can,work).\n", "rdfMT");
     ThreadPool.QueueUserWorkItem((o) => myServer.beginService(prologEngine));
     prologEngine.EndpointCreated(myServer);
 }
Exemple #13
0
        public override CmdResult ExecuteRequest(CmdRequest args)
        {
            if (args.Length < 1)
            {
                return(ShowUsage());
            }
            string cmd = args.GetString("command");

            //return ClientManager.DoCommandAll()
            // Make an immutable copy of the Clients dictionary to safely iterate over
            int[] completed   = { 0 };
            var   BotClients  = ClientManager.BotClients;
            int   count       = BotClients.Count;
            var   fromAgentID = args.CallerAgent;

            if (count == 0)
            {
                return(ClientManager.ExecuteSystemCommand(cmd, fromAgentID, WriteLine, args.CmdFlags));
            }
            CmdResult[] results   = new CmdResult[count];
            int[]       clientNum = { 0 };
            foreach (BotClient client in BotClients)
            {
                clientNum[0]++;
                ThreadPool.QueueUserWorkItem(
                    (WaitCallback)
                    delegate(object state)
                {
                    BotClient testClient  = (BotClient)state;
                    results[clientNum[0]] = testClient.ExecuteCommand(cmd, fromAgentID, WriteLine, args.CmdFlags);
                    ++completed[0];
                },
                    client);
            }
            while (completed[0] < count)
            {
                Thread.Sleep(50);
            }
            foreach (var r in results)
            {
                if (r != null)
                {
                    return(r);
                }
            }
            return(results[0]);
        }
 protected void FireNotificationCallback(NotificationEventArgs e)
 {
     if (OnNotificationDisplayed == null)
     {
         return;
     }
     try
     {
         e.Type = Type;
         ThreadPool.QueueUserWorkItem(o => Notificaton_Displayed(this, e));
     }
     catch (Exception ex)
     {
         Console.WriteLine("" + ex);
         Logger.Log("Error executing notification callback", Helpers.LogLevel.Warning, ex);
     }
 }
Exemple #15
0
 public void Start()
 {
     lock (StartupLock)
     {
         if (IsStarted)
         {
             return;
         }
         IsStarted = true;
         try
         {
             LogInfo("Starting " + clientManager.GetType() + " on HTTPD port " + PortNum);
             if (!httpListener.IsListening)
             {
                 if (httpListener.Prefixes.Count == 0)
                 {
                     PrefixAdd("http://*:" + PortNum + "/");
                     PrefixAdd("http://*:" + PortNum + "/hanson_robotics/");
                     if (RobotName != null)
                     {
                         PrefixAdd("http://*:" + PortNum + "/" + RobotName + "/");
                     }
                 }
                 httpListener.Start();
                 if (!SynchronouslyHandle)
                 {
                     // Starts up the http listener to process requests asynchronously.
                     // Move our listening loop off to a worker thread so that the GUI doesn't lock up.
                     ThreadPool.QueueUserWorkItem(Listen);
                     return;
                 }
                 else
                 {
                     // Also moves our listening loop off to a worker thread so that the GUI doesn't lock up.
                     ThreadPool.QueueUserWorkItem(HandleSynchronously);
                 }
             }
         }
         catch (Exception)
         {
             IsStarted = false;
         }
     }
 }
Exemple #16
0
        void Friends_FriendshipTerminated(object sender, FriendshipTerminatedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(sync =>
            {
                string name           = instance.Names.Get(e.AgentID, true);
                MethodInvoker display = () =>
                {
                    DisplayNotification(e.AgentID, name + " is no longer on your friend list");
                    RefreshFriendsList();
                };

                if (InvokeRequired)
                {
                    BeginInvoke(display);
                }
                else
                {
                    display();
                }
            });
        }
Exemple #17
0
        private void btnNewPick_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(sync =>
            {
                UUID parcelID = client.Parcels.RequestRemoteParcelID(client.Self.SimPosition, client.Network.CurrentSim.Handle, client.Network.CurrentSim.ID);
                newPickID     = UUID.Random();

                client.Self.PickInfoUpdate(
                    newPickID,
                    false,
                    parcelID,
                    Instance.State.Parcel.Name,
                    client.Self.GlobalPosition,
                    Instance.State.Parcel.SnapshotID,
                    Instance.State.Parcel.Desc
                    );

                Invoke(new MethodInvoker(() => ClearPicks()));
                client.Avatars.RequestAvatarPicks(AgentID);
            });
        }
Exemple #18
0
        /// <summary>
        /// Fire the events registered for this event type asynchronously
        /// </summary>
        /// <param name="capsEvent">Capability name</param>
        /// <param name="message">Decoded event body</param>
        /// <param name="simulator">Reference to the simulator that
        /// generated this event</param>
        internal void BeginRaiseEvent(string capsEvent, IMessage message, Simulator simulator)
        {
            bool specialHandler = false;

            Caps.EventQueueCallback callback;

            // Default handler first, if one exists
            if (_EventTable.TryGetValue(String.Empty, out callback))
            {
                if (callback != null)
                {
                    CapsCallbackWrapper wrapper;
                    wrapper.Callback  = callback;
                    wrapper.CapsEvent = capsEvent;
                    wrapper.Message   = message;
                    wrapper.Simulator = simulator;
                    ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);
                }
            }

            // Explicit handler next
            if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null)
            {
                CapsCallbackWrapper wrapper;
                wrapper.Callback  = callback;
                wrapper.CapsEvent = capsEvent;
                wrapper.Message   = message;
                wrapper.Simulator = simulator;
                ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);

                specialHandler = true;
            }

            if (!specialHandler)
            {
                Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client);
            }
        }
 private void StartDisplayNameChage(string name)
 {
     ThreadPool.QueueUserWorkItem(sync =>
     {
         Client.Avatars.GetDisplayNames(new List <UUID>()
         {
             Client.Self.AgentID
         },
                                        (success, names, badIDs) =>
         {
             if (!success || names.Length < 1)
             {
                 UpdateStatus("Failed to get curret name");
             }
             else
             {
                 Client.Self.SetDisplayName(names[0].DisplayName, name);
             }
         }
                                        );
     }
                                  );
 }
Exemple #20
0
        /// <summary>
        /// Handle Instant Messages
        /// </summary>
        /// <param name="im"></param>
        /// <param name="simulator"></param>
        void OnInstantMessage(object sender, InstantMessageEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(sync =>
            {
                Thread.Sleep(100);     // Give tab a chance to show up
                IMSession sess = null;
                string groupName;

                // All sorts of things come in as a instant messages. For actual messages
                // we need to match them up with an existing Conversation.  IM Conversations
                // are keyed by the name of the group or individual involved.
                switch (e.IM.Dialog)
                {
                case InstantMessageDialog.MessageFromAgent:
                    if (control.instance.Groups.ContainsKey(e.IM.IMSessionID))
                    {
                        // Message from a group member
                        groupName = control.instance.Groups[e.IM.IMSessionID].Name;
                        sess      = (IMSession)control.converse.GetConversation(groupName);
                        if (sess != null)
                        {
                            sess.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                        }
                        else
                        {
                            Talker.Say(e.IM.FromAgentName + ", " + e.IM.Message);
                        }
                    }
                    else if (e.IM.BinaryBucket.Length >= 2)
                    {
                        // Ad-hoc friend conference
                        sess = (IMSession)control.converse.GetConversation(Utils.BytesToString(e.IM.BinaryBucket));
                        if (sess != null)
                        {
                            sess.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                        }
                        else
                        {
                            Talker.Say(e.IM.FromAgentName + ", " + e.IM.Message);
                        }
                    }
                    else if (e.IM.FromAgentName == "Second Life")
                    {
                        Talker.Say("Second Life says " + e.IM.Message);
                    }
                    else
                    {
                        // Message from an individual
                        sess = (IMSession)control.converse.GetConversation(e.IM.FromAgentName);
                        if (sess != null)
                        {
                            sess.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                        }
                        else
                        {
                            Talker.Say(e.IM.FromAgentName + ", " + e.IM.Message);
                        }
                    }
                    break;

                case InstantMessageDialog.SessionSend:
                    if (control.instance.Groups.ContainsKey(e.IM.IMSessionID))
                    {
                        // Message from a group member
                        groupName = control.instance.Groups[e.IM.IMSessionID].Name;
                        sess      = (IMSession)control.converse.GetConversation(groupName);
                    }
                    else if (e.IM.BinaryBucket.Length >= 2)         // ad hoc friends conference
                    {
                        sess = (IMSession)control.converse.GetConversation(Utils.BytesToString(e.IM.BinaryBucket));
                    }

                    sess?.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                    break;

                case InstantMessageDialog.FriendshipOffered:
                    Talker.Say(e.IM.FromAgentName + " is offering friendship.");
                    break;

                default:
                    break;
                }
            }
                                         );
        }