Beispiel #1
0
 def Close(self):
     eg.PrintDebugNotice("closing %s" % self.path)
     if self.isStarted:
         self.Stop()
     if not self.initFailed:
         try:
             self.instance.__close__()
         except:
             import traceback
             eg.PrintDebugNotice(traceback.format_exc())
Beispiel #2
0
def DeInit():
    eg.PrintDebugNotice("stopping threads")
    eg.actionThread.Func(eg.actionThread.StopSession)()
    eg.scheduler.Stop()
    eg.actionThread.Stop()
    eg.eventThread.Stop()
    eg.PrintDebugNotice("shutting down")
    eg.config.Save()
    eg.messageReceiver.Stop()
    if eg.dummyAsyncoreDispatcher:
        eg.dummyAsyncoreDispatcher.close()
Beispiel #3
0
    def run(self, security_attributes):
        """
        Handles the creation of the pipe.


        Windows SACL and DACL data for creating the
            pipe.
        :type security_attributes: win32security.SECURITY_ATTRIBUTES instance
        :return: None
        :rtype: None
        """
        import eg

        eg.PrintDebugNotice('Named Pipe: Creating pipe {0}'.format(
            self._pipe_id))

        pipe = win32pipe.CreateNamedPipe(
            r'\\.\pipe\eventghost', PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_WAIT | PIPE_READMODE_MESSAGE,
            PIPE_UNLIMITED_INSTANCES, 4096, 4096, 5, security_attributes)

        win32pipe.ConnectNamedPipe(pipe, None)
        data = win32file.ReadFile(pipe, 4096)
        self.is_waiting = False

        if not self._parent.running_pipes[-1].is_waiting == self:
            self._parent.running_pipes += [
                Pipe(self._parent, self._parent.get_pipe_id(),
                     security_attributes)
            ]

        eg.PrintDebugNotice('Pipe {0}: Data received'.format(self._pipe_id))

        if data[0] == 0:
            event = threading.Event()
            res = ['']

            self._parent.process_command.add(self._pipe_id, data[1], res,
                                             event)

            while not event.isSet():
                pass

            win32file.WriteFile(pipe, str(repr(res[0])))
            win32pipe.DisconnectNamedPipe(pipe)
            win32file.CloseHandle(pipe)
        else:
            try:
                raise NamedPipeDataError('Pipe {0}: Unknown Error: {1}'.format(
                    self._pipe_id, str(data)))
            except NamedPipeDataError:
                traceback.print_exc()
        self._parent.running_pipes.remove(self)
Beispiel #4
0
    def ProcessMsg(self, line, icon):
        try:
            if self.fired and self.actionArgs.onlyOnce:
                return

            found, idx = False, -1
            for i in range(len(self.searchArgs.watchMsgTypes)):
                if icon == mtIcons[i][0]:
                    found = True
                    if self.searchArgs.watchMsgTypes[i]:
                        idx = i
                    break

            if (not found and not self.searchArgs.watchMsgTypes[MT_ACTION]
                    or found and idx == -1):
                return
            elif not found and self.searchArgs.watchMsgTypes[MT_ACTION]:
                idx = MT_ACTION

            l = line if self.searchArgs.caseSensitive else line.lower()
            if (self.searchArgs.wholeMessage and l == self.monStr
                    or not self.searchArgs.wholeMessage
                    and l.find(self.monStr) >= 0):
                self.fired = True
                eg.PrintDebugNotice("LogMonitor: Analyzed line: " + line)
                eg.PrintDebugNotice("LogMonitor: Found search string '" +
                                    self.monStr +
                                    "' in current log message of type '" +
                                    mtIcons[idx][1] + "'")

                eg.PrintDebugNotice("payload = self.ParseMsg(line)")
                payload = self.ParseMsg(line)

                if self.actionArgs.fireEvent and self.monEvt:
                    eg.PrintDebugNotice(
                        "LogMonitor: => fire event '" + self.monEvt +
                        "' with payload=", repr(payload))
                    p = payload if self.actionArgs.eventPayload else None
                    self.plugin.TriggerEvent(self.monEvt, payload=p)

                if self.actionArgs.setVariable and self.actionArgs.variableName != '':
                    exec('eg.globals.' + self.actionArgs.variableName + '=' +
                         repr(payload))

                if self.actionArgs.printToLog:
                    print payload

        except Exception, exc:
            # don't print anything (infinite loops)
            pass
 def _log_callback(self, level, time, message):
     if (self._log_level is not None and level <= self._log_level
             and level in CEC_LOG_CONSTANTS):
         level_str = CEC_LOG_CONSTANTS[level]
         eg.PrintDebugNotice("CEC %s: %s [%s]    %s" %
                             (self.name, level_str, str(time), message))
     return 0
