1
0
mirror of https://github.com/TomHarte/CLK.git synced 2024-12-25 18:30:21 +00:00
CLK/Machines/Typer.cpp

87 lines
2.1 KiB
C++
Raw Normal View History

//
// Typer.cpp
// Clock Signal
//
// Created by Thomas Harte on 19/06/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "Typer.hpp"
#include <stdlib.h>
using namespace Utility;
Typer::Typer(const char *string, HalfCycles delay, HalfCycles frequency, Delegate *delegate) :
2017-03-26 18:34:47 +00:00
counter_(-delay), frequency_(frequency), string_pointer_(0), delegate_(delegate), phase_(0) {
size_t string_size = strlen(string) + 3;
string_ = (char *)malloc(string_size);
snprintf(string_, string_size, "%c%s%c", Typer::BeginString, string, Typer::EndString);
}
void Typer::run_for(const HalfCycles duration) {
2017-03-26 18:34:47 +00:00
if(string_) {
if(counter_ < 0 && counter_ + duration >= 0) {
if(!type_next_character()) {
delegate_->typer_reset(this);
}
}
counter_ += duration;
2017-03-26 18:34:47 +00:00
while(string_ && counter_ > frequency_) {
counter_ -= frequency_;
2017-03-26 18:34:47 +00:00
if(!type_next_character()) {
delegate_->typer_reset(this);
}
}
}
}
2017-03-26 18:34:47 +00:00
bool Typer::type_next_character() {
if(string_ == nullptr) return false;
2017-03-26 18:34:47 +00:00
if(delegate_->typer_set_next_character(this, string_[string_pointer_], phase_)) {
phase_ = 0;
2017-03-26 18:34:47 +00:00
if(!string_[string_pointer_]) {
free(string_);
string_ = nullptr;
return false;
}
string_pointer_++;
2017-03-26 18:34:47 +00:00
} else {
phase_++;
}
return true;
}
2017-03-26 18:34:47 +00:00
Typer::~Typer() {
free(string_);
}
#pragma mark - Delegate
2017-03-26 18:34:47 +00:00
bool Typer::Delegate::typer_set_next_character(Utility::Typer *typer, char character, int phase) {
uint16_t *sequence = sequence_for_character(typer, character);
if(!sequence) return true;
if(!phase) clear_all_keys();
2017-03-26 18:34:47 +00:00
else {
set_key_state(sequence[phase - 1], true);
return sequence[phase] == Typer::Delegate::EndSequence;
}
return false;
}
2017-03-26 18:34:47 +00:00
uint16_t *Typer::Delegate::sequence_for_character(Typer *typer, char character) {
return nullptr;
}
uint16_t *Typer::Delegate::table_lookup_sequence_for_character(KeySequence *sequences, size_t length, char character) {
size_t ucharacter = (size_t)((unsigned char)character);
if(ucharacter > (length / sizeof(KeySequence))) return nullptr;
if(sequences[ucharacter][0] == NotMapped) return nullptr;
return sequences[ucharacter];
}