Пример #1
0
 def notice(self, target, msg):
     self.raw("NOTICE %s :%s" % (target, msg))
     
     events.trigger(
         'OwnNotice', source=self.me, target=str(target), text=msg,
         network=self, window=windows.get_default(self)
         )
Пример #2
0
    def hover(self, event):
        if self.linking:
            self.clear_hover()

        hover_iter = get_iter_at_coords(self, event.x, event.y)

        if not hover_iter.ends_line():        
            h_data = get_event_at_iter(self, hover_iter)
            h_data.tolink = set()

            events.trigger("Hover", h_data)
            
            if h_data.tolink:
                buffer = self.get_buffer()
            
                offset = buffer.get_iter_at_line(
                            hover_iter.get_line()
                            ).get_offset()
                                  
                for fr, to in h_data.tolink:
                    fr = buffer.get_iter_at_offset(offset + fr)
                    to = buffer.get_iter_at_offset(offset + to)
                    
                    buffer.apply_tag_by_name("link", fr, to)
                    
                    self.linking.add(
                        (buffer.create_mark(None, fr), 
                            buffer.create_mark(None, to))
                        )
                        
                    self.get_window(
                        gtk.TEXT_WINDOW_TEXT
                        ).set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND2))
        
        self.get_pointer()
Пример #3
0
    def to_edit_mode(self, widget, event):
        if self.label not in self.get_children():
            return

        if getattr(event, 'button', None) == 3:
            c_data = events.data(window=self.win, menu=[])
            events.trigger("NickEditMenu", c_data)

            if c_data.menu:
                menu = gtk.Menu()
                for item in menu_from_list(c_data.menu):
                    menu.append(item)
                menu.show_all()
                menu.popup(None, None, None, event.button, event.time)
        
        else:
            entry = gtk.Entry()
            entry.set_text(self.label.get_text())
            entry.connect('activate', self.nick_change)
            entry.connect('focus-out-event', self.to_show_mode)

            self.remove(self.label)
            self.add(entry)
            self.window.set_cursor(None)
                
            entry.show()
            entry.grab_focus()
Пример #4
0
    def popup(self, menu):    
        hover_iter = get_iter_at_coords(self, *self.hover_coords)
       
        menuitems = []
        if not hover_iter.ends_line():
            c_data = get_event_at_iter(self, hover_iter)
            c_data.menu = []
            
            events.trigger("RightClick", c_data)
            
            menuitems = c_data.menu
            
        if not menuitems:
            c_data = events.data(menu=[])
            events.trigger("MainMenu", c_data)
            
            menuitems = c_data.menu

        for child in menu.get_children():
            menu.remove(child)
        
        for item in menu_from_list(menuitems):
            menu.append(item)
            
        menu.show_all()
Пример #5
0
 def connect(self):
     if not self.status:
         self.status = CONNECTING
         
         self.source = ui.fork(self.on_dns, socket.getaddrinfo, self.server, self.port, 0, socket.SOCK_STREAM)
         
         events.trigger('Connecting', network=self)
Пример #6
0
 def msg(self, target, msg):
     self.raw("PRIVMSG %s :%s" % (target, msg))
     
     events.trigger(
         'OwnText', source=self.me, target=str(target), text=msg,
         network=self, window=windows.get_default(self)
         )
Пример #7
0
def onClose(e):
    nwindows = list(windows.get_with(network=e.window.network))
    
    if isinstance(e.window, windows.ChannelWindow): 
        cwindows = list(windows.get_with(
                            network=e.window.network,
                            wclass=windows.ChannelWindow
                            ))
        
        #if we only have one window for the network, don't bother to part as
        # we'll soon be quitting anyway
        if len(nwindows) != 1 and irc_script.ischan(e.window.network, e.window.id):
            e.window.network.part(e.window.id) 
    
    if len(nwindows) == 1:
        events.trigger("CloseNetwork", window=e.window, network=e.window.network)
    
    elif isinstance(e.window, windows.StatusWindow) and conf.get('status'):
        events.trigger("CloseNetwork", window=e.window, network=e.window.network)
        for window in nwindows:
            if window != e.window:
                window.close()
        
    if len(windows.manager) == 1:
        windows.new(windows.StatusWindow, irc.Network(), "status")
Пример #8
0
    def build_urk_menu(self, *args):
        data = events.data(menu=[])
        events.trigger("MainMenu", data)

        menu = self.urk_submenu
        for child in menu.get_children():
            menu.remove(child)
        for item in menu_from_list(data.menu):
            menu.append(item)
        menu.show_all()