Beispiel #6
0
 def __DoOneEvent(self):
     try:
         resultCode = MsgWaitForMultipleObjects(1, self.__events, 0, 10000,
                                                QS_ALLINPUT)
         if resultCode == WAIT_OBJECT_0:
             while 1:
                 try:
                     action = self.__queue.popleft()
                 except IndexError:
                     break
                 try:
                     self.HandleAction(action)
                 except:
                     action.PrintUnhandledException()
                 finally:
                     # if the frame reference would not be removed, the
                     # action would never be garbage collected.
                     action.callersFrame = None
         elif resultCode == WAIT_OBJECT_0 + 1:
             self.__PumpWaitingMessages()
         elif resultCode == WAIT_TIMEOUT:
             # Our timeout has elapsed.
             self.Poll()
         else:
             raise RuntimeError("unexpected win32wait return value")
     except:
         eg.PrintDebugNotice("Exception in __DoOneEvent")
         eg.PrintTraceback()
Beispiel #7
0
    def TriggerEventWait(self, suffix, payload=None, prefix="Main", source=eg):
        event = EventGhostEvent(suffix, payload, prefix, source)
        if event.source in self.filters:
            for filterFunc in self.filters[event.source]:
                if filterFunc(event) == True:
                    return event
        executed = Event()

        def Execute():
            try:
                event.Execute()
            finally:
                executed.set()

        def Transfer():
            ActionThreadCall(Execute)
            event.SetShouldEnd()

        self.AppendAction(Transfer)
        executed.wait(5.0)
        if not executed.isSet():
            if eg.debugLevel:
                eg.PrintDebugNotice("timeout TriggerEventWait")
                traceback.print_stack()
        return event
Beispiel #8
0
    def StartSession(self, filename):
        eg.eventTable.clear()
        self.corePluginInfos = []
        for guid in eg.CORE_PLUGIN_GUIDS:
            try:
                pluginInfo = eg.pluginManager.OpenPlugin(guid, None, ())
                pluginInfo.instance.__start__()
                pluginInfo.isStarted = True
                self.corePluginInfos.append(pluginInfo)
            except:  # pylint: disable-msg=W0702
                eg.PrintTraceback()
        start = clock()
        eg.document.Load(filename)
        eg.PrintDebugNotice("XML loaded in %f seconds." % (clock() - start))

        missingHardwareIds = (set(eg.WinUsb.ListDevices().iterkeys()) -
                              set(pluginInfo.info.hardwareId
                                  for pluginInfo in eg.pluginList))
        missingPlugins = [
            pluginInfo
            for pluginInfo in eg.pluginManager.database.itervalues()  # NOQA
            if pluginInfo.hardwareId in missingHardwareIds
        ]
        if missingPlugins:
            print "EventGhost has found devices on your system, that can be "
            print "handled by the following plugins and are not loaded by your"
            print "current configuration:"
            for pluginInfo in missingPlugins:
                print "   -", pluginInfo.name
            print "If you want to use them, please add the missing plugins."

        eg.programCounter = (eg.document.autostartMacro, None)
        eg.RunProgram()
