Example #1
0
def main():
    logging.basicConfig()
    logging.getLogger().setLevel(logging.INFO)
    # Using the correct encoding when printing
    sys.stdout = codecs.getwriter('mbcs' if os.name == 'nt' and sys.stdout.isatty() else 'utf-8')(sys.stdout, 'replace')
    set_agent('(PrivateChatSession; http://dev.ivybits.tk/projects/hal/)')

    try:
        sys.argv.remove('-d')
    except ValueError:
        pass
    else:
        from xail import main
        main.DEBUG_MODE = True
        logger.warning('Using debug mode!')

    try:
        dir = sys.argv[1]
    except IndexError:
        dir = '.'
    
    hal = HAL()

    def loadengine(pattern, name):
        engine = getattr(hal.xail, name)
        for file in glob(os.path.join(dir, pattern)):
            logger.info('%s Engine: Loading %s', name, file)
            engine.load(io.open(file, encoding='utf-8'))
    loadengine('*.gen', 'substr')
    loadengine('*.mtx', 'matrix')
    loadengine('*.rgx', 'regex')

    for file in glob(os.path.join(dir, '*.xail')):
        logger.info('Loading %s', file)
        hal.feed(io.open(file, encoding='utf-8'))

    user = getuser()
    prompt = '-%s:' % user
    halpro = '-HAL:'
    length = max(len(prompt), len(halpro))
    prompt.ljust(length)
    halpro.ljust(length)
    prompt += ' '
    context = {'USERNAME': user}
    print(halpro, 'Hello %s. I am HAL %s.'%(user, hal.version))
    print()
    try:
        while True:
            line = raw_input(prompt)
            try:
                print(halpro, hal.answer(line, context))
            except IOError as e:
                if e.errno != 0:
                    raise
                print() # It gets error 0 when some characters can't be displayed
            print()
    except (EOFError, KeyboardInterrupt):
        pass
    finally:
        print(halpro, 'Goodbye.')
Example #2
0
File: tkgui.py Project: IvyBits/HAL
class Application(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.root = master
        self.grid(sticky='WENS')
        self.createWidgets()
        self.queue = Queue()
        
        self.after(100, self.update_console)
        Thread(target=self.bootstrap).start()
    
    def write(self, text):
        self.queue.put(text)
        sys.stdout.write(text)
    
    def clear(self):
        self.queue.put(None)
    
    def update_console(self):
        try:
            while True:
                line = self.queue.get_nowait()
                if line is None:
                    self.console.delete(1.0, 'end')
                else:
                    self.console.insert('end', str(line))
                self.console.see('end')
                self.console.update_idletasks()
        except Empty:
            pass
        self.after(100, self.update_console)
    
    def bootstrap(self):
        from HAL import HAL

        write = self.write
        timer = self.timer = clock if os.name == 'nt' else time
        begin = timer()
        
        write('Initializing Engine...')
        self.hal = HAL()
        write(' done\n')

        try:
            dirname = sys.argv[1]
        except IndexError:
            dirname = os.getcwd()

        # Here's the legacy loading
        def loadfiles(pattern, attr, name):
            engine = getattr(self.hal.xail, attr)
            for file in glob(os.path.join(dirname, pattern)):
                write('%s Engine: Loading %s...' % (name, file))
                engine.load(io.open(file, encoding='utf-8'))
                write(' Done\n')
        loadfiles('*.gen', 'matrix', 'Matrix')
        loadfiles('*.mtx', 'substr', 'Substring')
        loadfiles('*.rgx', 'regex', 'Regex')
        
        # New unified XAIL loading
        files = glob(os.path.join(dirname, '*.xail'))
        max_length = max(map(len, files))
        for file in files:
            write('Loading %s' % file + ' ' * (max_length - len(file)) + '...')
            start = timer()
            self.hal.feed(io.open(file, encoding='utf-8'))
            write(' Finished in %8.2f ms\n' % ((timer() - start) * 1000))
        write('\n')

        user = getuser()
        prompt = '-%s: '%user
        halpro = '-HAL: '
        length = max(len(prompt), len(halpro))
        prompt.ljust(length)
        halpro.ljust(length)
        self.prompt, self.halpro = prompt, halpro
        self.context = {'USERNAME': user}

        write('Loaded in %.2f seconds.\n\n' % (timer() - begin))
        write(halpro + 'Hello %s. I am HAL %s.' % (user, self.hal.version) + '\n\n')

        self.entry.bind('<Return>', self.answer)
    
    def answer(self, e=None):
        write = self.write
        input = self.input.get()
        answer = self.hal.answer(input, self.context)
        write(self.prompt + input + '\n')
        write(self.halpro + answer + '\n\n')
        self.input.set('')
    
    def createWidgets(self):
        font_console = Font(family='Consolas', size=11)
        self.input = tk.StringVar()
        self.config(borderwidth=10)

        self.console = ScrolledText(self, font=font_console, state='normal')
        self.entry = ttk.Entry(self, textvariable=self.input, font=font_console)
        submit = ttk.Button(self, text='Submit')

        self.console.grid(columnspan=3, sticky='WENS')
        tk.LabelFrame(self, height=5).grid(row=1)
        self.entry.grid(row=2, sticky='WE')
        tk.LabelFrame(self, width=5).grid(row=2, column=1)
        submit.grid(row=2, column=2)
        submit['command'] = self.answer
        
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        self.root.wm_title('HAL')
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=0)
        self.rowconfigure(0, weight=1)