Пример #9
0
    def trigger_start():
        events.trigger("Start")
        
        window = windows.manager.get_active()
        
        if not window:
           window = windows.new(windows.StatusWindow, irc.Network(), "status")
           window.activate()

        events.run(command, window, window.network)
Пример #10
0
def change_nick(network, nick):
    if not network.status:
        events.trigger(
            'Nick',
            network=network, window=windows.get_default(network),
            source=network.me, target=nick, address='', text=nick
            )
        network.nicks[0] = nick
        network.me = nick
    else:
        network.raw('NICK :%s' % nick)
Пример #11
0
    def mouseup(self, event):
        if not self.get_buffer().get_selection_bounds():
            if event.button == 1:
                hover_iter = get_iter_at_coords(self, event.x, event.y)
            
                if not hover_iter.ends_line():
                    c_data = get_event_at_iter(self, hover_iter)

                    events.trigger("Click", c_data)
                
            if self.is_focus():
                self.win.focus()
Пример #12
0
def setupRaw(e):
    if not e.done and e.msg[1] in ('PRIVMSG', 'NOTICE') and \
          e.text.startswith('\x01') and e.text.endswith('\x01'):
        e_data = events.data(**e.__dict__)
        e_data.text = e.text[1:-1]
        tokens = e_data.text.split(' ')
        e_data.name = tokens[0].upper()
        e_data.args = tokens[1:]
        if e.msg[1] == 'PRIVMSG':
            events.trigger('Ctcp', e_data)
        else:
            events.trigger('CtcpReply', e_data)
        e.done = True
Пример #13
0
 def entered_text(self, ctrl):
     #FIXME: move this logic into Window
     for line in self.text.splitlines():
         if line:
             e_data = events.data(
                         window=self.win, network=self.win.network,
                         text=line, ctrl=ctrl
                         )
             events.trigger('Input', e_data)
             
             if not e_data.done:
                 events.run(line, self.win, self.win.network)
     
     self.text = ''
Пример #14
0
    def tab_popup(self, event):
        if event.button == 3: # right click
            c_data = events.data(window=self.win, menu=[])
            events.trigger("WindowMenu", c_data)

            c_data.menu += [
                None,
                ("Close", gtk.STOCK_CLOSE, self.win.close),
                ]
            
            menu = gtk.Menu()
            for item in menu_from_list(c_data.menu):
                menu.append(item)
            menu.show_all()
            menu.popup(None, None, None, event.button, event.time)
Пример #15
0
def _delay(event, data, seconds, date, doc_id=None):
    db = DB()
    core = db.core()
    if not doc_id:
        doc = {'element': 'sched',
            'type': 'at',
            'event': dumps(event.elements()),
            'data': dumps(data),
            'date': date}
        doc_id = core.insert(doc)

    if seconds > 0:
        sleep(float(seconds))
    trigger(event, data)
    core.remove(doc_id)
Пример #16
0
 def on_connect(self, result, error):
     if error:
         self.disconnect(error=error[1])
         #we should immediately retry if we failed to open the socket and there are hosts left
         if self.status == DISCONNECTED and not self.failedlasthost:
             windows.get_default(self).write("* Retrying with next available host")
             self.connect()
     else:
         self.source = source = ui.Source()
         self.status = INITIALIZING
         self.failedhosts[:] = ()
         
         events.trigger('SocketConnect', network=self)
         
         if source.enabled:
             self.source = ui.fork(self.on_read, self.socket.recv, 8192)
Пример #17
0
def setupCtcp(e):
    if not e.done:
        if e.name == 'ACTION':
            e_data = events.data(**e.__dict__)
            e_data.text = ' '.join(e.args)
            events.trigger('Action', e_data)
            e.done = True
            e.quiet = True
        elif e.name == 'PING':
            ctcp_reply(e.network, e.source, e.text)
            e.done = True
        elif e.name == 'VERSION':
            ctcp_reply(e.network, e.source, 'VERSION %s - %s' % (urk.long_version, urk.website))
            e.done = True
        elif e.name == 'TIME':
            ctcp_reply(e.network, e.source, 'TIME %s' % time.asctime())
            e.done = True
Пример #18
0
def _delay(event, data, seconds, date, doc_id=None):
    db = DB()
    core = db.core()
    if not doc_id:
        doc = {
            'element': 'sched',
            'type': 'at',
            'event': dumps(event.elements()),
            'data': dumps(data),
            'date': date
        }
        doc_id = core.insert(doc)

    if seconds > 0:
        sleep(float(seconds))
    trigger(event, data)
    core.remove(doc_id)