Beispiel #9
0
    def RegisterPlugin(
        self,
        name = None,
        description = None,
        kind = "other",
        author = "[unknown author]",
        version = "[unknown version]",
        icon = None,
        canMultiLoad = False,
        createMacrosOnAdd = False,
        url = None,
        help = None,
        guid = "",
        hardwareId = "",
        **kwargs
    ):
        if name is None:
            name = self.pluginName
        if description is None:
            description = name
        if help is not None:
            help = "\n".join([s.strip() for s in help.splitlines()])
            help = help.replace("\n\n", "<p>")
            description += "\n\n<p>" + help
        self.name = self.englishName = unicode(name)
        self.description = self.englishDescription = unicode(description)
        self.kind = unicode(kind)
        self.author = (
            unicode(", ".join(author)) if isinstance(author, tuple)
            else unicode(author)
        )
        self.version = unicode(version)
        self.canMultiLoad = canMultiLoad
        self.createMacrosOnAdd = createMacrosOnAdd
        self.url = unicode(url) if url else url  # Added by Pako
        self.guid = guid.upper()
        if not guid:
            eg.PrintDebugNotice("missing guid in plugin: %s" % self.path)
            self.guid = self.pluginName
        self.hardwareId = hardwareId.upper()
        # get the icon if any
        if icon is not None:
            self.icon = eg.Icons.StringIcon(icon)
        else:
            iconPath = join(self.path, "icon.png")
            if exists(iconPath):
                self.icon = eg.Icons.PathIcon(iconPath)

        # try to translate name and description
        textCls = getattr(eg.text.Plugin, self.pluginName, None)
        if textCls is not None:
            self.name = getattr(textCls, "name", name)
            self.description = getattr(textCls, "description", description)

        # we are done with this plugin module, so we can interrupt further
        # processing by raising RegisterPluginException
        raise RegisterPluginException
Beispiel #10
0
 def Poll(self):
     if eg.config.limitMemory and eg.document.frame is None:
         try:
             if 0 == SetProcessWorkingSetSize(
                     self.hHandle, 3670016,
                     eg.config.limitMemorySize * 1048576):
                 #TODO: what to do here?
                 eg.PrintDebugNotice(FormatError())
                 self.__class__.Poll = self.Poll2
         except:
             self.__class__.Poll = self.Poll2
Beispiel #11
0
                    def run():
                        if isinstance(data, dict):
                            res[0] = command(**data)
                        elif isinstance(data, (tuple, list)):
                            res[0] = command(*data)

                        eg.PrintDebugNotice(
                            'Pipe {0}: Return data: {1}'.format(
                                pipe_id, str(res[0])))

                        event.set()
Beispiel #12
0
    def OnExit(self):
        if not eg.startupArguments.translate:
            eg.PrintDebugNotice("Triggering OnClose")
            egEvent = eg.eventThread.TriggerEvent("OnClose")
            while not egEvent.isEnded:
                self.Yield()

            eg.PrintDebugNotice("Calling exit functions")
            for func in self.onExitFuncs:
                eg.PrintDebugNotice(func)
                func()

            eg.PrintDebugNotice("Calling eg.DeInit()")
            eg.Init.DeInit()

        currentThread = threading.currentThread()

        while self.Pending():
            self.Dispatch()

        # try to wait till all utility threads have ended
        startTime = time.clock()
        waitTime = 0
        while True:
            threads = [
                thread for thread in threading.enumerate()
                if (thread is not currentThread
                    and thread is not eg.messageReceiver._ThreadWorker__thread
                    and not thread.isDaemon() and thread.isAlive())
            ]
            if len(threads) == 0:
                break
            waitTime = time.clock() - startTime
            if waitTime > 5.0:
                break
            while self.Pending():
                self.Dispatch()
            time.sleep(0.01)
        eg.PrintDebugNotice("Waited for threads shutdown: %f s" %
                            (time.clock() - startTime))
        if eg.debugLevel and len(threads):
            eg.PrintDebugNotice("The following threads did not terminate:")
            for thread in threads:
                eg.PrintDebugNotice(" ", thread, thread.getName())
        # destroy the TaskBarIcon, as it would otherwise stay as a ghost
        # icon in the system-tray.
        wx.TaskBarIcon.Destroy(eg.taskBarIcon)
        eg.PrintDebugNotice("Done!")
        ExitProcess(0)
Beispiel #13
0
 def MyWndProc(self, dummyHwnd, dummyMesg, wParam, lParam):
     if wParam == HSHELL_WINDOWDESTROYED:
         self.WindowDestroyedProc(None, None, lParam, None)
     elif wParam in (HSHELL_WINDOWACTIVATED, HSHELL_WINDOWCREATED, 0x8004):
         self.WindowGotFocusProc(None, None, lParam, None)
     elif wParam == HSHELL_REDRAW:
         self.WindowTitleChangedProc(None, None, lParam, None)
     elif wParam == 0x8006:
         self.WindowFlashedProc(None, None, lParam, None)
     else:
         eg.PrintDebugNotice(
             "MyWndProc unknown wParam:: 0x{:04X}".format(wParam))
     return 1
    def StartSession(self, filename):
        eg.eventTable.clear()
        self.corePluginInfos = []
        for guid in eg.CORE_PLUGIN_GUIDS:
            try:
                pluginInfo = eg.pluginManager.OpenPlugin(guid, None, ())
                pluginInfo.instance.__start__()
                pluginInfo.isStarted = True
                self.corePluginInfos.append(pluginInfo)
            except:  # pylint: disable-msg=W0702
                eg.PrintTraceback()
        start = clock()
        eg.document.Load(filename)
        eg.PrintDebugNotice("XML loaded in %f seconds." % (clock() - start))

        missingHardwareIds = (set(eg.WinUsb.ListDevices().keys()) -
                              set(pluginInfo.info.hardwareId
                                  for pluginInfo in eg.pluginList))
        missingPlugins = [
            pluginInfo
            for pluginInfo in eg.pluginManager.database.values()  # NOQA
            if pluginInfo.hardwareId in missingHardwareIds
        ]
        if missingPlugins:
            print("EventGhost has found devices on your system, that can be ")
            print(
                "handled by the following plugins and are not loaded by your")
            print("current configuration:")
            for pluginInfo in missingPlugins:
                print("   -", pluginInfo.name)
            print("If you want to use them, please add the missing plugins.")

        payload = dict(IsLocalAdmin=User.IsLocalAdmin(),
                       IsDomainLogin=User.IsDomainLogin())

        if payload['IsDomainLogin']:
            payload['IsDomainAdmin'] = User.IsDomainAdmin()

        event = eg.EventGhostEvent(prefix='Windows',
                                   suffix='User.' + User.Name(),
                                   payload=payload)
        event.Execute()
        eg.programCounter = (eg.document.autostartMacro, None)
        eg.RunProgram()
Beispiel #15
0
 def StopLoad(cls):
     for link, xmlId in cls.linkList:
         if xmlId is not None and xmlId != -1:
             if xmlId in cls.sessionId2target:
                 target = cls.sessionId2target[xmlId]
             elif xmlId in cls.id2target:
                 target = cls.id2target[xmlId]
             else:
                 eg.PrintDebugNotice("target id %d not found" % xmlId)
                 continue
             cls.id2target[target.xmlId] = target
             link.xmlId = target.xmlId
             link.target = target
             if target.dependants is None:
                 target.dependants = [link]
             else:
                 target.dependants.append(link)
             wx.CallAfter(eg.Notify, "NodeChanged", link.owner)
     del cls.linkList[:]
Beispiel #16
0
    def OnExit(self):
        if not eg.startupArguments.translate:
            eg.PrintDebugNotice("Calling exit functions")
            for func in self.onExitFuncs:
                eg.PrintDebugNotice(func)
                func()

            eg.PrintDebugNotice("Calling eg.DeInit()")
            eg.Init.DeInit()

        currentThread = threading.currentThread()

        while self.Pending():
            self.Dispatch()

        # try to wait till all utility threads have ended
        startTime = time.clock()
        waitTime = 0
        while True:
            threads = [
                thread for thread in threading.enumerate()
                if (
                    thread is not currentThread and
                    thread is not eg.messageReceiver._ThreadWorker__thread and
                    not thread.isDaemon() and
                    thread.isAlive()
                )
            ]
            if len(threads) == 0:
                break
            waitTime = time.clock() - startTime
            if waitTime > 5.0:
                break
            while self.Pending():
                self.Dispatch()
            time.sleep(0.01)
        eg.PrintDebugNotice(
            "Waited for threads shutdown: %f s" % (time.clock() - startTime)
        )
        if eg.debugLevel and len(threads):
            eg.PrintDebugNotice("The following threads did not terminate:")
            for thread in threads:
                eg.PrintDebugNotice(" ", thread, thread.getName())
        eg.PrintDebugNotice("Done!")
        ExitProcess(0)