Пример #19
0
def onRightClick(e):
    set_target(e)

    # nick on this channel
    if is_nick(e):
        make_nick_menu(e, e._target)

    elif is_url(e):
        if e._target.startswith('www'):
            e._target = 'http://%s' % e._target
    
        def copy_to():
            # copy to clipboard
            ui.set_clipboard(e._target)
            
        e.menu += [('Copy', copy_to)]
        
    elif is_chan(e):
        e.channel = e._target
        e.network = e.window.network
        events.trigger('ChannelMenu', e) 
Пример #20
0
 def click(self, event):
     if event.button == 3:
         x, y = event.get_coords()
 
         (data,), path, x, y = self.get_path_at_pos(int(x), int(y))
     
         c_data = events.data(window=self.win, data=self[data], menu=[])
     
         events.trigger("ListRightClick", c_data)
         
         if c_data.menu:
             menu = gtk.Menu()
             for item in menu_from_list(c_data.menu):
                 menu.append(item)
             menu.show_all()
             menu.popup(None, None, None, event.button, event.time)
     
     elif event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
         x, y = event.get_coords()
 
         (data,), path, x, y = self.get_path_at_pos(int(x), int(y))
     
         events.trigger("ListDoubleClick", window=self.win, target=self[data])
Пример #21
0
 def got_msg(self, msg):
     pmsg = parse_irc(msg, self.server)
 
     e_data = events.data(
                 raw=msg,
                 msg=pmsg,
                 text=pmsg[-1],
                 network=self,
                 window=windows.get_default(self)
                 )
     
     if "!" in pmsg[0]:
         e_data.source, e_data.address = pmsg[0].split('!',1)
         
     else:
         e_data.source, e_data.address = pmsg[0], ''
     
     if len(pmsg) > 2:
         e_data.target = pmsg[2]
     else:
         e_data.target = pmsg[-1]
     
     events.trigger('Raw', e_data)
Пример #22
0
 def disconnect(self, error=None):
     if self.socket:
         self.socket.close()
     
     if self.source:
         self.source.unregister()
         self.source = None
     
     self.socket = None
     
     self.status = DISCONNECTED
     
     #note: connecting from onDisconnect is probably a Bad Thing
     events.trigger('Disconnect', network=self, error=error)
     
     #trigger a nick change if the nick we want is different from the one we
     # had.
     if self.me != self.nicks[0]:
         events.trigger(
             'Nick', network=self, window=windows.get_default(self),
             source=self.me, target=self.nicks[0], address='',
             text=self.nicks[0]
             )
         self.me = self.nicks[0]
Пример #23
0
    def keypress(self, event):
        keychar = (
            (gtk.gdk.CONTROL_MASK, '^'),
            (gtk.gdk.SHIFT_MASK, '+'),
            (gtk.gdk.MOD1_MASK, '!')
            )

        key = ''
        for keymod, char in keychar:
            # we make this an int, because otherwise it leaks
            if int(event.state) & keymod:
                key += char
        key += gtk.gdk.keyval_name(event.keyval)

        events.trigger('KeyPress', key=key, string=event.string, window=self.win)

        if key == "^Return":
            self.entered_text(True)
        
        up = gtk.gdk.keyval_from_name("Up")
        down = gtk.gdk.keyval_from_name("Down")
        tab = gtk.gdk.keyval_from_name("Tab")

        return event.keyval in (up, down, tab)