Beispiel #17
0
    def __init__(self):
        Section.__init__(self)
        configDir = eg.configDir
        if not os.path.exists(configDir):
            os.makedirs(configDir)
        configFilePath = os.path.join(configDir, "config.py")
        self._configFilePath = configFilePath

        if exists(configFilePath):
            try:
                eg.ExecFile(configFilePath,
                            {"__metaclass__": MakeSectionMetaClass},
                            self.__dict__)
            except:
                if eg.debugLevel:
                    raise
        else:
            eg.PrintDebugNotice('File "%s" does not exist.' % configFilePath)
        if self.language == "Deutsch":
            self.language = "de_DE"
Beispiel #18
0
    def __init__(self):
        Section.__init__(self)
        configDir = eg.configDir
        if not os.path.exists(configDir):
            os.makedirs(configDir)
        configFilePath = os.path.join(configDir, "config.py")
        self._configFilePath = configFilePath

        # BUG: of the python function 'ExecFile'. It doesn't handle unicode
        # filenames right.
        configFilePath = configFilePath.encode(sys.getfilesystemencoding())

        if exists(configFilePath):
            try:
                eg.ExecFile(configFilePath,
                            {"__metaclass__": MakeSectionMetaClass},
                            self.__dict__)
            except:
                if eg.debugLevel:
                    raise
        else:
            eg.PrintDebugNotice('File "%s" does not exist.' % configFilePath)
Beispiel #19
0
 def Close(self):
     eg.PrintDebugNotice("closing %s" % self.path)
     if self.isStarted:
         self.Stop()
     if not self.initFailed:
         self.instance.__close__()
Beispiel #20
0
 def DoOnClose():
     eg.PrintDebugNotice("Triggering OnClose")
     egEvent = eg.eventThread.TriggerEvent("OnClose")
     while not egEvent.isEnded:
         self.Yield()
Beispiel #21
0
 def TimeItWrapper(*args, **kwargs):
     startTime = time.clock()
     funcName, _ = GetFuncArgString(func, args, kwargs)
     res = func(*args, **kwargs)
     eg.PrintDebugNotice(funcName + " :" + repr(time.clock() - startTime))
     return res
Beispiel #22
0
    def run(self):
        """
        Processes the queued data.

        :return: None
        :rtype: None
        """
        import eg

        while True:
            self._queue_event.wait()
            self._queue_event.clear()
            while self._queue:
                pipe_id, data, res, event = self._queue.pop(0)
                if pipe_id != self._running_id:
                    self._queue += [(pipe_id, data, res, event)]
                    continue

                command = process_data(data)
                try:
                    command, data = command.split(',', 1)
                except ValueError:
                    data = '()'

                eg.PrintDebugNotice(
                    'Pipe {0}: Command: {1}, Parameters: {2}'.format(
                        pipe_id, command, data))

                command = command.strip()
                data = data.strip()

                try:
                    if '=' in command:
                        raise NamedPipeCommandError(
                            'Pipe {0}: Command not allowed: {1}'.format(
                                pipe_id, command))

                    if not data.startswith('dict') and '=' in data:
                        raise NamedPipeDataError(
                            'Pipe {0}: Data not allowed: {1}'.format(
                                pipe_id, data))

                    if (data[0] not in ('(', '[', '{')
                            and not data.startswith('dict')):
                        raise NamedPipeDataError(
                            'Pipe {0}: Data not allowed: {1}'.format(
                                pipe_id, data))

                    try:
                        command = eval(command.split('(', 1)[0])
                    except SyntaxError:
                        raise NamedPipeDataError(
                            'Pipe {0}: Command malformed: {1}'.format(
                                pipe_id, command))
                    else:
                        if isinstance(command, (str, unicode)):
                            raise NamedPipeCommandError(
                                'Pipe {0}: Command does not exist: {1}'.format(
                                    pipe_id, command))
                    try:
                        data = eval(data)
                    except SyntaxError:
                        raise NamedPipeDataError(
                            'Pipe {0}: Data malformed: {1}'.format(
                                pipe_id, data))

                    if not isinstance(data, (dict, list, tuple)):
                        raise NamedPipeDataError(
                            'Pipe {0}: Data malformed: {1}'.format(
                                pipe_id, str(data)))

                except NamedPipeException:
                    traceback.print_exc()
                    event.set()
                else:

                    def run():
                        if isinstance(data, dict):
                            res[0] = command(**data)
                        elif isinstance(data, (tuple, list)):
                            res[0] = command(*data)

                        eg.PrintDebugNotice(
                            'Pipe {0}: Return data: {1}'.format(
                                pipe_id, str(res[0])))

                        event.set()

                    wx.CallAfter(run)
                    event.wait()
                self._running_id = pipe_id + 1