Пример #24
0
def run(task, inputs=None, outputs=None, fetch=True, status=None, **kwargs):
    """
    Run a task with the specified I/O bindings.

    :param task: Specification of the task to run.
    :type task: dict
    :param inputs: Specification of how input objects should be fetched
        into the runtime environment of this task.
    :type inputs: dict
    :param outputs: Specification of what should be done with outputs
        of this task.
    :type outputs: dict
    :param write_script: If ``True`` task scripts will be written to file before
        being passed to ``exec``. This improves interactive debugging with
        tools such as ``pdb`` at the cost of additional file I/O. Note that
        when passed to run *all* tasks will be written to file including
        validation and conversion tasks.
    :param fetch: If ``True`` will perform a fetch on the input before
        running the task (default ``True``).
    :param status: Job status to update to during execution of this task.
    :type status: girder_worker.utils.JobStatus
    :returns: A dictionary of the form ``name: binding`` where ``name`` is
        the name of the output and ``binding`` is an output binding of the form
        ``{'data': data}``. The ``'data'`` field may be absent if an output URI
        was provided. Instead, those outputs will be saved to that URI and the
        output binding will contain the location in the ``'uri'`` field.
    """
    inputs = inputs or {}
    outputs = outputs or {}

    task_inputs = {_extractId(d): d for d in task.get('inputs', ())}
    task_outputs = {_extractId(d): d for d in task.get('outputs', ())}
    mode = task.get('mode', 'python')

    if mode not in _task_map:
        raise Exception('Invalid mode: %s' % mode)

    job_mgr = kwargs.get('_job_manager')

    info = {
        'task': task,
        'task_inputs': task_inputs,
        'task_outputs': task_outputs,
        'mode': mode,
        'inputs': inputs,
        'outputs': outputs,
        'status': status,
        'job_mgr': job_mgr,
        'kwargs': kwargs
    }
    events.trigger('run.before', info)

    try:
        # If some inputs are not there, fill in with defaults
        _validateInputs(task_inputs, inputs)

        for name, d in inputs.iteritems():
            task_input = task_inputs[name]
            if task_input.get('stream'):
                continue  # this input will be fetched as a stream

            if fetch:
                if status == JobStatus.RUNNING and 'data' not in d:
                    set_job_status(job_mgr, JobStatus.FETCHING_INPUT)
                d['data'] = io.fetch(d, **dict({'task_input': task_input}, **kwargs))

            events.trigger('run.handle_input', {
                'info': info,
                'task_input': task_input,
                'input': d,
                'name': name
            })

            if 'script_data' not in d:
                d['script_data'] = d['data']

        for name, task_output in task_outputs.iteritems():
            if name not in outputs:
                outputs[name] = {}

        # Set the appropriate job status flag
        set_job_status(job_mgr, status)

        # Actually run the task for the given mode
        _task_map[mode](
            task=task, inputs=inputs, outputs=outputs, task_inputs=task_inputs,
            task_outputs=task_outputs, **kwargs)

        for name, task_output in task_outputs.iteritems():
            if task_output.get('stream'):
                continue  # this output has already been sent as a stream

            output = outputs[name]
            e = events.trigger('run.handle_output', {
                'info': info,
                'task_output': task_output,
                'output': output,
                'outputs': outputs,
                'name': name
            })

            if not e.default_prevented:
                data = outputs[name]['script_data']

                if status == JobStatus.RUNNING:
                    set_job_status(job_mgr, JobStatus.PUSHING_OUTPUT)
                io.push(data, outputs[name], **dict({'task_output': task_output}, **kwargs))

            output.pop('script_data', None)

        events.trigger('run.after', info)

        return outputs
    except StateTransitionException:
        if job_mgr:
            status = job_mgr.refreshStatus()
            # If we are canceling we want to stay in that state, otherwise raise
            # the exception
            if status != JobStatus.CANCELING:
                raise
        else:
            raise
    finally:
        events.trigger('run.finally', info)