Beispiel #23
0
 def LogItWrapper(*args, **kwargs):
     funcName, argString = GetFuncArgString(func, args, kwargs)
     eg.PrintDebugNotice(funcName + argString)
     return func(*args, **kwargs)
Beispiel #24
0
def Msg(msg):
    try:
        eg.PrintDebugNotice(str(msg))
    except:
        pass
Beispiel #25
0
    def ParseMsg(self, line):
        payload = None

        try:
            eg.PrintDebugNotice("ParseMsg self.parseArgs.searchMode",
                                self.parseArgs.searchMode)
            if self.parseArgs.searchMode == SM_KEEP_FULL:
                payload = line

            elif self.parseArgs.searchMode == SM_FIND_NUMBER:
                strings = re.findall(r"\d*\.\d+|\d*\,\d+|\d+", line)
                numbers = []
                for s in strings:
                    s = s.replace(',', '.')
                    if s.find('.') >= 0:
                        numbers.append(float(s))
                    else:
                        numbers.append(int(s))

                if len(numbers) == 0:
                    payload = None
                elif len(numbers) == 1:
                    payload = numbers[0]
                else:
                    payload = numbers

            elif self.parseArgs.searchMode == SM_GET_SUBSTR_BY_CHAR:
                strings = []
                sstr = line
                p1, p2 = 0, 0
                l1, l2 = len(self.parseArgs.searchChar1), len(
                    self.parseArgs.searchChar2)
                c1, c2 = self.parseArgs.searchChar1, self.parseArgs.searchChar2
                while p1 >= 0 and p1 < len(sstr):
                    sstr = sstr[p1:]
                    eg.PrintDebugNotice('sstr', sstr)
                    p1 = sstr.find(c1)
                    if p1 >= 0:
                        p2 = sstr.find(c2)
                        eg.PrintDebugNotice('p1', p1, 'p2', p2)
                        if p2 > p1:
                            strings.append(sstr[p1 + l1:p2])
                            p1 = p2 + l2

                if len(strings) == 0:
                    payload = None
                elif len(strings) == 1:
                    payload = strings[0]
                else:
                    payload = strings

            elif self.parseArgs.searchMode == SM_GET_SUBSTR_BY_POS:
                payload = line[self.parseArgs.searchPos1:self.parseArgs.
                               searchPos2]

            elif self.parseArgs.searchMode == SM_APPLY_REGEX:
                payload = re.findall(self.parseArgs.searchRegex, line)

        except Exception, exc:
            payload = None
            msg = "Error parsing log message <" + unicode(
                line) + ">, error=" + unicode(exc)

            eg.PrintTraceback(msg)
Beispiel #26
0
 def StopSession(self):
     actionThread.Func(actionThread.StopSession, 120)()
     eg.PrintDebugNotice("StopSession done")
Beispiel #27
0
    def run(self):

        import eg

        # This is where the permissions get created for the pipe
        eg.PrintDebugNotice('Pipe: Creating security descriptor')
        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_descriptor = win32security.SECURITY_DESCRIPTOR()
        security_descriptor.SetSecurityDescriptorDacl(1, None, 0)
        security_attributes.SECURITY_DESCRIPTOR = security_descriptor
        eg.PrintDebugNotice('Pipe 0: Creating Pipe')

        pipe = win32pipe.CreateNamedPipe(
            r'\\.\pipe\eventghost',
            PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
            PIPE_TYPE_MESSAGE | PIPE_WAIT | PIPE_READMODE_MESSAGE,
            PIPE_UNLIMITED_INSTANCES, 4096, 4096, 5, security_attributes)

        while True:
            self.is_waiting = True
            pipe_id = self.get_pipe_id()

            # creation of the pipe. once the pipe has been made it will sit
            # and wait for data to be written to the pipe. once data has been
            # written it will then read the data and close the pipe. then it
            # will parse the data sent and execute the command. It will loop
            # like this the entire time EG is running. The thread that handles
            # the pipe is a daemon thread and the thread will be terminated
            # when EG closes.

            win32pipe.ConnectNamedPipe(pipe, None)

            self.running_pipes += [self]

            if len(self.running_pipes) > 1:
                if not self.running_pipes[-1].is_waiting:
                    self.running_pipes += [
                        Pipe(self, self.get_pipe_id(), security_attributes)
                    ]
            else:
                self.running_pipes += [
                    Pipe(self, self.get_pipe_id(), security_attributes)
                ]

            data = win32file.ReadFile(pipe, 4096)
            self.is_waiting = False

            eg.PrintDebugNotice('Pipe {0}: Data received'.format(pipe_id))

            if data[0] == 0:
                event = threading.Event()
                res = ['']

                self.process_command.add(pipe_id, data[1], res, event)

                while not event.isSet():
                    pass

                win32file.WriteFile(pipe, str(repr(res[0])))
                win32pipe.DisconnectNamedPipe(pipe)

            else:
                try:
                    raise NamedPipeDataError(
                        'Pipe {0}: Unknown Error: {1}'.format(
                            pipe_id, str(data)))
                except NamedPipeDataError:
                    traceback.print_exc()
            self.running_pipes.remove(self)
Beispiel #28
0
 def __start__(self):
     eg.PrintDebugNotice("MouseEvent " + version)
     self.mouseListener = MouseEventListener(self)
     self.started = True
Beispiel #29
0
    def OnSelectionChanged(self, event):
        event.Skip()
        tree = self.tree
        item = tree.GetSelection()
        if not item.IsOk():
            return
        hwnd = tree.GetPyData(item)
        eg.PrintDebugNotice("HWND:", hwnd)
        if tree.GetItemParent(item) == tree.root:
            # only selected a program
            pid = hwnd
            hwnd = None
        else:
            pid = GetWindowThreadProcessId(hwnd)[1]

        if pid == self.lastPid and hwnd == self.lastHwnd:
            return
        self.lastPid = pid
        self.lastHwnd = hwnd
        exe = GetProcessName(pid)

        def SetOption(flag, option, value):
            checkBox, textCtrl = option
            checkBox.SetValue(flag)
            textCtrl.SetValue(value)
            textCtrl.Enable(flag)

        rootHwnd = None
        options = self.options
        SetOption(bool(exe), options[0], exe)
        if hwnd is not None:
            rootHwnd = GetAncestor(hwnd, GA_ROOT)
            targetWinName = GetWindowText(rootHwnd)
            targetWinClass = GetClassName(rootHwnd)
            SetOption(True, options[1], targetWinName)
            SetOption(True, options[2], targetWinClass)
        else:
            SetOption(False, options[1], "")
            SetOption(False, options[2], "")
        if rootHwnd is not None and rootHwnd != hwnd:
            targetWinName = GetWindowText(hwnd)
            targetWinClass = GetClassName(hwnd)
            SetOption(True, options[3], targetWinName)
            SetOption(True, options[4], targetWinClass)
            searchHwnd = hwnd
            data = [
                child
                for child in GetWindowChildsList(
                    rootHwnd,
                    tree.includeInvisible
                ) if (
                    GetClassName(child) == targetWinClass and
                    GetWindowText(child) == targetWinName
                )
            ]
            try:
                count = data.index(searchHwnd) + 1
            except:
                count = 0
        else:
            SetOption(False, options[3], "")
            SetOption(False, options[4], "")
            if rootHwnd is not None:
                data = [
                    hwnd
                    for hwnd in GetTopLevelWindowList(tree.includeInvisible)  # NOQA
                    if (
                        GetClassName(hwnd) == targetWinClass and
                        GetWindowText(hwnd) != targetWinName and
                        GetWindowThreadProcessId(hwnd)[1] == pid
                    )
                ]
                count = len(data)
            else:
                count = 0
        SetOption(count > 0, options[5], count or 1)
Beispiel #30
0
 def LogItWithReturnWrapper(*args, **kwargs):
     funcName, argString = GetFuncArgString(func, args, kwargs)
     eg.PrintDebugNotice(funcName + argString)
     result = func(*args, **kwargs)
     eg.PrintDebugNotice(funcName + " => " + repr(result))
     return result