Пример #25
0
def run(task, inputs=None, outputs=None, auto_convert=True, validate=True,
        fetch=True, status=None, **kwargs):
    """
    Run a task with the specified I/O bindings.

    :param task: Specification of the task to run.
    :type task: dict
    :param inputs: Specification of how input objects should be fetched
        into the runtime environment of this task.
    :type inputs: dict
    :param outputs: Speficiation of what should be done with outputs
        of this task.
    :type outputs: dict
    :param auto_convert: If ``True`` (the default), perform format conversions
        on inputs and outputs with :py:func:`convert` if they do not
        match the formats specified in the input and output bindings.
        If ``False``, an expection is raised for input or output bindings
        do not match the formats specified in the analysis.
    :param validate: If ``True`` (the default), perform input and output
        validation with :py:func:`isvalid` to ensure input bindings are in the
        appropriate format and outputs generated by the script are
        formatted correctly. This guards against dirty input as well as
        buggy scripts that do not produce the correct type of output. An
        invalid input or output will raise an exception. If ``False``, perform
        no validation.
    :param write_script: If ``True`` task scripts will be written to file before
        being passed to ``exec``. This improves interactive debugging with
        tools such as ``pdb`` at the cost of additional file I/O. Note that
        when passed to run *all* tasks will be written to file including
        validation and conversion tasks.
    :param fetch: If ``True`` will perform a fetch on the input before
        running the task (default ``True``).
    :param status: Job status to update to during execution of this task.
    :type status: girder_worker.utils.JobStatus
    :returns: A dictionary of the form ``name: binding`` where ``name`` is
        the name of the output and ``binding`` is an output binding of the form
        ``{'format': format, 'data': data}``. If the `outputs` param
        is specified, the formats of these bindings will match those given in
        `outputs`. Additionally, ``'data'`` may be absent if an output URI
        was provided. Instead, those outputs will be saved to that URI and
        the output binding will contain the location in the ``'uri'`` field.
    """
    def extractId(spec):
        return spec['id'] if 'id' in spec else spec['name']

    if inputs is None:
        inputs = {}

    task_inputs = {extractId(d): d for d in task.get('inputs', ())}
    task_outputs = {extractId(d): d for d in task.get('outputs', ())}
    mode = task.get('mode', 'python')

    if mode not in _task_map:
        raise Exception('Invalid mode: %s' % mode)

    job_mgr = kwargs.get('_job_manager')

    info = {
        'task': task,
        'task_inputs': task_inputs,
        'task_outputs': task_outputs,
        'mode': mode,
        'inputs': inputs,
        'outputs': outputs,
        'auto_convert': auto_convert,
        'validate': validate,
        'kwargs': kwargs
    }
    events.trigger('run.before', info)

    try:
        # If some inputs are not there, fill in with defaults
        for name, task_input in task_inputs.iteritems():
            if name not in inputs:
                if 'default' in task_input:
                    inputs[name] = task_input['default']
                else:
                    raise Exception(
                        'Required input \'%s\' not provided.' % name)

        for name, d in inputs.iteritems():
            task_input = task_inputs[name]
            if task_input.get('stream'):
                continue  # this input will be fetched as a stream

            # Fetch the input
            if fetch:
                if status == JobStatus.RUNNING and 'data' not in d:
                    _job_status(job_mgr, JobStatus.FETCHING_INPUT)
                d['data'] = io.fetch(
                    d, **dict({'task_input': task_input}, **kwargs))

            # Validate the input
            if validate and not isvalid(
                    task_input['type'], d,
                    **dict(
                        {'task_input': task_input, 'fetch': False}, **kwargs)):
                raise Exception(
                    'Input %s (Python type %s) is not in the expected type '
                    '(%s) and format (%s).' % (
                        name, type(d['data']), task_input['type'], d['format'])
                    )

            # Convert data
            if auto_convert:
                try:
                    converted = convert(
                        task_input['type'], d, {'format': task_input['format']},
                        status=JobStatus.CONVERTING_INPUT,
                        **dict(
                            {'task_input': task_input, 'fetch': False},
                            **kwargs))
                except Exception, e:
                    raise Exception('%s: %s' % (name, str(e)))

                d['script_data'] = converted['data']
            elif not validate or (d.get('format', task_input.get('format')) ==
                                  task_input.get('format')):
                d['script_data'] = d['data']
            else:
Пример #26
0
                        d['format'])
                    )

            # We should consider refactoring the logic below, reasoning about
            # the paths through this code is difficult, since this logic is
            # entered by 'run', 'isvalid', and 'convert'.
            if auto_convert:
                outputs[name] = convert(
                    task_output['type'], script_output, d,
                    status=JobStatus.CONVERTING_OUTPUT,
                    **dict({'task_output': task_output}, **kwargs))
            elif not validate or d['format'] == task_output['format']:
                data = d['script_data']

                if status == JobStatus.RUNNING:
                    _job_status(job_mgr, JobStatus.PUSHING_OUTPUT)
                io.push(
                    data, d, **dict({'task_output': task_output}, **kwargs))
            else:
                raise Exception('Expected exact format match but %s != %s.' % (
                    d['format'], task_output['format']))

            if 'script_data' in outputs[name]:
                del outputs[name]['script_data']

        events.trigger('run.after', info)

        return outputs
    finally:
        events.trigger('run.finally', info)
Пример #27
0
 def raw(self, msg):
     events.trigger("OwnRaw", network=self, raw=msg)
     
     if self.status >= INITIALIZING:
         self.socket.send(msg + "\r\n")
Пример #28
0
def onWindowMenu(e):
    if isinstance(e.window, windows.ChannelWindow):
        e.channel = e.window.id
        e.network = e.window.network
        events.trigger('ChannelMenu', e)
Пример #29
0
def emote(network, user, msg):
    network.raw("PRIVMSG %s :\x01ACTION %s\x01" % (user, msg))
    events.trigger(
        'OwnAction', network=network, window=windows.get_default(network),
        source=network.me, target=str(user), text=msg
        )
Пример #30
0
 def window_change(notebook, _wptr, page_num):
     events.trigger("Active", window=notebook.get_nth_page(page_num))
Пример #31
0
 def super_window_change(self, event):
     if event.type == gtk.gdk.FOCUS_CHANGE and event.in_:
         window = windows.manager.get_active()
     
         if window:
             events.trigger('SuperActive', window=window)
Пример #32
0
 def exit(self, *args):
     events.trigger("Exit")
     gtk.main_level() and gtk.main_quit()