repo
string
commit
string
message
string
diff
string
marcoshack/marcoshack.github.io
5cf932213f45c62e9700ba3b58e08e444633ae49
nao exibir imagens na lista de posts em telefones
diff --git a/index.html b/index.html index ebcc58c..a8943b2 100644 --- a/index.html +++ b/index.html @@ -1,24 +1,24 @@ --- layout: default title: home --- {% for post in paginator.posts %} <div class="row"> - <div class="span2"> + <div class="span2 hidden-phone"> {% if post.image != nil %} <img src="/images/{{ post.image }}" /> {% endif %} </div> <div class="span6"> <h3><a href="{{ post.url }}">{{ post.title }}</a></h3> <p class="small"><i class="icon-time"></i> {{ post.date | date: "%Y-%m-%d %H:%M" }}</p> <div class="post_content"> {{ post.content | strip_html | truncatewords: 30 }} <a href="{{ post.url }}"><span class="text-info">continuar lendo</span></a> </div> </div> </div> {% endfor %} {% include pagination.html %}
marcoshack/marcoshack.github.io
b5d7bcca818bea709f9d694904bf48062a6c87dc
[git post-receive] nao prosseguir se ocorrer um erro em algum dos comandos
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh index dbc5fdc..0d40a5d 100644 --- a/_deploy/git-post-receive.sh +++ b/_deploy/git-post-receive.sh @@ -1,36 +1,44 @@ # # The "post-receive" script is run after receive-pack has accepted a pack # and the repository has been updated. It is passed arguments in through # stdin in the form # <oldrev> <newrev> <refname> # For example: # aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master # # see contrib/hooks/ for a sample, or uncomment the next line and # rename the file to "post-receive". #. /usr/share/git-core/contrib/hooks/post-receive-email JEKYLL_CMD=$HOME/bin/jekyll BUNDLE_CMD=$HOME/bin/bundle GIT_REPO=$HOME/repo/mhack.git [email protected]:marcoshack/mhack.git TMP_GIT_CLONE=$HOME/tmp/mhack PUBLIC_WWW=$HOME/www/mhack +function check_command { + if [[ $? != 0 ]]; then exit 1; fi +} + echo "--> Setting up local workspace" git clone $GIT_REPO $TMP_GIT_CLONE +check_command + cd $TMP_GIT_CLONE && $BUNDLE_CMD install +check_command echo "--> Updating site" $JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW +check_command echo "--> Syincing remote repositories" for REPO in $REMOTE_REPOS; do cd $TMP_GIT_CLONE && git push --mirror $REPO done echo "--> Cleaning up local workspace" rm -Rf $TMP_GIT_CLONE -exit +exit 0
marcoshack/marcoshack.github.io
7908b1d4f95db7ae59b415886b108f6d39f0cdfd
alteracao da home, listando posts com conteudo parcial e imagens
diff --git a/Gemfile b/Gemfile index 4279128..0a89dbc 100644 --- a/Gemfile +++ b/Gemfile @@ -1,11 +1,12 @@ source :rubygems gem 'jekyll' gem 'rake' +gem 'nokogiri' # gsl needs native libraries: # # $ brew tap homebrew/versions # $ brew install gsl114 # gem 'gsl' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 36b0752..69132ed 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,36 +1,38 @@ GEM remote: http://rubygems.org/ specs: classifier (1.3.3) fast-stemmer (>= 1.0.0) directory_watcher (1.4.1) fast-stemmer (1.0.1) gsl (1.14.7) narray (>= 0.5.9) jekyll (0.12.0) classifier (~> 1.3) directory_watcher (~> 1.1) kramdown (~> 0.13.4) liquid (~> 2.3) maruku (~> 0.5) pygments.rb (~> 0.3.2) kramdown (0.13.8) liquid (2.4.1) maruku (0.6.1) syntax (>= 1.0.0) narray (0.6.0.4) + nokogiri (1.5.6) posix-spawn (0.3.6) pygments.rb (0.3.7) posix-spawn (~> 0.3.6) yajl-ruby (~> 1.1.0) rake (10.0.3) syntax (1.0.0) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES gsl jekyll + nokogiri rake diff --git a/README_POSTS.md b/README_POSTS.md new file mode 100644 index 0000000..38b92a9 --- /dev/null +++ b/README_POSTS.md @@ -0,0 +1,6 @@ +# Custom post attributes + +## image + +Image file name relative from ./images/ to be displayed in the posts list. The image maximum size MUST be 170x150px. + diff --git a/_config.yml b/_config.yml index 4a0a52b..d619cfc 100644 --- a/_config.yml +++ b/_config.yml @@ -1,15 +1,17 @@ permalink: /:year/:month/:title.html exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md ] future: false lsi: true # Produces an index for related posts. -paginate: 3 +paginate: 4 authors: mhack: name: Marcos Hack display_name: Marcos Hack email: [email protected] twitter: marcoshack github: marcoshack + +plugins: ./_plugins \ No newline at end of file diff --git a/_plugins/strip_html.rb b/_plugins/strip_html.rb new file mode 100644 index 0000000..78e3ddc --- /dev/null +++ b/_plugins/strip_html.rb @@ -0,0 +1,7 @@ +require 'nokogiri' + +module HTMLFilter + def strip_html(input) + Nokogiri::HTML(input).text + end +end diff --git a/_posts/2009-06-15-definicao-de-cloud-computing-nist.html b/_posts/2009-06-15-definicao-de-cloud-computing-nist.html index dd4b80d..ef01366 100644 --- a/_posts/2009-06-15-definicao-de-cloud-computing-nist.html +++ b/_posts/2009-06-15-definicao-de-cloud-computing-nist.html @@ -1,10 +1,10 @@ --- layout: post title: Definição de Cloud Computing pelo NIST date: 2009-06-15 04:48:04 UTC updated: 2009-06-15 04:48:04 UTC comments: false categories: Cloud Computing --- -<div><!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } A:link { so-language: zxx } --><br/><p style="margin-bottom:.5cm;">O <em>National Institute of Standards and Technology</em> (<a href="http://www.nist.gov/">NIST [1]</a>) disponibilizou no início de Junho o primeiro rascunho de uma definição para <em>Cloud Computing</em> (Computação em Nuvem). Trata-se de um documento de duas páginas com as primeiras linhas do que futuramente deve se tornar uma definição formal desse paradigma de computação na visão do instituto.</p><br/><br/>O texto é muito acessível e basicamente define cinco características essenciais que definem computação em nuvem, três modelos de entrega dos serviços e quatro modelos de instalação e configuração da infraestrutura necessária para criação das nuvens.<br/><br/>O texto completo está disponível publicamente no <a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html">site do <span style="text-decoration:underline;">instituto</span></a><a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html"> [2]</a>. Neste artigo gostaria apenas de fornecer a descrição dos três modelos de entrega de serviço definidas neste trabalho, pois através desses conceitos é possível entender melhor os serviços de computação em nuvem oferecidos atualmente:<br/><ul><br/> <li><em><strong>Software as a Service (SaaS)</strong></em>: Esse é o já conhecido pela maioria dos profissionais da área de software, trata-se de entregar produtos de software para os consumidores finais através de dispositivos e aplicações clientes "leves", como dispositivos móveis (p.ex. celulares e <em>netbook</em>s), e de uma forma mais geral através de navegadores de Internet padrão (<em>browsers</em>). O cliente final não gerencia ou controla a infraestrutura necessária para o funcionamento do serviço, como rede, armazenamento, sistema operacional, nem tão pouco as funcionalidades oferecidas. Nessa categoria estão produtos como <em>Gmail</em>, <em>Google Docs</em>, <em>Twitter</em>, <em>Flickr, Picasa, Facebook</em>, entre muitos outros.</li><br/> <li><em><strong>Plataform as a Service (PaaS): </strong></em>Nessa categoria o provedor fornece uma infraestrutura na nuvem para a instalação e disponibilização de aplicações desenvolvidas pelo o usuário, utilizando ferramentas e ambientes de execução fornecidas pelo provedor do serviço. O usuário não gerencia ou controla os recursos de infraestrutura do ambiente de execução, como sistema operacional, rede, plataforma de execução, banco de dados e etc. Esses recursos são oferecidos de forma transparente através de APIs fornecidos pelo provedor. Mas nesse caso o cliente tem total controle da aplicação em si e geralmente de parâmetros de configuração do ambiente de execução. O <a href="http://code.google.com/appengine/"><em>Google App Engine</em></a><a href="http://code.google.com/appengine/"> [3]</a> é talvés o mais famoso exemplo desse modelo.</li><br/> <li><em><strong>Infrastructure as a Service (IaaS):</strong></em><em> </em>Neste modelo os serviços oferecidos aos clientes são processamento, armazenamento, rede e outros recursos computacionais fundamentais através dos quais os usuários podem executar quaisquer tipos de aplicações. Nesse caso o cliente tem total controle sobre o ambiente de execução, desde o sistema operacional até a plataforma de execução das aplicações. Porém, o usuário não gerencia ou controla a infraestrutura da nuvem em si, como por exemplo em qual hardware real suas "máquinas" estarão rodando. O Amazon Web Services (<a href="http://aws.amazon.com/">AWS [4]</a>) sem dúvida é o melhor representante deste modelo atualmente.</li><br/></ul><br/>Como diz a primeira nota da versão atual da <a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html">definição do NIST [2]</a>, o paradigma de computação em nuvem está em pleno desenvolvimento e suas definições e características evoluirão com o tempo.<br/><br/>[1] <a href="http://www.nist.gov/index.html">http://www.nist.gov/index.html</a><br/>[2] <a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html">http://csrc.nist.gov/groups/SNS/cloud-computing/index.html</a><br/>[3] <a href="http://code.google.com/appengine/">http://code.google.com/appengine/</a><br/>[4] <a href="http://aws.amazon.com/">http://aws.amazon.com/</a></div> \ No newline at end of file +<br/><p style="margin-bottom:.5cm;">O <em>National Institute of Standards and Technology</em> (<a href="http://www.nist.gov/">NIST [1]</a>) disponibilizou no início de Junho o primeiro rascunho de uma definição para <em>Cloud Computing</em> (Computação em Nuvem). Trata-se de um documento de duas páginas com as primeiras linhas do que futuramente deve se tornar uma definição formal desse paradigma de computação na visão do instituto.</p><br/><br/>O texto é muito acessível e basicamente define cinco características essenciais que definem computação em nuvem, três modelos de entrega dos serviços e quatro modelos de instalação e configuração da infraestrutura necessária para criação das nuvens.<br/><br/>O texto completo está disponível publicamente no <a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html">site do <span style="text-decoration:underline;">instituto</span></a><a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html"> [2]</a>. Neste artigo gostaria apenas de fornecer a descrição dos três modelos de entrega de serviço definidas neste trabalho, pois através desses conceitos é possível entender melhor os serviços de computação em nuvem oferecidos atualmente:<br/><ul><br/> <li><em><strong>Software as a Service (SaaS)</strong></em>: Esse é o já conhecido pela maioria dos profissionais da área de software, trata-se de entregar produtos de software para os consumidores finais através de dispositivos e aplicações clientes "leves", como dispositivos móveis (p.ex. celulares e <em>netbook</em>s), e de uma forma mais geral através de navegadores de Internet padrão (<em>browsers</em>). O cliente final não gerencia ou controla a infraestrutura necessária para o funcionamento do serviço, como rede, armazenamento, sistema operacional, nem tão pouco as funcionalidades oferecidas. Nessa categoria estão produtos como <em>Gmail</em>, <em>Google Docs</em>, <em>Twitter</em>, <em>Flickr, Picasa, Facebook</em>, entre muitos outros.</li><br/> <li><em><strong>Plataform as a Service (PaaS): </strong></em>Nessa categoria o provedor fornece uma infraestrutura na nuvem para a instalação e disponibilização de aplicações desenvolvidas pelo o usuário, utilizando ferramentas e ambientes de execução fornecidas pelo provedor do serviço. O usuário não gerencia ou controla os recursos de infraestrutura do ambiente de execução, como sistema operacional, rede, plataforma de execução, banco de dados e etc. Esses recursos são oferecidos de forma transparente através de APIs fornecidos pelo provedor. Mas nesse caso o cliente tem total controle da aplicação em si e geralmente de parâmetros de configuração do ambiente de execução. O <a href="http://code.google.com/appengine/"><em>Google App Engine</em></a><a href="http://code.google.com/appengine/"> [3]</a> é talvés o mais famoso exemplo desse modelo.</li><br/> <li><em><strong>Infrastructure as a Service (IaaS):</strong></em><em> </em>Neste modelo os serviços oferecidos aos clientes são processamento, armazenamento, rede e outros recursos computacionais fundamentais através dos quais os usuários podem executar quaisquer tipos de aplicações. Nesse caso o cliente tem total controle sobre o ambiente de execução, desde o sistema operacional até a plataforma de execução das aplicações. Porém, o usuário não gerencia ou controla a infraestrutura da nuvem em si, como por exemplo em qual hardware real suas "máquinas" estarão rodando. O Amazon Web Services (<a href="http://aws.amazon.com/">AWS [4]</a>) sem dúvida é o melhor representante deste modelo atualmente.</li><br/></ul><br/>Como diz a primeira nota da versão atual da <a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html">definição do NIST [2]</a>, o paradigma de computação em nuvem está em pleno desenvolvimento e suas definições e características evoluirão com o tempo.<br/><br/>[1] <a href="http://www.nist.gov/index.html">http://www.nist.gov/index.html</a><br/>[2] <a href="http://csrc.nist.gov/groups/SNS/cloud-computing/index.html">http://csrc.nist.gov/groups/SNS/cloud-computing/index.html</a><br/>[3] <a href="http://code.google.com/appengine/">http://code.google.com/appengine/</a><br/>[4] <a href="http://aws.amazon.com/">http://aws.amazon.com/</a> \ No newline at end of file diff --git a/_posts/2012-05-30-monitoracao-jvm-com-jmx-e-snmp.html b/_posts/2012-05-30-monitoracao-jvm-com-jmx-e-snmp.html index 4d08694..c8ae094 100644 --- a/_posts/2012-05-30-monitoracao-jvm-com-jmx-e-snmp.html +++ b/_posts/2012-05-30-monitoracao-jvm-com-jmx-e-snmp.html @@ -1,12 +1,11 @@ --- layout: post title: Monitoração da JVM via JMX e SNMP +image: coffee.jpg date: 2012-05-30 23:05:56 UTC updated: 2012-05-30 23:05:56 UTC - - sysadmin -tags: - - java - - monitoração +categories: [ sysadmin ] +tags: [ java, monitoração ] --- <div style="text-align: justify;">Este post apresenta de forma sucinta os passos necessários para configuração dos agentes JMX e SNMP na Máquina Virtual Java (<em>JVM</em>) assim como exemplos de utilização das ferramentas&nbsp;<em>jconsole</em>&nbsp;e&nbsp;<em>snmpwalk</em>&nbsp;para monitoração. Esse conteúdo é baseado na <a href="http://download.oracle.com/javase/1.5.0/docs/guide/management/" target="_blank">documentação de gerenciamento da JDK Sun/Oracle</a>.</div><br /><div id="headertabs"><div><div id="Configura.C3.A7.C3.A3o"><div style="text-align: justify;">A instalação padrão da JRE/JDK possui um modelo dos arquivos&nbsp;<em>management.properties</em>&nbsp;e&nbsp;<em>snmp.acl</em>&nbsp;com todas as configurações disponíveis (ambos em&nbsp;<em>$JAVA_HOME/jre/lib/management/</em>). Para facilitar a leitura e manutenção recomendo criar estes arquivos na estrutura de diretórios da sua aplicação, principalmente porque isso será necessário caso queira monitorar mais de uma JVM na mesma máquina (ver exemplo do&nbsp;Tomcat&nbsp;abaixo).</div><br /><h2 style="text-align: justify;"> snmp.acl</h2><div style="text-align: justify;">Crie o arquivo&nbsp;<em>snmp.acl</em>&nbsp;no local desejado com as linhas abaixo. Tenha em mente que o dono desse arquivo deve ser o mesmo do processo da JVM, a não ser que esteja executando com&nbsp;<em>root</em>&nbsp;que não é recomendável, diga-se de passagem:</div><br /><pre style="padding-left: 30px;">acl = {<br /> {<br /> communities = public, private<br /> access = read-only<br /> managers = 0.0.0.0/0<br /> }<br />}</pre><br /><div style="text-align: justify;">altere as permissões do mesmo para&nbsp;<em>600</em>&nbsp;(leitura e escrita apenas para o dono):</div><br /><pre style="padding-left: 30px;">chmod 600 &lt;CAMINHO_ARQUIVO_SNMP_ACL&gt;</pre><br /><h2> management.properties</h2><span style="text-align: justify;">Crie o arquivo&nbsp;</span><em style="text-align: justify;">management.properties</em><span style="text-align: justify;">&nbsp;no local desejado e insira as linha a seguir. Neste exemplo utilizamos as portas 9998 e 9999 para os agentes SNMP e JMX consecutivamente. Não esqueça de substituir&nbsp;</span><em style="text-align: justify;">&lt;CAMINHO_ARQUIVO_SNMP_ACL&gt;</em><span style="text-align: justify;">&nbsp;pelo caminho absoluto do arquivo&nbsp;</span><em style="text-align: justify;">snmp.acl</em><span style="text-align: justify;">:</span><br /><br /><pre style="padding-left: 30px;">com.sun.management.jmxremote.port=9999<br />com.sun.management.jmxremote.authenticate=false<br />com.sun.management.jmxremote.ssl=false<br />com.sun.management.snmp.port=9998<br />com.sun.management.snmp.interface=0.0.0.0<br />com.sun.management.snmp.acl.file=&lt;CAMINHO_ARQUIVO_SNMP_ACL&gt;</pre><br /><h2> Inicialização da JVM</h2><span style="text-align: justify;">Adicione o seguinte parâmetro na inicialização da JVM:</span><br /><br /><pre style="padding-left: 30px;">-Dcom.sun.management.config.file=&lt;CAMINHO_ARQUIVO_MANAGEMENT_PROPERTIES&gt;</pre><br /><h2 style="text-align: justify;"> Tomcat</h2><span style="text-align: justify;">Sugiro o seguinte padrão para a configuração dos agentes no Tomcat:</span><br /><ul style="text-align: justify;"><li>Crie os arquivos&nbsp;<em>management.properties</em>&nbsp;e&nbsp;<em>snmp.acl</em>&nbsp;no diretório&nbsp;<em>$CATALINA_BASE/conf</em>.</li></ul><ul style="text-align: justify;"><li>Crie ou edite o arquivo&nbsp;<em>$CATALINA_HOME/bin/setenv.sh</em>&nbsp;e adicione a linha a seguir. O script&nbsp;<em>catalina.sh</em>&nbsp;carrega esse arquivo na inicialização caso exista: <dl><dd><pre>CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.config.file=&lt;CAMINHO_MANAGEMENT_PROPERTIES&gt;"</pre><br /></dd></dl></li></ul></div></div></div> \ No newline at end of file diff --git a/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html b/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html index c077668..ffb793b 100644 --- a/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html +++ b/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html @@ -1,10 +1,18 @@ --- layout: post title: Mongo on Rails no MongoDB São Paulo +image: mongodb.png date: 2012-09-28 16:25:11 UTC updated: 2012-09-28 16:25:11 UTC categories: [ eventos, palestras ] -tags:[ mongoid, mongodb, ruby, rails, 10gen ] +tags: [ mongoid, mongodb, ruby, rails, 10gen ] --- -<div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/-Glv3uZ7UZJk/UGXPTSe9KkI/AAAAAAABFEM/baOf3SydV1w/s1600/mongodb.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="66" src="http://4.bp.blogspot.com/-Glv3uZ7UZJk/UGXPTSe9KkI/AAAAAAABFEM/baOf3SydV1w/s200/mongodb.png" width="200" /></a></div>No dia 13 de Julho tivemos o evendo anual <a href="http://www.10gen.com/events/mongodb-sao-paulo" target="_blank">MongoDB São Paulo</a>, que pela primeira vez&nbsp;realizado&nbsp;inteiramente&nbsp;pela 10gen, empresa responsável pelo desenvolvimento do MongoDB e que inclusive está abrindo um escritório em São Paulo para atender clientes locais, prestando serviços de consultoria, suporte e treinamento, mais informações conversem com o <a href="http://www.linkedin.com/in/marcellobaquero" target="_blank">Marcello Baquero</a>&nbsp;ou&nbsp;<a href="http://www.linkedin.com/in/steffbold" target="_blank">Steffany Boldrini</a>&nbsp;da 10gen.<br /><br />Mas vamos ao que interessa (pelo menos pra mim): durante o evento apresentei a palestra "Mongo On Rails", onde falei sobre a utilização da gem Mongoid em projetos Ruby on Rails - desde a instalação e configuração da Gem até a modelagem de documentos usando a DSL do Mongoid - e alguns cases de utilização de MongoDB e Mongoid na Editora Abril.<br /><br />Segue o vídeo na íntegra da apresentação, o código utilizado está disponível no repositório <a href="https://github.com/marcoshack/mongo_on_rails" target="_blank">"mongo_on_rails" no Github</a>:<br /><br /><iframe allowfullscreen="allowfullscreen" frameborder="0" height="334" src="http://blip.tv/play/hOdBg4DyJwI.html?p=1" width="596"></iframe><embed src="http://a.blip.tv/api.swf#hOdBg4DyJwI" style="display: none;" type="application/x-shockwave-flash"></embed><br /><br /><br /><div><br /></div> \ No newline at end of file +No dia 13 de Julho tivemos o evendo anual <a href="http://www.10gen.com/events/mongodb-sao-paulo" target="_blank">MongoDB São Paulo</a>, que pela primeira vez&nbsp;realizado&nbsp;inteiramente&nbsp;pela 10gen, empresa responsável pelo desenvolvimento do MongoDB e que inclusive está abrindo um escritório em São Paulo para atender clientes locais, prestando serviços de consultoria, suporte e treinamento, mais informações conversem com o <a href="http://www.linkedin.com/in/marcellobaquero">Marcello Baquero</a>&nbsp;ou&nbsp;<a href="http://www.linkedin.com/in/steffbold">Steffany Boldrini</a>&nbsp;da 10gen. +<br /><br /> +Mas vamos ao que interessa (pelo menos pra mim): durante o evento apresentei a palestra "Mongo On Rails", onde falei sobre a utilização da gem Mongoid em projetos Ruby on Rails - desde a instalação e configuração da Gem até a modelagem de documentos usando a DSL do Mongoid - e alguns cases de utilização de MongoDB e Mongoid na Editora Abril. +<br /><br /> +Segue o vídeo na íntegra da apresentação, o código utilizado está disponível no repositório <a href="https://github.com/marcoshack/mongo_on_rails">"mongo_on_rails" no Github</a>: +<br /><br /> + +<iframe allowfullscreen="allowfullscreen" frameborder="0" height="334" src="http://blip.tv/play/hOdBg4DyJwI.html?p=1" width="596"></iframe><embed src="http://a.blip.tv/api.swf#hOdBg4DyJwI" style="display: none;" type="application/x-shockwave-flash"></embed> \ No newline at end of file diff --git a/_posts/2012-10-15-java-jdk-1.5-no-os-x-lion-e-mountain-lion.md b/_posts/2012-10-15-java-jdk-1.5-no-os-x-lion-e-mountain-lion.md index 8a2a8b6..0be6a78 100644 --- a/_posts/2012-10-15-java-jdk-1.5-no-os-x-lion-e-mountain-lion.md +++ b/_posts/2012-10-15-java-jdk-1.5-no-os-x-lion-e-mountain-lion.md @@ -1,36 +1,37 @@ --- layout: post title: Java JDK 1.5 no OS X Lion e Mountain Lion description: Como instalar o Java JDK 1.5 no Mac OSX Mountaion Lion +image: coffee.jpg date: 2012-10-15 17:46:10 UTC updated: 2013-01-18 00:41:00 UTC categories: [ programação ] tags: [ java, mac, osx, montain lion ] --- Basicamente segui os passos descritos no artigo [Java 1.5 for OS X Mountain Lion](http://www.s-seven.net/java_15_mountain_lion), exceto que não usei o Pacifist nos passos 6 e 7 (20 pratas pra extrair um .pkg? C'MON MAN!) cd ~/Downloads wget http://support.apple.com/downloads/DL1359/en_US/JavaForMacOSX10.5Update10.dmg \ -O ~/Downloads/JavaForMacOSX10.5Update10.dmg hdiutil attach ~/Downloads/JavaForMacOSX10.5Update10.dmg pkgutil --expand /Volumes/Java\ For\ Mac\ OS\ X\ 10.5\ Update\ 10/JavaForMacOSX10.5Update10.pkg \ ~/Downloads/JavaForMacOSX10.5Update10 cd ~/Downloads/JavaForMacOSX10.5Update10/JavaForMacOSX10.5Update10.pkg/ mv Payload payload.gz gunzip payload.gz cpio -idmv < payload sudo cp -R System/Library/Frameworks/JavaVM.framework/Versions/1.5.0 \ /System/Library/Frameworks/JavaVM.framework/Versions/ Depois é só seguir os passos exatamente como estão no artigo. Pra usar o JDK 1.5 com ferramentas de linha de comando declare a variável de ambiente JAVA_HOME usando o comando /usr/libexec/java_home: export JAVA_HOME=`/usr/libexec/java_home --version 1.5.0` That's it! diff --git a/_posts/2012-12-18-jmeter-reports.html b/_posts/2012-12-18-jmeter-reports.html index aa5dbb7..3a02456 100644 --- a/_posts/2012-12-18-jmeter-reports.html +++ b/_posts/2012-12-18-jmeter-reports.html @@ -1,11 +1,12 @@ --- layout: post title: jmeter-reports description: Ferramenta para gerar relatórios simplesdo JMeter a partir do summary report. +image: jmeter-logo.png date: 2012-12-18 20:32:44 UTC updated: 2012-12-18 20:32:44 UTC categories: [ programação ] tags: [ ruby, performance, jmeter, gem, reports ] --- Nas últimas semanas dediquei boa parte do meu tempo trabalhando em testes de performance do <a href="http://id.abril.com.br/" target="_blank">Abril ID</a>, o sistema de autenticação utilizado por quase todos os sites da casa.<br /><br />Utilizamos o <a href="http://jmeter.apache.org/" target="_blank">JMeter</a> como injetor de carga, e uma funcionalidade que falta nessa ótima ferramenta é uma forma de gerenciar e visualizar execuções anteriores. E como todo bom programador a preguiça não me permite anotar os resultados numa planilha sem ficar de saco cheio depois da 3 execução e começar a codar alguma coisa divertida pra facilitar a vida.<br /><br />Nasce então a gem&nbsp;<i>jmeter-reports</i>, uma super-mega-ultra-absurdamente-complexa ferramenta de análise de resultados de testes de performance .... ok, bem menos, mas é legal, geek-friendly e tem até cores!<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-jxH0Olu83Wk/UNDSgktylHI/AAAAAAABKmw/Xf5oqRY7Ii0/s1600/Screen+Shot+2012-12-18+at+6.30.38+PM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-jxH0Olu83Wk/UNDSgktylHI/AAAAAAABKmw/Xf5oqRY7Ii0/s1600/Screen+Shot+2012-12-18+at+6.30.38+PM.png" /></a></div><br /><div class="separator" style="clear: both; text-align: center;"></div><br />Mais informações visite a <a href="https://github.com/marcoshack/jmeter-reports" target="_blank">página do repositório no Github</a> e divirta-se! Quando tiver um tempinho vou implementar outputs em HTML e PDF com gráficos bem bonitos pra deixar os chefes felizes.<br /><br /> \ No newline at end of file diff --git a/images/coffee.jpg b/images/coffee.jpg new file mode 100644 index 0000000..f17f0a2 Binary files /dev/null and b/images/coffee.jpg differ diff --git a/images/jmeter-logo.png b/images/jmeter-logo.png new file mode 100644 index 0000000..ca5249b Binary files /dev/null and b/images/jmeter-logo.png differ diff --git a/images/mongodb.png b/images/mongodb.png new file mode 100644 index 0000000..ea79344 Binary files /dev/null and b/images/mongodb.png differ diff --git a/index.html b/index.html index 42cb009..ebcc58c 100644 --- a/index.html +++ b/index.html @@ -1,27 +1,24 @@ --- layout: default title: home --- {% for post in paginator.posts %} - <div class="page-header"> - <h1><a href="{{ post.url }}">{{ post.title }}</a></h1> - <p class="small"><i class="icon-time"></i> {{ post.date | date: "%Y-%m-%d %H:%M" }}</p> +<div class="row"> + <div class="span2"> + {% if post.image != nil %} + <img src="/images/{{ post.image }}" /> + {% endif %} </div> - <div class="row"> - <div class="span8"> - {{ post.content }} - <p><a class="btn btn-mini btn-inverse" href="{{ post.url }}">ir para o post</a></p> + <div class="span6"> + <h3><a href="{{ post.url }}">{{ post.title }}</a></h3> + <p class="small"><i class="icon-time"></i> {{ post.date | date: "%Y-%m-%d %H:%M" }}</p> + <div class="post_content"> + {{ post.content | strip_html | truncatewords: 30 }} + <a href="{{ post.url }}"><span class="text-info">continuar lendo</span></a> </div> </div> -{% endfor %} - - -<!-- <div class="hero-unit"> - <h2><a href="{{ first_post.url }}">{{ first_post.title }}</a></h2> - <p>{{ first_post.content | truncate: 450 }}</p> - <p><a href="{{ first_post.url }}">ver post</a></p> </div> - --> +{% endfor %} {% include pagination.html %}
marcoshack/marcoshack.github.io
6ee9055207c0413566252d59efba5215dce5935b
--future adicionado ao rake server
diff --git a/Rakefile b/Rakefile index 1b17409..4c1841f 100644 --- a/Rakefile +++ b/Rakefile @@ -1,18 +1,18 @@ require 'rubygems' require 'rake' task :server do - sh "jekyll --server --auto" + sh "jekyll --server --auto --future" end namespace :site do task :deploy do sh "git push aws master" end end namespace :git do task :update_hooks do sh "scp _deploy/git-post-receive.sh mhack.com:~/repo/mhack.git/hooks/post-receive" end end
marcoshack/marcoshack.github.io
8cf94cbdbd8232763c49a1bd365f31901150c324
refatoracao das categorias do post
diff --git a/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html b/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html index 9950148..c077668 100644 --- a/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html +++ b/_posts/2012-09-28-mongo-on-rails-mongodb-sao-paulo.html @@ -1,17 +1,10 @@ --- layout: post title: Mongo on Rails no MongoDB São Paulo date: 2012-09-28 16:25:11 UTC updated: 2012-09-28 16:25:11 UTC -categories: - - eventos - - palestras -tags: - - mongoid - - mongodb - - ruby - - rails - - 10gen +categories: [ eventos, palestras ] +tags:[ mongoid, mongodb, ruby, rails, 10gen ] --- <div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/-Glv3uZ7UZJk/UGXPTSe9KkI/AAAAAAABFEM/baOf3SydV1w/s1600/mongodb.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="66" src="http://4.bp.blogspot.com/-Glv3uZ7UZJk/UGXPTSe9KkI/AAAAAAABFEM/baOf3SydV1w/s200/mongodb.png" width="200" /></a></div>No dia 13 de Julho tivemos o evendo anual <a href="http://www.10gen.com/events/mongodb-sao-paulo" target="_blank">MongoDB São Paulo</a>, que pela primeira vez&nbsp;realizado&nbsp;inteiramente&nbsp;pela 10gen, empresa responsável pelo desenvolvimento do MongoDB e que inclusive está abrindo um escritório em São Paulo para atender clientes locais, prestando serviços de consultoria, suporte e treinamento, mais informações conversem com o <a href="http://www.linkedin.com/in/marcellobaquero" target="_blank">Marcello Baquero</a>&nbsp;ou&nbsp;<a href="http://www.linkedin.com/in/steffbold" target="_blank">Steffany Boldrini</a>&nbsp;da 10gen.<br /><br />Mas vamos ao que interessa (pelo menos pra mim): durante o evento apresentei a palestra "Mongo On Rails", onde falei sobre a utilização da gem Mongoid em projetos Ruby on Rails - desde a instalação e configuração da Gem até a modelagem de documentos usando a DSL do Mongoid - e alguns cases de utilização de MongoDB e Mongoid na Editora Abril.<br /><br />Segue o vídeo na íntegra da apresentação, o código utilizado está disponível no repositório <a href="https://github.com/marcoshack/mongo_on_rails" target="_blank">"mongo_on_rails" no Github</a>:<br /><br /><iframe allowfullscreen="allowfullscreen" frameborder="0" height="334" src="http://blip.tv/play/hOdBg4DyJwI.html?p=1" width="596"></iframe><embed src="http://a.blip.tv/api.swf#hOdBg4DyJwI" style="display: none;" type="application/x-shockwave-flash"></embed><br /><br /><br /><div><br /></div> \ No newline at end of file
marcoshack/marcoshack.github.io
e012bfa4bfbc91b13bb5ac1bd444e89b3b52ab6f
another minor fix in post-receive hook
diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh index d6489f7..dbc5fdc 100644 --- a/_deploy/git-post-receive.sh +++ b/_deploy/git-post-receive.sh @@ -1,36 +1,36 @@ # # The "post-receive" script is run after receive-pack has accepted a pack # and the repository has been updated. It is passed arguments in through # stdin in the form # <oldrev> <newrev> <refname> # For example: # aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master # # see contrib/hooks/ for a sample, or uncomment the next line and # rename the file to "post-receive". #. /usr/share/git-core/contrib/hooks/post-receive-email JEKYLL_CMD=$HOME/bin/jekyll BUNDLE_CMD=$HOME/bin/bundle GIT_REPO=$HOME/repo/mhack.git [email protected]:marcoshack/mhack.git TMP_GIT_CLONE=$HOME/tmp/mhack PUBLIC_WWW=$HOME/www/mhack echo "--> Setting up local workspace" git clone $GIT_REPO $TMP_GIT_CLONE cd $TMP_GIT_CLONE && $BUNDLE_CMD install echo "--> Updating site" $JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW echo "--> Syincing remote repositories" for REPO in $REMOTE_REPOS; do - git push --mirror $REPO + cd $TMP_GIT_CLONE && git push --mirror $REPO done echo "--> Cleaning up local workspace" rm -Rf $TMP_GIT_CLONE exit
marcoshack/marcoshack.github.io
190699ba489b10c0c1a4ed3b745697f0ed59d4cd
minor fix in post-receive hook
diff --git a/Rakefile b/Rakefile index bed71d8..1b17409 100644 --- a/Rakefile +++ b/Rakefile @@ -1,10 +1,18 @@ require 'rubygems' require 'rake' task :server do sh "jekyll --server --auto" end -task :deploy do - sh "git push aws master" +namespace :site do + task :deploy do + sh "git push aws master" + end +end + +namespace :git do + task :update_hooks do + sh "scp _deploy/git-post-receive.sh mhack.com:~/repo/mhack.git/hooks/post-receive" + end end diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh index 646b406..d6489f7 100644 --- a/_deploy/git-post-receive.sh +++ b/_deploy/git-post-receive.sh @@ -1,36 +1,36 @@ # # The "post-receive" script is run after receive-pack has accepted a pack # and the repository has been updated. It is passed arguments in through # stdin in the form # <oldrev> <newrev> <refname> # For example: # aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master # # see contrib/hooks/ for a sample, or uncomment the next line and # rename the file to "post-receive". #. /usr/share/git-core/contrib/hooks/post-receive-email JEKYLL_CMD=$HOME/bin/jekyll BUNDLE_CMD=$HOME/bin/bundle GIT_REPO=$HOME/repo/mhack.git [email protected]:marcoshack/mhack.git TMP_GIT_CLONE=$HOME/tmp/mhack PUBLIC_WWW=$HOME/www/mhack echo "--> Setting up local workspace" git clone $GIT_REPO $TMP_GIT_CLONE -$BUNDLE_CMD install +cd $TMP_GIT_CLONE && $BUNDLE_CMD install echo "--> Updating site" $JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW echo "--> Syincing remote repositories" for REPO in $REMOTE_REPOS; do git push --mirror $REPO done echo "--> Cleaning up local workspace" rm -Rf $TMP_GIT_CLONE exit
marcoshack/marcoshack.github.io
1599311fd2ba2224428eb7b03eb855a618e6e507
apache vhost config and git post-receive script
diff --git a/Gemfile b/Gemfile index 8dbbd62..4279128 100644 --- a/Gemfile +++ b/Gemfile @@ -1,10 +1,11 @@ source :rubygems gem 'jekyll' +gem 'rake' # gsl needs native libraries: # # $ brew tap homebrew/versions # $ brew install gsl114 # -gem 'gsl' +gem 'gsl' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index d704c2c..36b0752 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,34 +1,36 @@ GEM remote: http://rubygems.org/ specs: classifier (1.3.3) fast-stemmer (>= 1.0.0) directory_watcher (1.4.1) fast-stemmer (1.0.1) gsl (1.14.7) narray (>= 0.5.9) jekyll (0.12.0) classifier (~> 1.3) directory_watcher (~> 1.1) kramdown (~> 0.13.4) liquid (~> 2.3) maruku (~> 0.5) pygments.rb (~> 0.3.2) kramdown (0.13.8) liquid (2.4.1) maruku (0.6.1) syntax (>= 1.0.0) narray (0.6.0.4) posix-spawn (0.3.6) pygments.rb (0.3.7) posix-spawn (~> 0.3.6) yajl-ruby (~> 1.1.0) + rake (10.0.3) syntax (1.0.0) yajl-ruby (1.1.0) PLATFORMS ruby DEPENDENCIES gsl jekyll + rake diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..bed71d8 --- /dev/null +++ b/Rakefile @@ -0,0 +1,10 @@ +require 'rubygems' +require 'rake' + +task :server do + sh "jekyll --server --auto" +end + +task :deploy do + sh "git push aws master" +end diff --git a/_config.yml b/_config.yml index 64a3245..4a0a52b 100644 --- a/_config.yml +++ b/_config.yml @@ -1,15 +1,15 @@ permalink: /:year/:month/:title.html -exclude: [ Gemfile, Gemfile.lock, README.md ] +exclude: [ Gemfile, Gemfile.lock, Rakefile, README.md ] future: false lsi: true # Produces an index for related posts. paginate: 3 authors: mhack: name: Marcos Hack display_name: Marcos Hack email: [email protected] twitter: marcoshack github: marcoshack diff --git a/_apache-vhost.conf b/_deploy/apache-vhost.conf similarity index 100% rename from _apache-vhost.conf rename to _deploy/apache-vhost.conf diff --git a/_deploy/git-post-receive.sh b/_deploy/git-post-receive.sh new file mode 100644 index 0000000..646b406 --- /dev/null +++ b/_deploy/git-post-receive.sh @@ -0,0 +1,36 @@ +# +# The "post-receive" script is run after receive-pack has accepted a pack +# and the repository has been updated. It is passed arguments in through +# stdin in the form +# <oldrev> <newrev> <refname> +# For example: +# aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master +# +# see contrib/hooks/ for a sample, or uncomment the next line and +# rename the file to "post-receive". + +#. /usr/share/git-core/contrib/hooks/post-receive-email + +JEKYLL_CMD=$HOME/bin/jekyll +BUNDLE_CMD=$HOME/bin/bundle +GIT_REPO=$HOME/repo/mhack.git [email protected]:marcoshack/mhack.git +TMP_GIT_CLONE=$HOME/tmp/mhack +PUBLIC_WWW=$HOME/www/mhack + +echo "--> Setting up local workspace" +git clone $GIT_REPO $TMP_GIT_CLONE +$BUNDLE_CMD install + +echo "--> Updating site" +$JEKYLL_CMD --no-auto $TMP_GIT_CLONE $PUBLIC_WWW + +echo "--> Syincing remote repositories" +for REPO in $REMOTE_REPOS; do + git push --mirror $REPO +done + +echo "--> Cleaning up local workspace" +rm -Rf $TMP_GIT_CLONE + +exit
marcoshack/marcoshack.github.io
4a89abd1963e2b17dc5dfc6127b53049c6228a75
pagination
diff --git a/Gemfile b/Gemfile index 9224d0b..8dbbd62 100644 --- a/Gemfile +++ b/Gemfile @@ -1,4 +1,10 @@ source :rubygems gem 'jekyll' -#gem 'gsl' + +# gsl needs native libraries: +# +# $ brew tap homebrew/versions +# $ brew install gsl114 +# +gem 'gsl' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..d704c2c --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,34 @@ +GEM + remote: http://rubygems.org/ + specs: + classifier (1.3.3) + fast-stemmer (>= 1.0.0) + directory_watcher (1.4.1) + fast-stemmer (1.0.1) + gsl (1.14.7) + narray (>= 0.5.9) + jekyll (0.12.0) + classifier (~> 1.3) + directory_watcher (~> 1.1) + kramdown (~> 0.13.4) + liquid (~> 2.3) + maruku (~> 0.5) + pygments.rb (~> 0.3.2) + kramdown (0.13.8) + liquid (2.4.1) + maruku (0.6.1) + syntax (>= 1.0.0) + narray (0.6.0.4) + posix-spawn (0.3.6) + pygments.rb (0.3.7) + posix-spawn (~> 0.3.6) + yajl-ruby (~> 1.1.0) + syntax (1.0.0) + yajl-ruby (1.1.0) + +PLATFORMS + ruby + +DEPENDENCIES + gsl + jekyll diff --git a/_config.yml b/_config.yml index 2c28a52..64a3245 100644 --- a/_config.yml +++ b/_config.yml @@ -1,19 +1,15 @@ permalink: /:year/:month/:title.html -exclude: - - Gemfile - - Gemfile.lock - - README +exclude: [ Gemfile, Gemfile.lock, README.md ] future: false - -# Produces an index for related posts. -lsi: true +lsi: true # Produces an index for related posts. +paginate: 3 authors: mhack: name: Marcos Hack display_name: Marcos Hack email: [email protected] twitter: marcoshack github: marcoshack diff --git a/_includes/pagination.html b/_includes/pagination.html new file mode 100644 index 0000000..f48abab --- /dev/null +++ b/_includes/pagination.html @@ -0,0 +1,32 @@ +<div class="pagination pagination-centered"> + <ul> + {% if paginator.previous_page %} + {% if paginator.previous_page == 1 %} + <li class="disabled"><a href="#">&laquo;</a></li> + {% else %} + <li><a href="/page{{paginator.previous_page}}">&laquo;</a></li> + {% endif %} + {% endif %} + + {% if paginator.page == 1 %} + <li class="disabled"><a href="#">1</a></li> + {% else %} + <li><a href="/">1</a></li> + {% endif %} + + {% for count in (2..paginator.total_pages) %} + <li class="page"> + {% if count == paginator.page %} + <li class="active"><a href="#">{{count}}</a></li> + {% else %} + <li><a href="/page{{count}}">{{count}}</a></li> + {% endif %} + {% endfor %} + + {% if paginator.next_page %} + <li class="active"><a href="/page{{paginator.next_page}}">&raquo;</a></li> + {% else %} + <li class="disabled"><a href="#">&raquo;</a></li> + {% endif %} + </ul> +</div> \ No newline at end of file diff --git a/_layouts/post.html b/_layouts/post.html index f01ca11..bb1f51e 100644 --- a/_layouts/post.html +++ b/_layouts/post.html @@ -1,18 +1,20 @@ --- layout: default --- <!-- post header --> -<h1><a href="{{ page.url }}">{{ page.title }}</a></h1> -<p class="small"><i class="icon-time"></i> {{ page.date | date: "%Y-%m-%d %H:%M" }}</p> +<div class="page-header"> + <h1><a href="{{ page.url }}">{{ page.title }}</a></h1> + <p class="small"><i class="icon-time"></i> {{ page.date | date: "%Y-%m-%d %H:%M" }}</p> +</div> <div class="post"> {{ content }} </div> {% include facebook_div.html %} {% include facebook_script.html %} <br/> <!-- uhhhh --> {% include disqus_div.html %} {% include disqus_script.html %} diff --git a/index.html b/index.html index f6ce5f5..42cb009 100644 --- a/index.html +++ b/index.html @@ -1,25 +1,27 @@ --- layout: default title: home --- -{% assign first_post = site.posts.first %} -<div class="hero-unit"> +{% for post in paginator.posts %} + <div class="page-header"> + <h1><a href="{{ post.url }}">{{ post.title }}</a></h1> + <p class="small"><i class="icon-time"></i> {{ post.date | date: "%Y-%m-%d %H:%M" }}</p> + </div> + <div class="row"> + <div class="span8"> + {{ post.content }} + <p><a class="btn btn-mini btn-inverse" href="{{ post.url }}">ir para o post</a></p> + </div> + </div> +{% endfor %} + + +<!-- <div class="hero-unit"> <h2><a href="{{ first_post.url }}">{{ first_post.title }}</a></h2> <p>{{ first_post.content | truncate: 450 }}</p> <p><a href="{{ first_post.url }}">ver post</a></p> </div> + --> -<div class="page-header"> - <h2>posts anteriores</h2> - <ul> - {% for post in site.posts %} - {% if post != site.posts.first %} - <li> - <a href="{{ post.url }}">{{ post.title }}</a> - [{{ post.date | date_to_string }}] - </li> - {% endif %} - {% endfor %} - </ul> -</div> \ No newline at end of file +{% include pagination.html %}
marcoshack/marcoshack.github.io
297faf51e841ab7077efde9e97541f978696f85a
fork me on github added
diff --git a/_includes/github_ribbon.html b/_includes/github_ribbon.html new file mode 100644 index 0000000..ebf63a6 --- /dev/null +++ b/_includes/github_ribbon.html @@ -0,0 +1,3 @@ +<spam class="hidden-phone"> + <a href="https://github.com/marcoshack"><img style="position: absolute; top: 0; right: 0; border: 0;" src="/images/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a> +</spam> \ No newline at end of file diff --git a/_includes/navbar.html b/_includes/navbar.html index 6fba96d..c91ff17 100644 --- a/_includes/navbar.html +++ b/_includes/navbar.html @@ -1,22 +1,23 @@ <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="/">mhack</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class=""> <a href="/">home</a> </li> <li class=""> <a href="/contato.html">contato</a> </li> </ul> </div> + {% include github_ribbon.html %} </div> </div> </div> \ No newline at end of file diff --git a/_includes/sidebar.html b/_includes/sidebar.html new file mode 100644 index 0000000..c4e8c82 --- /dev/null +++ b/_includes/sidebar.html @@ -0,0 +1,4 @@ +<!-- side bar --> +<div class="span2 hidden-phone"> + {% include twitter_widget.html %} +</div> \ No newline at end of file diff --git a/_layouts/default.html b/_layouts/default.html index 80a4a58..de859e9 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,39 +1,36 @@ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> {% if page.tags != nil %} <meta name="keywords" content="{{ page.tags | join: ', ' }}"> {% endif %} {% if page.description != nil %} <meta name="description" content="{{ page.description }}"> {% endif %} <title>mhack - {{ page.title }}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="/assets/css/bootstrap.css" rel="stylesheet"> <link href="/assets/css/custom.css" rel="stylesheet"> {% include ga.html %} </head> <body> {% include navbar.html %} <br/> <br/> <div class="container"> <div class="row"> <!-- main content --> <div class="span8"> {{ content }} </div> - <!-- side bar --> - <div class="span2 hidden-phone"> - {% include twitter_widget.html %} - </div> + {% include sidebar.html %} </div> </div> <script src="/assets/js/jquery-1.9.0.js"></script> <script src="/assets/js/bootstrap.js"></script> </body> </html> \ No newline at end of file diff --git a/images/forkme_right_orange_ff7600.png b/images/forkme_right_orange_ff7600.png new file mode 100644 index 0000000..7dc1afc Binary files /dev/null and b/images/forkme_right_orange_ff7600.png differ
marcoshack/marcoshack.github.io
a4e203e74dd77144824090d3f60edea53e8bbfc6
redirecionamento dos dominios
diff --git a/.htaccess b/.htaccess index ca4db61..2b2d77e 100644 --- a/.htaccess +++ b/.htaccess @@ -1,25 +1,22 @@ -# -# Redirecionamentos -# +<If "%{HTTP_HOST} != 'mhack.com'"> + RedirectMatch permanent /(.*) http://mhack.com/$1 +</If> -# post antigos RedirectPermanent /2012/10/java-jdk-15-no-os-x-lion-e-mountain-lion.html /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html RedirectPermanent /2012/08/mongo-on-rails-no-mongodb-sao-paulo.html /2012/09/mongo-on-rails-mongodb-sao-paulo.html RedirectPermanent /2010/08/monitoracao-da-jvm-via-jmx-e-snmp.html /2012/05/monitoracao-jvm-com-jmx-e-snmp.html RedirectPermanent /2009/10/japan-linux-symposium-e-lancamento-do.html /2009/10/japan-linux-symposium-lancamento-windows7.html RedirectPermanent /2009/06/definicao-de-cloud-computing-pelo-nist.html /2009/06/definicao-de-cloud-computing-nist.html RedirectPermanent /2009/05/amazon-web-services-leva-educacao-as.html /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html RedirectPermanent /2008/12/segunda-via-do-documento-do-carro-em.html /2008/12/segunda-via-documento-carro-sao-paulo.html - -# sufixo .html ao inves de "/" nos posts RedirectPermanent /2012/12/jmeter-reports/ /2012/12/jmeter-reports.html RedirectPermanent /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion/ /2012/10/java-jdk-1.5-no-os-x-lion-e-mountain-lion.html RedirectPermanent /2012/09/mongo-on-rails-mongodb-sao-paulo/ /2012/09/mongo-on-rails-mongodb-sao-paulo.html RedirectPermanent /2012/05/monitoracao-jvm-com-jmx-e-snmp/ /2012/05/monitoracao-jvm-com-jmx-e-snmp.html RedirectPermanent /2010/01/campus-party-2010-dia-1/ /2010/01/campus-party-2010-dia-1.html RedirectPermanent /2009/10/japan-linux-symposium-lancamento-windows7/ /2009/10/japan-linux-symposium-lancamento-windows7.html RedirectPermanent /2009/06/definicao-de-cloud-computing-nist/ /2009/06/definicao-de-cloud-computing-nist.html RedirectPermanent /2009/05/amazon-web-services-leva-a-educacao-as-nuvens/ /2009/05/amazon-web-services-leva-a-educacao-as-nuvens.html RedirectPermanent /2009/03/ip-communications-2008/ /2009/03/ip-communications-2008.html RedirectPermanent /2008/12/segunda-via-documento-carro-sao-paulo/ /2008/12/segunda-via-documento-carro-sao-paulo.html -RedirectPermanent /contato /contato.html +RedirectPermanent /contato /contato.html \ No newline at end of file
marcoshack/marcoshack.github.io
d4a4d7097f9682e4c7b3b049c80124677e65bca0
refatoracao dos includes do facebook e disqus, inclusao do widget do twitter
diff --git a/_includes/.gitkeep b/_includes/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/disqus_div.html b/_includes/disqus_div.html new file mode 100644 index 0000000..9120fa7 --- /dev/null +++ b/_includes/disqus_div.html @@ -0,0 +1,8 @@ +{% unless page.comments == false %} +<!-- disqus placeholder--> +<div id="disqus"> + <div id="disqus_thread"></div> + <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> + <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> +</div> +{% endunless %} \ No newline at end of file diff --git a/_includes/disqus_script.html b/_includes/disqus_script.html new file mode 100644 index 0000000..34833da --- /dev/null +++ b/_includes/disqus_script.html @@ -0,0 +1,11 @@ +{% unless page.comments == false %} +<!-- disqus script --> +<script type="text/javascript"> + var disqus_shortname = 'mhack'; + (function() { + var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; + dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; + (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); + })(); +</script> +{% endunless %} diff --git a/_includes/facebook_div.html b/_includes/facebook_div.html new file mode 100644 index 0000000..629b17f --- /dev/null +++ b/_includes/facebook_div.html @@ -0,0 +1,3 @@ +<!-- facebook placeholder --> +<div class="fb-like" data-send="true" data-width="450" data-show-faces="false"> +</div> \ No newline at end of file diff --git a/_includes/facebook_script.html b/_includes/facebook_script.html new file mode 100644 index 0000000..b27fddb --- /dev/null +++ b/_includes/facebook_script.html @@ -0,0 +1,11 @@ +<!-- facebook script --> +<div id="fb-root"></div> +<script> + (function(d, s, id) { + var js, fjs = d.getElementsByTagName(s)[0]; + if (d.getElementById(id)) return; + js = d.createElement(s); js.id = id; + js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; + fjs.parentNode.insertBefore(js, fjs); + }(document, 'script', 'facebook-jssdk')); +</script> \ No newline at end of file diff --git a/_includes/ga.html b/_includes/ga.html new file mode 100644 index 0000000..c6c1c7b --- /dev/null +++ b/_includes/ga.html @@ -0,0 +1,12 @@ +<br/> +<script type="text/javascript"> + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-6981296-7']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); + })(); +</script> \ No newline at end of file diff --git a/_includes/navbar.html b/_includes/navbar.html new file mode 100644 index 0000000..6fba96d --- /dev/null +++ b/_includes/navbar.html @@ -0,0 +1,22 @@ +<div class="navbar navbar-inverse navbar-fixed-top"> + <div class="navbar-inner"> + <div class="container"> + <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + </button> + <a class="brand" href="/">mhack</a> + <div class="nav-collapse collapse"> + <ul class="nav"> + <li class=""> + <a href="/">home</a> + </li> + <li class=""> + <a href="/contato.html">contato</a> + </li> + </ul> + </div> + </div> + </div> +</div> \ No newline at end of file diff --git a/_includes/twitter_widget.html b/_includes/twitter_widget.html new file mode 100644 index 0000000..1ab7a1a --- /dev/null +++ b/_includes/twitter_widget.html @@ -0,0 +1,3 @@ +<a class="twitter-timeline" href="https://twitter.com/marcoshack" data-widget-id="293893619042107392">Tweets by @marcoshack</a> +<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); +</script> \ No newline at end of file diff --git a/_layouts/default.html b/_layouts/default.html index 147862e..80a4a58 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,70 +1,39 @@ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> {% if page.tags != nil %} <meta name="keywords" content="{{ page.tags | join: ', ' }}"> {% endif %} {% if page.description != nil %} <meta name="description" content="{{ page.description }}"> {% endif %} <title>mhack - {{ page.title }}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="/assets/css/bootstrap.css" rel="stylesheet"> <link href="/assets/css/custom.css" rel="stylesheet"> - - <script type="text/javascript"> - var _gaq = _gaq || []; - _gaq.push(['_setAccount', 'UA-6981296-7']); - _gaq.push(['_trackPageview']); - - (function() { - var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; - var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); - })(); - </script> + {% include ga.html %} </head> <body> - - <div class="navbar navbar-inverse navbar-fixed-top"> - <div class="navbar-inner"> - <div class="container"> - <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> - <span class="icon-bar"></span> - <span class="icon-bar"></span> - <span class="icon-bar"></span> - </button> - <a class="brand" href="/">mhack</a> - <div class="nav-collapse collapse"> - <ul class="nav"> - <li class=""> - <a href="/">home</a> - </li> - <li class=""> - <a href="/contato.html">contato</a> - </li> - </ul> - </div> - </div> - </div> - </div> + {% include navbar.html %} <br/> <br/> <div class="container"> <div class="row"> + <!-- main content --> <div class="span8"> {{ content }} </div> - <div class="span4"> - <!--Sidebar content--> + <!-- side bar --> + <div class="span2 hidden-phone"> + {% include twitter_widget.html %} </div> </div> </div> <script src="/assets/js/jquery-1.9.0.js"></script> <script src="/assets/js/bootstrap.js"></script> </body> </html> \ No newline at end of file diff --git a/_layouts/post.html b/_layouts/post.html index 6df4a59..f01ca11 100644 --- a/_layouts/post.html +++ b/_layouts/post.html @@ -1,55 +1,18 @@ --- layout: default --- -<!-- Post Header --> +<!-- post header --> <h1><a href="{{ page.url }}">{{ page.title }}</a></h1> <p class="small"><i class="icon-time"></i> {{ page.date | date: "%Y-%m-%d %H:%M" }}</p> -<!-- Post Content (start) --> -{{ content }} -<!-- Post Content (end) --> - -<div class="row"> - <!-- Facebook --> - <div class="span8"> - <div class="fb-like" data-send="true" data-width="450" data-show-faces="false"> - </div> - </div> - - <br/> - <br/> - - {% unless page.comments == false %} - <!-- Disqus --> - <div class="span8"> - <div id="disqus"> - <div id="disqus_thread"></div> - - <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> - <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> - </div> - </div> - {% endunless %} +<div class="post"> + {{ content }} </div> -<div id="fb-root"></div> -<script> - (function(d, s, id) { - var js, fjs = d.getElementsByTagName(s)[0]; - if (d.getElementById(id)) return; - js = d.createElement(s); js.id = id; - js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; - fjs.parentNode.insertBefore(js, fjs); - }(document, 'script', 'facebook-jssdk')); -</script> +{% include facebook_div.html %} +{% include facebook_script.html %} + +<br/> <!-- uhhhh --> -{% unless page.comments == false %} -<script type="text/javascript"> - var disqus_shortname = 'mhack'; - (function() { - var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; - dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; - (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); - })(); -</script> -{% endunless %} +{% include disqus_div.html %} +{% include disqus_script.html %} diff --git a/_posts/2009-05-05-amazon-web-services-leva-a-educacao-as-nuvens.md b/_posts/2009-05-05-amazon-web-services-leva-a-educacao-as-nuvens.md index 8863a06..5aa8d13 100644 --- a/_posts/2009-05-05-amazon-web-services-leva-a-educacao-as-nuvens.md +++ b/_posts/2009-05-05-amazon-web-services-leva-a-educacao-as-nuvens.md @@ -1,28 +1,27 @@ --- layout: post title: Amazon Web Services leva a educação às núvens date: 2009-05-05 12:56:47 UTC updated: 2009-05-05 12:56:47 UTC -comments: false categories: cloud --- É fato que a Amazon saiu na frente no mercado de [Cloud Computing](http://en.wikipedia.org/wiki/Cloud_computing) com seu serviço [Amazon Web Services](http://aws.amazon.com/). O serviço foi lançado em 2006, mas foi em meados de 2008 que passou a ganhar mais destaque devido ao grande interesse do mercado na chamada computação em nuvem, que basicamente é a venda de recursos computacionais como serviço na Internet. E ainda não há no mercado um sistema tão simples de usar e com um esquema de tarifação tão atrativo como o da Amazon. No serviço Elastic Cloud Computing, ou EC2, basicamente a Amazon cobra por tempo de uptime de uma "máquina", chamada instância. Uma instância *small* por exemplo, com capacidade computacional equivalente a um computador com processador AMD Opteron(tm) Dual-Core de 2.5GHz com 2GB custa US$ 0,10 por hora para Linux e Unix, e US$ 0,125 para instâncias Windows, além dos custos de tráfego de rede e armazenamento (ver [EC2 pricing](http://aws.amazon.com/ec2/#pricing)). Mas o serviço EC2 é apenas um dos 15 [serviços oferecidos](http://aws.amazon.com/products/) atualmente. O mais interessante é que você pode subir quantas instâncias quiser com um único comando. Em questão de segundos uma ou "n" máquinas estão no ar, pode-se criar imagens customizadas com todo o software necessário e simplesmente dar um comando como ec2-run-instances -n 50 ami-id para subir 50 instâncias da imagem identificada com `ami-id` na nuvem. Dai pra frente você acessa a console das máquinas via SSH ou Terminal Services. E o melhor, pagando US$ 5,00 por hora por um recurso computacional equivalente a 50 computadores Dual-Core e 100GB de memória ao todo! Imagine ter que alugar ou comprar essas máquinas, switches e roteadores, instalar o sistema operacional e programas necessários nas 50 máquinas, e etc, etc, etc. Pra quem rala pra conseguir meia-dúzia de máquinas no laboratório da empresa sabe o que isso significa. E pra melhorar ainda mais essa oferta a Amazon lançou um [programa educacional](http://aws.amazon.com/education/), onde professores e estudantes podem utilizar a nuvem para lecionar disciplinas relacionadas a computação e desenvolver projetos acadêmicos, e de graça! Cada professor pode ter até 2 disciplinas simultâneas, com US$ 100,00 de crédito para cada aluno usar durante até 1 ano. Chega de brigar com os laboratoristas para instalar o programa X, liberar as portas Y e Z, e todos os percalços que todo professor e estudante já tiveram que lidar para conseguir recursos nos laboratórios da faculdade. Tenho certeza que esse tipo de infraestrutura motivaria muito os estudantes de computação, além de ser uma tecnologia "em alta" e com toda certeza uma tendência sem volta para o mercado, os estudantes têm a sua disposição uma capacidade computacional e um ambiente de desenvolvimento que apenas grandes empresas poderiam bancar. É claro que esse tipo de inciativa visa formar profissionais capacitados a trabalhar nesse novo ambiente, é um investimento que com certeza retornará para a Amazon na forma de novos clientes que só poderão utilizar esse tipo de serviço se puderem contar com mão-de-obra capacitada. Mas independente da plataforma, interface e produtos específicos que a Amazon oferece atualmente, os conceitos utilizados para o desenvolvimento de aplicações para rodar nesse tipo ambiente servirá para qualquer outra nuvem, seja o [Google App Engine](http://appengine.google.com/), [Sun Cloud Computing](http://www.sun.com/solutions/cloudcomputing/index.jsp), ou até mesmo na sua "nuvenzinha particular" criada com o promissor projeto open source [Eucalyptus](http://open.eucalyptus.com/). Parabéns pela iniciativa da Amazon e boa sorte para os professores, estudantes e profissionais que decidirem aceitar o desafio e sair na frente nessa nova e excitante era da computação!
damian/jQuery-Colour-Swatch
b065583eb9eb9915ca63fc211120f13f112b5a43
Some refining of column logic
diff --git a/colourpicker.html b/colourpicker.html index 3e87fe1..ef6d2ad 100644 --- a/colourpicker.html +++ b/colourpicker.html @@ -1,74 +1,74 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-UK" dir="ltr"> <head> <title>jQuery Colour Swatch</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" language="Javascript" src="colourpicker.js"></script> <script type="text/javascript" language="Javascript"> $(document).ready(function() { var colour = $('input#choose_your_colour'); - colour.colourPicker({ colourInput : true, colours: ['magenta', 'blue', 'pink', 'yellow'] }); - // colour.colourPicker({colours: ['magenta', 'blue', 'pink', 'yellow']}); + // colour.colourPicker({ colourInput : true, colours: ['magenta', 'blue', 'pink', 'yellow'] }); + colour.colourPicker({colours: ['magenta', 'blue'] }); // colour.colourPicker(); }); </script> <style type="text/css" media="screen"> div#colour-swatch, label, input { float: left; display: block; clear: both; } div#colour-swatch { padding: 4px; border: 1px solid #CCCCCC; background-color: #333333; display: none; } div#colour-swatch table { border-collapse: collapse; } div#colour-swatch table td { width: 12px; height: 14px; cursor: pointer; border: 1px solid black; margin: 1px; float: left; display: block; } div#colour-swatch table td:hover { border: 1px solid #FFFF00; } div#colour-swatch table tbody tr { - width: 70px; +/* width: 70px;*/ height: 25px; background-color: white; float: left; display: block; } div#colour-swatch table tbody tr#colour-preview { margin-left: 1px; margin-top: 3px; border: 1px solid black; } </style> </head> <body> <label for="choose_your_colour">Choose your colour</label> <input type="text" name="choose_your_colour" value="" id="choose_your_colour"> <div id="colour-swatch"></div> </body> </html> diff --git a/colourpicker.js b/colourpicker.js index 5365cd3..d04b900 100644 --- a/colourpicker.js +++ b/colourpicker.js @@ -1,62 +1,76 @@ (function($) { $.fn.colourPicker = function(options) { var defaults = { colours: ['red', 'blue', 'yellow', 'green', 'purple', 'orange', 'grey', 'magenta'], colourInput : true, - columns: 4 + columns: 4 }; + + if (options) { + if (options.colours) { + if (options.colours.length < defaults.columns) { + options.columns = options.colours.length; + } + } + + if (options.columns) { + if (options.columns % 2 != 0 && defaults.colours.length % 2 == 0) { + options.columns = options.columns - 1; + } + } + } var options = $.extend(defaults, options); return this.each(function() { obj = $(this); var _flag = false; var _append = false obj.bind('focus', function(){ if (!_append) { $('div#colour-swatch').fadeIn('slow').append(createTable(defaults.colours, defaults.columns)); - $('div#colour-swatch table tbody tr#colour-preview').css({ 'width' : $('div#colour-swatch table thead').width()-5 }) + $('div#colour-swatch table tbody tr#colour-preview').css({ 'width' : $('div#colour-swatch table thead').width()-4 }) _append = true; _flag = true; } if (!_flag) { $('div#colour-swatch').fadeIn('slow'); _flag = true; } }); obj.bind('blur', function(){ if (_flag) { $('div#colour-swatch').fadeOut('slow'); _flag = false; } }); $('div#colour-swatch table thead td').live('click', function(){ rel = $(this).attr('value'); obj.val(rel); if (defaults.colourInput) { obj.css({ 'background-color' : rel }); } $('div#colour-swatch').fadeOut('slow'); _flag = false; }); $('div#colour-swatch table thead td').live('mouseover', function(){ $('div#colour-swatch table tbody tr#colour-preview').css({ 'background-color' : $(this).attr('value') }); }); function createTable(array, columns) { var html = '<table><thead><tr>'; for (var i=0; i < array.length; i++) { if (i!=0 && i%columns==0) { html += '</tr><tr>'; } html += '<td style="background-color: ' + array[i] + ';" value="' + array[i] +'">&nbsp;</td>' }; html += '</tr></thead><tbody><tr id="colour-preview"></tr></tbody></table>'; return html; } }); } })(jQuery); \ No newline at end of file
Kyahx/remotecontrol
86ec23bf8ed0cb8c0e4646ef08a4a7532d15e120
inital code
diff --git a/RemoteControl.lua b/RemoteControl.lua new file mode 100644 index 0000000..c3f5ec4 --- /dev/null +++ b/RemoteControl.lua @@ -0,0 +1,159 @@ +--[[------------------------------------------------------------------------- + Copyright (c) 2009, Kyahx + All rights reserved. +---------------------------------------------------------------------------]] + +local addon = CreateFrame"Frame" + +local _tostring = tostring +local function argstostring(v, ...) v = _tostring(v) if select('#', ...) == 0 then return v end return v..", "..argstostring(...) end +function addon:Print(...) ChatFrame1:AddMessage("|cff33ff99RemoteControl:|r "..argstostring(...)) end +function addon:Debug(...) ChatFrame1:AddMessage("|cffff0000RemoteControl Debug:|r "..argstostring(...)) end + +local OnEvent = function(self, event, ...) + if self[event] then self[event](self, ...) end + if self[self.mode] and self[self.mode][event] then self[self.mode][event](self, ...) end +end + +addon:SetScript("OnEvent", OnEvent) +addon:RegisterEvent"ADDON_LOADED" + +_G['RC'] = addon + +--[[------------------------------------------------------------------------- + Core +---------------------------------------------------------------------------]] + +function addon:ADDON_LOADED(addon) + if addon ~= "RemoteControl" then return end + + self:RegisterEvent("CHAT_MSG_ADDON") + + self:RegisterEvent("CONFIRM_SUMMON") + self:RegisterEvent("DUEL_REQUESTED") + self:RegisterEvent("PARTY_INVITE_REQUEST") + self:RegisterEvent("PLAYER_REGEN_ENABLED") + self:RegisterEvent("QUEST_ACCEPT_CONFIRM") + self:RegisterEvent("QUEST_DETAIL") + self:RegisterEvent("RESURRECT_REQUEST") + self:RegisterEvent("START_LOOT_ROLL") + self:RegisterEvent("UNIT_SPELLCAST_START") + + self.playerName = UnitName("player") + if GetPartyLeaderIndex() > 0 then + self:SetLeader(UnitName("party"..GetPartyLeaderIndex())) + else + self:SetLeader(self.playerName) + end + + self.mounts = {} + for i=1,24 do + local name = select(2,GetCompanionInfo("MOUNT", i)) + if name ~= nil then self.mounts[name] = i end + end + + self:SetupLeaderHooks() + + self:UnregisterEvent("ADDON_LOADED") + self.ADDON_LOADED = nil +end + +function addon:SetupLeaderHooks() + local hooks = { "CameraOrSelectOrMoveStart", "MoveAndSteerStart", "MoveBackwardStart", + "MoveForwardStart", "MoveViewDownStart", "MoveViewInStart", "MoveViewLeftStart", + "MoveViewOutStart", "MoveViewRightStart", "MoveViewUpStart", "JumpOrAscendStart", + "PitchDownStart", "PitchUpStart", "SitStandOrDescendStart", "StartAttack", "StrafeLeftStart", + "StrafeRightStart", "TargetNearestEnemy", "TurnLeftStart", "TurnOrActionStart", "TurnRightStart" } + + local updateLead = function() if self.leader ~= self.playerName then self:SendComm("SetLeader") end end + for _,func in pairs(hooks) do hooksecurefunc(_G, func, updateLead) end + + hooksecurefunc(_G, "JumpOrAscendStart", function() self:SendComm("Regroup") end) +end + +function addon:SendComm(msg) + local distro, target = "PARTY", nil + + --if GetNumPartyMembers() == 0 and IsInGuild() then distro = "GUILD" end + --if UnitIsFriend("target","player") == 1 then distro = "WHISPER" target = UnitName("target") end + + SendAddonMessage("RemoteControl", msg, distro, target) +end + +function addon:CHAT_MSG_ADDON(prefix, msg, channel, sender) + if (prefix ~= "RemoteControl") then return end + OnEvent(self, msg, sender) +end + +function addon:SetLeader(name, skip) + name = name or self.playerName + if name == self.playerName then + self.mode = "lead" + else + self.mode = "follow" + end + self.leader = name + self:Regroup() +end + +function addon:Regroup() + if not InCombatLockdown() then self:SendComm("PLAYER_REGEN_ENABLED") end +end + +function addon:PARTY_INVITE_REQUEST(name) + AcceptGroup() + StaticPopup_Hide("PARTY_INVITE") + self:SetLeader(name) +end + +--[[------------------------------------------------------------------------- + Leader +---------------------------------------------------------------------------]] + +local leader = {} +addon.lead = leader + +function leader:UNIT_SPELLCAST_START(unit, spell) + if self.mounts[spell] and unit == "player" then self:SendComm("Mount") end +end + +--[[------------------------------------------------------------------------- + Follower +---------------------------------------------------------------------------]] + +local follower = {} +addon.follow = follower + +function follower:Mount() + if not IsMounted() then CallCompanion("MOUNT", 1) end +end + +function follower:CONFIRM_SUMMON() + ConfirmSummon() + StaticPopup_Hide("CONFIRM_SUMMON") +end + +function follower:DUEL_REQUESTED() + CancelDuel() + StaticPopup_Hide("DUEL_REQUESTED") +end + +function follower:PLAYER_REGEN_ENABLED() + if not InCombatLockdown() then FollowUnit(self.leader) end +end + +function follower:QUEST_ACCEPT_CONFIRM() + ConfirmAcceptQuest() +end + +function follower:QUEST_DETAIL() + AcceptQuest() +end + +function follower:RESURRECT_REQUEST() + AcceptResurrect() +end + +function follower:START_LOOT_ROLL(lootIndex) + RollOnLoot(lootIndex,0) +end \ No newline at end of file diff --git a/RemoteControl.toc b/RemoteControl.toc new file mode 100644 index 0000000..676c59a --- /dev/null +++ b/RemoteControl.toc @@ -0,0 +1,7 @@ +## Interface: 30000 +## Title: RemoteControl +## Notes: Remote control for multi-boxing +## Author: Kyahx +## Version: 1.0 + +RemoteControl.lua
rgee/HFOSS-Dasher
d4d75616ebfdc9b0263fe7d2e263592d04d1c761
File dialog now closes when you hit cancel. We weren't checking the response.
diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 0ccb88e..3be0421 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -125,1032 +125,1036 @@ dasher_main_class_init(DasherMainClass *pClass) { G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } g_message("loading interface"); dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); pPrivate->pGameDisplay = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "GameDisplay")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); gtk_dasher_control_set_game_display(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), pPrivate->pGameDisplay); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // /** * Clear all text out of the dasher editor. * @param pSelf a reference to an instance of DasherMain */ void clear_dasher_editor_text(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } /** * Start game mode, specify the text to play with, and clear out any text in the dasher editor. * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. * * @param pGameTextFilePath - the absolute path to the text file to play with * @param pSelf - a reference to an instance of DasherMain */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkDasherControl *pControl = GTK_DASHER_CONTROL(pPrivate->pDasherWidget); gtk_widget_set_visible(GTK_WIDGET(pPrivate->pGameDisplay), true); dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); clear_dasher_editor_text(pSelf); } void init_game_from_default_button(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { init_game_mode(_(""), (DasherMain*)pData); //TODO: this is really ugly - clearly symptomatic of doing something wrong with GTK //but I can't figure out what. For now, it makes the UI behave properly. gtk_widget_destroy(gtk_widget_get_parent( gtk_widget_get_parent( (gtk_widget_get_parent(GTK_WIDGET(pButton)))))); } /** * Event handler which displays a standard GTK file dialog. The dialog allows the user * to specify a text file to play game mode with. * * @param pButton the button that fired the event * @param pWidget reference needed by GTK for callback signature * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references * to the dialog's parent window and an instance of DasherMain */ void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); - if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { + gint response = gtk_dialog_run(GTK_DIALOG(pFileDialog)); + + if(response == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); - } + } else if( response == GTK_RESPONSE_CANCEL ) { + gtk_widget_destroy(GTK_WIDGET(objRefs->first)); + } } void quit_game_mode(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE((DasherMain*)pData); } /** * Toggle game mode on and off. Toggling on causes a dialog box to be displayed * welcoming the user to game mode and prompting them to specify a file to play with. * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core * to respond appropriately. * * @param pSelf a reference to an instance of DasherMain */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), GTK_RESPONSE_NONE); gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK(init_game_from_default_button), pSelf); g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Are you sure you wish to turn off game mode? All unsaved changes will be lost.")); GtkWidget *pNoButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_NO, GTK_RESPONSE_REJECT); GtkWidget *pYesButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_YES, GTK_RESPONSE_ACCEPT); //g_signal_connect(pYesButton, "button-press-event", G_CALLBACK(quit_game_mode), (gpointer)pSelf); switch(gtk_dialog_run(GTK_DIALOG(pDialog))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialog)); break; case GTK_RESPONSE_ACCEPT: dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); clear_dasher_editor_text(pSelf); } if(GTK_IS_WIDGET(pDialog)) { gtk_widget_destroy(GTK_WIDGET(pDialog)); } } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; } } else { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Are you sure you wish to quit?")); gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't quit"), GTK_RESPONSE_REJECT, _("Quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialogue));
rgee/HFOSS-Dasher
440e0383c5af22dd3e9be81e225e5b56366677d5
Improved documentation in various places. Fixed innacuracies caused by code and docs being out of sync.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index 36b414a..e6d99d7 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,122 +1,122 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif #include <sstream> void CEventHandler::InsertEvent(CEvent *pEvent) { //put the event at the end of the queue EnqueueEvent(pEvent); //if we are already dispatching events, don't do it again //this is necessary to keep recursive calls from removing //events from the queue while we iterate over it if(m_bIsDispatching) { return; } else { ProcessEventQueue(); } } void CEventHandler::ProcessEventQueue() { //iterate over the event queue until it's empty while(!m_qEventQueue.empty()) { CEvent *currEvent = m_qEventQueue.front(); m_qEventQueue.pop(); m_pInterface->InterfaceEventHandler(currEvent); m_pInterface->ExternalEventHandler(currEvent); //entering the dispatching loop - no longer safe to modify m_vSpecificListeners m_bIsDispatching = true; //dispatch the event at the front of the queue to all registered listeners for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[currEvent->m_iEventType - 1].begin(); it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); ++it) { (*it)->HandleEvent(currEvent); } //done dispatching this event - safe to modify m_vSpecificListeners m_bIsDispatching = false; //register all listeners that have been waiting to be added for(EvtListenerCollection::iterator it = m_vPendingSpecificReg.begin(); it != m_vPendingSpecificReg.end(); ++it) RegisterListener((*it).first, (*it).second); //unregister all that have been waiting to be removed for(EvtListenerCollection::iterator it = m_vPendingSpecificUnreg.begin(); it != m_vPendingSpecificUnreg.end(); ++it) UnregisterListener((*it).first, (*it).second); m_vPendingSpecificUnreg.clear(); m_vPendingSpecificReg.clear(); } } void CEventHandler::EnqueueEvent(CEvent *pEvent) { m_qEventQueue.push(pEvent); } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { if(m_bIsDispatching) { // Add the listener to the pending set if events are being dispatched m_vPendingSpecificReg.push_back(std::make_pair(pListener, iEventType)); } // Only try to add a new listener if it doesn't already exist in the Listener map else if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { m_vSpecificListeners[iEventType - 1].push_back(pListener); } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { + for(int curEvtType = 1; curEvtType <= NUM_EVENTS; curEvtType++) { RegisterListener(pListener, curEvtType); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { if(!m_bIsDispatching) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType - 1].begin(); it != m_vSpecificListeners[iEventType - 1].end(); ++it) { if((*it) == pListener) { m_vSpecificListeners[iEventType - 1].erase(it); break; } } } else { m_vPendingSpecificUnreg.push_back(std::make_pair(pListener, iEventType)); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { - for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { + for(int curEvtType = 1; curEvtType <= NUM_EVENTS; curEvtType++) { UnregisterListener(pListener, curEvtType); } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 5d49b2f..36df367 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,167 +1,167 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ /** * This class handles the dispatch and management of events throughout Dasher. * Any class that derives from CDasherComponent can subscribe to events. These * events are enumerated in Event.h. All CDasherComponents are automatically * registered for their selected events on construction. * * Components SHOULD specify exactly which events they're interested in * instead of omitting this information. This allows the event management * system to make optimal use of time in dispatching events. (i.e. cuts * down on unused event dispatching) */ class Dasher::CEventHandler { public: - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(NUM_EVENTS), m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. - for(int i = 0; i < m_iNUM_EVENTS; i++) { + for(int i = 0; i < NUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. * * @warning If this is called from an Event Handler, (i.e. While events * are being processed) the event is enqueued to be dispatched * and NOT immediately dispatched. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for all events. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; /** * Dispatch all the events in the event queue, and take * care of all the pending additions/deletions to m_vSpecificListeners * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and * m_vPendSpecificUnreg */ void ProcessEventQueue(); /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ - const int m_iNUM_EVENTS; + //const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 8d54d79..affc325 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,58 +1,60 @@ #include "FileWordGenerator.h" #include "DasherInterfaceBase.h" using namespace Dasher; bool CFileWordGenerator::Generate() { if(!m_sFileHandle.is_open()) { m_sFileHandle.open(m_sPath.c_str()); } if(m_sFileHandle.fail()) { throw std::runtime_error("File: " + m_sPath + " cannot be read."); } m_uiPos = 0; m_sGeneratedString.clear(); if(m_sFileHandle.eof()) { return false; } else if(m_sFileHandle.good()) { std::getline(m_sFileHandle, m_sGeneratedString); return true; } else { return false; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")+1); } std::string CFileWordGenerator::GetNextWord() { if(m_uiPos >= m_sGeneratedString.length()) { // Attempt to reload the buffer. - if(!Generate()) return ""; + if(!Generate()) { + return ""; + } } size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); std::string result; - // If there are no space characters. + // If there are no space characters. if(found != string::npos) { result = m_sGeneratedString.substr(m_uiPos, found); m_uiPos += (found + 1); } else { result = m_sGeneratedString.substr(m_uiPos); m_uiPos = m_sGeneratedString.length(); }; return result; } diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index fffef4a..3156b21 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,113 +1,115 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> #include <stdexcept> using namespace std; #include "WordGeneratorBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE - * kept open for the lifetime of this object and the size of the file + * kept open for the lifetime of this object but the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all - * at once. + * at once. It's highly unlikely anyone will ever have a text file + * large enough to fill the memory allocated to Dasher by the OS where + * the text is one giant line. */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string sPath, int iRegen) : m_sPath(sPath), CWordGeneratorBase(iRegen) { Generate(); } CFileWordGenerator(std::string sPath) : m_sPath(sPath), CWordGeneratorBase() { Generate(); } virtual ~CFileWordGenerator() { m_sFileHandle.close(); } /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string if there are no more * words. * @throw Throws an exception if the file cannot be read. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter. Returns the file name and extension, without * any slashes. * @return The actual name of the file being read from */ std::string GetFilename(); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * The generator function. Reads words from the specified file. * @return True if generating the new buffer was successful, * false if we've reached the end of the file. * @throw Throws an exception if the file cannot be read. */ bool Generate(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Src/DasherCore/GameDisplay.h b/Src/DasherCore/GameDisplay.h index 6ef87b6..d2487d9 100644 --- a/Src/DasherCore/GameDisplay.h +++ b/Src/DasherCore/GameDisplay.h @@ -1,48 +1,48 @@ #ifndef _GameDisplay_H_ #define _GameDisplay_H_ #include <vector> #include <string> using namespace std; namespace Dasher { /** * A class which allows GameModule to display formatted * information in a separate area on the screen. Currently, * the only information it can display is a color coded * representation of the current text chunk (see DispayChunkText). * There is a lot of room for extending this to support new features, * different types of games, etc. */ class CGameDisplay { public: CGameDisplay() {} /** TODO: Improve this documentation * Display a colored sequence of characters in the game display window. * @param text the sequence of characters * @param colors the color to give each index of text */ virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors) = 0; /** * Hide the display and clear the text in the label. */ - virtual void hide() = 0; + virtual void Hide() = 0; /** * Display a dialog alerting the user about something * related to game mode. */ - virtual void alert(std::string message) = 0; + virtual void Alert(std::string message) = 0; }; } #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index cc3e050..5cbe71a 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,206 +1,205 @@ #include "GameModule.h" -#include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, }; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: { // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; DecorateDisplay(); m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; } } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; if(m_pGameDisplay) - m_pGameDisplay->hide(); + m_pGameDisplay->Hide(); if(m_pWordGenerator) delete m_pWordGenerator; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); std::string nextWord; for(int i = 0; i < m_iTargetChunkSize; i++) { nextWord = m_pWordGenerator->GetNextWord(); //done with game text if(nextWord == "") { m_sTargetString = ""; - m_pGameDisplay->alert("Congratulations! You've completed Dasher game mode!"); + m_pGameDisplay->Alert("Congratulations! You've completed Dasher game mode!"); m_pEventHandler->InsertEvent(new CGameModeCompleteEvent()); return; } else { m_sTargetString += nextWord; m_sTargetString += " "; } } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); DecorateDisplay(); } void CGameModule::DecorateDisplay() { if(m_pGameDisplay == NULL) return; std::vector<std::string> colors = std::vector<std::string>(); for(int pos = 0; pos < m_sTargetString.length(); pos++) { if(pos < m_iCurrentStringPos + 1) { colors.push_back("blue"); } else if(pos == m_iCurrentStringPos + 1) { colors.push_back("red"); } else { colors.push_back("black"); } } m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { m_pGameDisplay = pGameDisplay; } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 816374e..c9ce043 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,244 +1,245 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" #include "GameDisplay.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful - * arrow to guide them in the right path through the dasher model. + * crosshair to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * - * This class handles logic and drawing code with respect to the above. + * This class handles logic with respect to the above. It handles drawing to the dasher display, + * but delegates platform specific UI modifications to a CDasherDisplay. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, Dasher::CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pInterface(pInterface), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { } ~CGameModule() { m_pSettingsStore->SetBoolParameter(BP_GAME_MODE, false); } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); /** * Set the word generator for this instance to draw words from. * @param pWordGenerator the word generator to be used */ void SetWordGenerator(CWordGeneratorBase *pWordGenerator); /** * Reset the game module. This makes the game module invalid until it is provided * with a new WordGenerator. */ void reset(); void SetGameDisplay(CGameDisplay *pGameDisplay); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /** * Update the game display. */ void DecorateDisplay(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * The display widget that this module is using to draw its UI. */ CGameDisplay *m_pGameDisplay; /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase *m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ Dasher::CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /** * Flag that denotes whether we are approximating the target position * or not. */ bool m_bApproximating; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ static const int vEvents[3]; }; } #endif diff --git a/Src/Gtk2/GtkGameDisplay.cpp b/Src/Gtk2/GtkGameDisplay.cpp index 9a54011..7d3d0b7 100644 --- a/Src/Gtk2/GtkGameDisplay.cpp +++ b/Src/Gtk2/GtkGameDisplay.cpp @@ -1,35 +1,35 @@ #include "GtkGameDisplay.h" using namespace std; void GtkGameDisplay::DisplayChunkText(std::string text, std::vector<std::string>& colors) { std::string markup = "<span font-weight = \"bold\" font_size = \"xx-large\">"; for(int pos = 0; pos < text.length(); pos++) { markup += "<span foreground = \""+ colors[pos]+"\">"+text.substr(pos, 1)+"</span>"; } markup += "</span>"; gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), markup.c_str()); } -void GtkGameDisplay::hide() { +void GtkGameDisplay::Hide() { gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), ""); gtk_widget_set_visible(GTK_WIDGET(m_pContainer), false); } -void GtkGameDisplay::alert(std::string message) { +void GtkGameDisplay::Alert(std::string message) { GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_OK, message.c_str() ); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(GTK_WIDGET(dialog)); } diff --git a/Src/Gtk2/GtkGameDisplay.h b/Src/Gtk2/GtkGameDisplay.h index f2bb6ef..c3f891a 100644 --- a/Src/Gtk2/GtkGameDisplay.h +++ b/Src/Gtk2/GtkGameDisplay.h @@ -1,39 +1,44 @@ #include "../DasherCore/GameDisplay.h" #include <gtk/gtk.h> #include <string> #include <cstring> class GtkGameDisplay : public Dasher::CGameDisplay { public: /** * @param pContainer - the table that all of the * widgets for the game display live in */ GtkGameDisplay(GtkWidget *pContainer) : Dasher::CGameDisplay(), m_pContainer(pContainer) { m_pChunkDisplay = gtk_label_new(NULL); gtk_container_add(GTK_CONTAINER(m_pContainer), m_pChunkDisplay); gtk_widget_set_visible(m_pChunkDisplay, true); } virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors); - virtual void hide(); + virtual void Hide(); - virtual void alert(std::string message); + virtual void Alert(std::string message); private: /** * The Gtk table containing the game mode UI. */ GtkWidget *m_pContainer; + + + /** + * The label object used to display the text. + */ GtkWidget *m_pChunkDisplay; };
rgee/HFOSS-Dasher
41851e9ec71a5527270ebfbbabeee3612469319f
Cleaned up game module switch and fixed some documentation on events.
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 52d0154..4b20de1 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,228 +1,227 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; class CNoGameNodeEvent; class CGameModeCompleteEvent; } /* * The enumeration of event types. Whenever you add a new event type, * you must add its enum representation here. You must also make sure - * to change the constant in EventHandler that refers to the number of events - * or you will likely get errors. + * to change the number of events or you will likely get errors. */ enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, EV_GAME_MODE_COMPLETE, NUM_EVENTS = 13 }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; /** * This is an event to signal that the user has finished typing the game mode * target. Appropriate action should be taken by visual components to * congratulate them in response to this evt. */ class Dasher::CGameModeCompleteEvent : public Dasher::CEvent { public: CGameModeCompleteEvent() { m_iEventType = EV_GAME_MODE_COMPLETE; } }; /** An event that represents when the game target node cannot be found * among the current last-typed node's children. Since the set of child * nodes is a set consisting of all possible characters in the current * alphabet, the only way for it not to exist at all is if it was not * drawn yet. */ class Dasher::CNoGameNodeEvent : public Dasher::CEvent { public: CNoGameNodeEvent(std::pair<CDasherNode*, CDasherNode*> pNodes) : m_pNodes(pNodes) { m_iEventType = EV_NO_GAME_NODE; } /** * The pair of nodes that represent the closest drawn nodes to the top * and bottom of where the target node /should/ be. * * If the left of this pair is null, the target node is at the top-most * node in the current subtree of the model (in Dasher space). * * Conversely, if the right of this pair is null, the target node exists * at the bottom of the current subtree of the model. */ std::pair<CDasherNode*, CDasherNode*> m_pNodes; }; /** * An event that notifies listeners that a node previously flagged for * game mode has been drawn. */ class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; /** * The node itself. */ CDasherNode* m_pNode; /** * the coordinates at which m_pNode was drawn. */ screenint m_iX, m_iY; /** * View object for manipulating the screen. */ CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 727f34a..cc3e050 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,216 +1,206 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, }; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { - case EV_NO_GAME_NODE: - { - CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); - } case EV_EDIT: { - CEditEvent* evt = static_cast<CEditEvent*>(pEvent); + CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: + { // Check if the typed character is correct - if(CharacterFound(evt)) { + if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; - DecorateDisplay(); + DecorateDisplay(); m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; - // Removed a character (Stepped one node back) - case 0: - break; - default: - break; + } } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; - default: - break; - } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; if(m_pGameDisplay) m_pGameDisplay->hide(); if(m_pWordGenerator) delete m_pWordGenerator; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); std::string nextWord; for(int i = 0; i < m_iTargetChunkSize; i++) { nextWord = m_pWordGenerator->GetNextWord(); //done with game text if(nextWord == "") { m_sTargetString = ""; m_pGameDisplay->alert("Congratulations! You've completed Dasher game mode!"); m_pEventHandler->InsertEvent(new CGameModeCompleteEvent()); return; } else { m_sTargetString += nextWord; m_sTargetString += " "; } } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); DecorateDisplay(); } void CGameModule::DecorateDisplay() { if(m_pGameDisplay == NULL) return; std::vector<std::string> colors = std::vector<std::string>(); for(int pos = 0; pos < m_sTargetString.length(); pos++) { if(pos < m_iCurrentStringPos + 1) { colors.push_back("blue"); } else if(pos == m_iCurrentStringPos + 1) { colors.push_back("red"); } else { colors.push_back("black"); } } m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { m_pGameDisplay = pGameDisplay; }
rgee/HFOSS-Dasher
4e04baa4ecd63d39004e0e46a7f3d6ec636467f0
Got the edtior text to clear when game finishes.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index b62a10b..76ae20f 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,875 +1,877 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <tr1/memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; m_pGameDisplay = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); InitGameModule(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); case BP_GAME_MODE: if(GetBoolParameter(BP_GAME_MODE)) { InitGameModule(); } else if(m_pGameModule){ CreateModel(0); ResetGameModule(); } default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); + + g_pLogger->Log(strCurrentContext); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } else if(pEvent->m_iEventType == EV_GAME_MODE_COMPLETE) { SetBoolParameter(BP_GAME_MODE, false); Pause(); } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule && GetBoolParameter(BP_GAME_MODE)) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } diff --git a/Src/DasherCore/GameDisplay.h b/Src/DasherCore/GameDisplay.h index 6ef87b6..70321b8 100644 --- a/Src/DasherCore/GameDisplay.h +++ b/Src/DasherCore/GameDisplay.h @@ -1,48 +1,54 @@ #ifndef _GameDisplay_H_ #define _GameDisplay_H_ #include <vector> #include <string> using namespace std; namespace Dasher { /** * A class which allows GameModule to display formatted * information in a separate area on the screen. Currently, * the only information it can display is a color coded * representation of the current text chunk (see DispayChunkText). * There is a lot of room for extending this to support new features, * different types of games, etc. */ class CGameDisplay { public: CGameDisplay() {} /** TODO: Improve this documentation * Display a colored sequence of characters in the game display window. * @param text the sequence of characters * @param colors the color to give each index of text */ virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors) = 0; /** * Hide the display and clear the text in the label. */ virtual void hide() = 0; /** * Display a dialog alerting the user about something * related to game mode. */ virtual void alert(std::string message) = 0; + + /** + * Clear the dasher editor, as is appropriate when starting + * or ending game mode. + */ + virtual void ClearEditor() = 0; }; } #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 727f34a..cedcebd 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,216 +1,217 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, }; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); } case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; DecorateDisplay(); m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; if(m_pGameDisplay) m_pGameDisplay->hide(); if(m_pWordGenerator) delete m_pWordGenerator; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); std::string nextWord; for(int i = 0; i < m_iTargetChunkSize; i++) { nextWord = m_pWordGenerator->GetNextWord(); //done with game text if(nextWord == "") { m_sTargetString = ""; m_pGameDisplay->alert("Congratulations! You've completed Dasher game mode!"); m_pEventHandler->InsertEvent(new CGameModeCompleteEvent()); + m_pGameDisplay->ClearEditor(); return; } else { m_sTargetString += nextWord; m_sTargetString += " "; } } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); DecorateDisplay(); } void CGameModule::DecorateDisplay() { if(m_pGameDisplay == NULL) return; std::vector<std::string> colors = std::vector<std::string>(); for(int pos = 0; pos < m_sTargetString.length(); pos++) { if(pos < m_iCurrentStringPos + 1) { colors.push_back("blue"); } else if(pos == m_iCurrentStringPos + 1) { colors.push_back("red"); } else { colors.push_back("black"); } } m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { m_pGameDisplay = pGameDisplay; } diff --git a/Src/Gtk2/DasherControl.cpp b/Src/Gtk2/DasherControl.cpp index 1088feb..ca4687c 100644 --- a/Src/Gtk2/DasherControl.cpp +++ b/Src/Gtk2/DasherControl.cpp @@ -1,638 +1,641 @@ #include "../Common/Common.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <iostream> #include "DasherControl.h" #include "Timer.h" #include "../DasherCore/Event.h" #include "../DasherCore/ModuleManager.h" #include "GtkGameDisplay.h" #include <fcntl.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <sys/stat.h> #include <unistd.h> using namespace std; // 'Private' methods (only used in this file) extern "C" gint key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data); extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data); extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data); extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData); extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data); static bool g_iTimeoutID = 0; // CDasherControl class definitions CDasherControl::CDasherControl(GtkVBox *pVBox, GtkDasherControl *pDasherControl) { m_pPangoCache = NULL; m_pScreen = NULL; m_pDasherControl = pDasherControl; m_pVBox = GTK_WIDGET(pVBox); Realize(); // m_pKeyboardHelper = new CKeyboardHelper(this); // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); } void CDasherControl::CreateModules() { CDasherInterfaceBase::CreateModules(); //create default set first // Create locally cached copies of the mouse input objects, as we // need to pass coordinates to them from the timer callback m_pMouseInput = (CDasherMouseInput *) RegisterModule(new CDasherMouseInput(m_pEventHandler, m_pSettingsStore)); SetDefaultInputDevice(m_pMouseInput); m_p1DMouseInput = (CDasher1DMouseInput *)RegisterModule(new CDasher1DMouseInput(m_pEventHandler, m_pSettingsStore)); RegisterModule(new CSocketInput(m_pEventHandler, m_pSettingsStore)); #ifdef JOYSTICK RegisterModule(new CDasherJoystickInput(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CDasherJoystickInputDiscrete(m_pEventHandler, m_pSettingsStore, this)); #endif #ifdef TILT RegisterModule(new CDasherTiltInput(m_pEventHandler, m_pSettingsStore, this)); #endif } void CDasherControl::SetupUI() { m_pCanvas = gtk_drawing_area_new(); #if GTK_CHECK_VERSION (2,18,0) gtk_widget_set_can_focus(m_pCanvas, TRUE); #else GTK_WIDGET_SET_FLAGS(m_pCanvas, GTK_CAN_FOCUS); #endif gtk_widget_set_double_buffered(m_pCanvas, FALSE); GtkWidget *pFrame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(pFrame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(pFrame), m_pCanvas); gtk_box_pack_start(GTK_BOX(m_pVBox), pFrame, TRUE, TRUE, 0); gtk_widget_show_all(GTK_WIDGET(m_pVBox)); // Connect callbacks - note that we need to implement the callbacks // as "C" style functions and pass this as user data so they can // call the object g_signal_connect(m_pCanvas, "button_press_event", G_CALLBACK(button_press_event), this); g_signal_connect(m_pCanvas, "button_release_event", G_CALLBACK(button_press_event), this); g_signal_connect_after(m_pCanvas, "realize", G_CALLBACK(realize_canvas), this); g_signal_connect(m_pCanvas, "configure_event", G_CALLBACK(canvas_configure_event), this); g_signal_connect(m_pCanvas, "destroy", G_CALLBACK(canvas_destroy_event), this); g_signal_connect(m_pCanvas, "key-release-event", G_CALLBACK(key_release_event), this); g_signal_connect(m_pCanvas, "key_press_event", G_CALLBACK(key_press_event), this); g_signal_connect(m_pCanvas, "focus_in_event", G_CALLBACK(canvas_focus_event), this); g_signal_connect(m_pCanvas, "expose_event", G_CALLBACK(canvas_expose_event), this); //g_signal_connect(m_pDasher) // Create the Pango cache // TODO: Use system defaults? if(GetStringParameter(SP_DASHER_FONT) == "") SetStringParameter(SP_DASHER_FONT, "Sans 10"); m_pPangoCache = new CPangoCache(GetStringParameter(SP_DASHER_FONT)); } void CDasherControl::SetupPaths() { char *home_dir; char *user_data_dir; const char *system_data_dir; home_dir = getenv("HOME"); user_data_dir = new char[strlen(home_dir) + 10]; sprintf(user_data_dir, "%s/.dasher/", home_dir); mkdir(user_data_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // PROGDATA is provided by the makefile system_data_dir = PROGDATA "/"; SetStringParameter(SP_SYSTEM_LOC, system_data_dir); SetStringParameter(SP_USER_LOC, user_data_dir); delete[] user_data_dir; } -void CDasherControl::CreateGameDisplay(void* pGameDisplay) { +void CDasherControl::CreateGameDisplay(GtkWidget *pGameDisplay, void *pEditor) { - m_pGameDisplay = new GtkGameDisplay(GTK_WIDGET(pGameDisplay)); + m_pGameDisplay = new GtkGameDisplay(GTK_WIDGET(pGameDisplay), DASHER_EDITOR(pEditor)); InitGameModule(); m_pGameModule->SetGameDisplay(m_pGameDisplay); } void CDasherControl::CreateSettingsStore() { m_pSettingsStore = new CGnomeSettingsStore(m_pEventHandler); } void CDasherControl::ScanAlphabetFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *alphabetglob; alphabetglob = g_pattern_spec_new("alphabet*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(alphabetglob); } void CDasherControl::ScanColourFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *colourglob; colourglob = g_pattern_spec_new("colour*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(colourglob); } CDasherControl::~CDasherControl() { if(m_pMouseInput) { m_pMouseInput = NULL; } if(m_p1DMouseInput) { m_p1DMouseInput = NULL; } if(m_pPangoCache) { delete m_pPangoCache; m_pPangoCache = NULL; } // if(m_pKeyboardHelper) { // delete m_pKeyboardHelper; // m_pKeyboardHelper = 0; // } } bool CDasherControl::FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent) { if((pEvent->type == GDK_FOCUS_CHANGE) && (pEvent->in)) { GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); gboolean *returnType; focusEvent->type = GDK_FOCUS_CHANGE; focusEvent->window = (GdkWindow *) m_pDasherControl; focusEvent->send_event = FALSE; focusEvent->in = TRUE; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "focus_in_event", GTK_WIDGET(m_pDasherControl), focusEvent, NULL, &returnType); } return true; } void CDasherControl::SetFocus() { gtk_widget_grab_focus(m_pCanvas); } void CDasherControl::GameMessageOut(int message, const void* messagedata) { gtk_dasher_control_game_messageout(m_pDasherControl, message, messagedata); } GArray *CDasherControl::GetAllowedValues(int iParameter) { // Glib version of the STL based core function GArray *pRetVal(g_array_new(false, false, sizeof(gchar *))); std::vector < std::string > vList; GetPermittedValues(iParameter, vList); for(std::vector < std::string >::iterator it(vList.begin()); it != vList.end(); ++it) { // For internal glib reasons we need to make a variable and then // pass - we can't use the iterator directly const char *pTemp(it->c_str()); char *pTempNew = new char[strlen(pTemp) + 1]; strcpy(pTempNew, pTemp); g_array_append_val(pRetVal, pTempNew); } return pRetVal; } void CDasherControl::RealizeCanvas(GtkWidget *pWidget) { // TODO: Pointless function - call directly from C callback. #ifdef DEBUG std::cout << "RealizeCanvas()" << std::endl; #endif OnUIRealised(); } void CDasherControl::StartTimer() { // Start the timer loops as everything is set up. // Aim for 40 frames per second, computers are getting faster. if(g_iTimeoutID == 0) { g_iTimeoutID = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 25, timer_callback, this, NULL); // TODO: Reimplement this (or at least reimplement some kind of status reporting) //g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 5000, long_timer_callback, this, NULL); } } void CDasherControl::ShutdownTimer() { // TODO: Figure out how to implement this - at the moment it's done // through a return value from the timer callback, but it would be // nicer to prevent any further calls as soon as the shutdown signal // has been receieved. } int CDasherControl::CanvasConfigureEvent() { GtkAllocation a; #if GTK_CHECK_VERSION (2,18,0) gtk_widget_get_allocation(m_pCanvas, &a); #else a.width = m_pCanvas->allocation.width; a.height = m_pCanvas->allocation.height; #endif if(m_pScreen != NULL) delete m_pScreen; m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache, a.width, a.height); ChangeScreen(m_pScreen); return 0; } void CDasherControl::ExternalEventHandler(Dasher::CEvent *pEvent) { // Convert events coming from the core to Glib signals. if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); HandleParameterNotification(pEvt->m_iParameter); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_changed", pEvt->m_iParameter); } else if(pEvent->m_iEventType == EV_EDIT) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { // Insert event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_insert", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 2) { // Delete event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 10) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_convert"); } else if(pEditEvent->m_iEditType == 11) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_protect"); } } else if(pEvent->m_iEventType == EV_EDIT_CONTEXT) { CEditContextEvent *pEditContextEvent(static_cast < CEditContextEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_context_request", pEditContextEvent->m_iOffset, pEditContextEvent->m_iLength); } else if(pEvent->m_iEventType == EV_START) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_start"); } else if(pEvent->m_iEventType == EV_STOP) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_stop"); } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast < CControlEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_control", pControlEvent->m_iID); } else if(pEvent->m_iEventType == EV_LOCK) { CLockEvent *pLockEvent(static_cast<CLockEvent *>(pEvent)); DasherLockInfo sInfo; sInfo.szMessage = pLockEvent->m_strMessage.c_str(); sInfo.bLock = pLockEvent->m_bLock; sInfo.iPercent = pLockEvent->m_iPercent; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_lock_info", &sInfo); } else if(pEvent->m_iEventType == EV_MESSAGE) { CMessageEvent *pMessageEvent(static_cast<CMessageEvent *>(pEvent)); DasherMessageInfo sInfo; sInfo.szMessage = pMessageEvent->m_strMessage.c_str(); sInfo.iID = pMessageEvent->m_iID; sInfo.iType = pMessageEvent->m_iType; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_message", &sInfo); } else if(pEvent->m_iEventType == EV_COMMAND) { CCommandEvent *pCommandEvent(static_cast<CCommandEvent *>(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_command", pCommandEvent->m_strCommand.c_str()); } else if(pEvent->m_iEventType == EV_GAME_MODE_COMPLETE) { - //TODO: clear the dasher editor text here! + + g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", _(""), 0); + //gtk_dasher_control_set_buffer(m_pDasherControl, 0); + //TODO: clear the dasher editor text here! } }; void CDasherControl::WriteTrainFile(const std::string &strNewText) { if(strNewText.length() == 0) return; std::string strFilename(GetStringParameter(SP_USER_LOC) + GetStringParameter(SP_TRAIN_FILE)); int fd=open(strFilename.c_str(),O_CREAT|O_WRONLY|O_APPEND,S_IRUSR|S_IWUSR); write(fd,strNewText.c_str(),strNewText.length()); close(fd); } // TODO: Sort these methods out void CDasherControl::ExternalKeyDown(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyDown(get_time(), iButtonID); // } KeyDown(get_time(), iKeyVal); } void CDasherControl::ExternalKeyUp(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyUp(get_time(), iButtonID); // } KeyUp(get_time(), iKeyVal); } void CDasherControl::HandleParameterNotification(int iParameter) { switch(iParameter) { case SP_DASHER_FONT: if(m_pPangoCache) { m_pPangoCache->ChangeFont(GetStringParameter(SP_DASHER_FONT)); ScheduleRedraw(); } break; case BP_GLOBAL_KEYBOARD: // TODO: reimplement // if(m_pKeyboardHelper) // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); break; } } int CDasherControl::TimerEvent() { int x, y; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_pointer(gtk_widget_get_window(m_pCanvas), &x, &y, NULL); #else gdk_window_get_pointer(m_pCanvas->window, &x, &y, NULL); #endif m_pMouseInput->SetCoordinates(x, y); gdk_window_get_pointer(gdk_get_default_root_window(), &x, &y, NULL); int iRootWidth; int iRootHeight; gdk_drawable_get_size(gdk_get_default_root_window(), &iRootWidth, &iRootHeight); if(GetLongParameter(LP_YSCALE) < 10) SetLongParameter(LP_YSCALE, 10); y = (y - iRootHeight / 2); m_p1DMouseInput->SetCoordinates(y, GetLongParameter(LP_YSCALE)); NewFrame(get_time(), false); // Update our UserLog object about the current mouse position CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { // We want current canvas and window coordinates so normalization // is done properly with respect to the canvas. GdkRectangle sWindowRect; GdkRectangle sCanvasRect; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_frame_extents(gtk_widget_get_window(m_pCanvas), &sWindowRect); #else gdk_window_get_frame_extents(m_pCanvas->window, &sWindowRect); #endif pUserLog->AddWindowSize(sWindowRect.y, sWindowRect.x, sWindowRect.y + sWindowRect.height, sWindowRect.x + sWindowRect.width); if (m_pScreen != NULL) { if (m_pScreen->GetCanvasSize(&sCanvasRect)) pUserLog->AddCanvasSize(sCanvasRect.y, sCanvasRect.x, sCanvasRect.y + sCanvasRect.height, sCanvasRect.x + sCanvasRect.width); } int iMouseX = 0; int iMouseY = 0; gdk_window_get_pointer(NULL, &iMouseX, &iMouseY, NULL); // TODO: This sort of thing shouldn't be in specialised methods, move into base class somewhere pUserLog->AddMouseLocationNormalized(iMouseX, iMouseY, true, GetNats()); } return 1; // See CVS for code which used to be here } int CDasherControl::LongTimerEvent() { // std::cout << "Framerate: " << GetFramerate() << std::endl; // std::cout << "Render count: " << GetRenderCount() << std::endl; return 1; } gboolean CDasherControl::ExposeEvent() { NewFrame(get_time(), true); return 0; } gboolean CDasherControl::ButtonPressEvent(GdkEventButton *event) { // Take the focus if we click on the canvas // GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); // gboolean *returnType; // focusEvent->type = GDK_FOCUS_CHANGE; // focusEvent->window = (GdkWindow *) m_pCanvas; // focusEvent->send_event = FALSE; // focusEvent->in = TRUE; // gtk_widget_grab_focus(GTK_WIDGET(m_pCanvas)); // g_signal_emit_by_name(GTK_OBJECT(m_pCanvas), "focus_in_event", GTK_WIDGET(m_pCanvas), focusEvent, NULL, &returnType); // No - don't take the focus - give it to the text area instead if(event->type == GDK_BUTTON_PRESS) HandleClickDown(get_time(), (int)event->x, (int)event->y); else if(event->type == GDK_BUTTON_RELEASE) HandleClickUp(get_time(), (int)event->x, (int)event->y); return false; } gint CDasherControl::KeyReleaseEvent(GdkEventKey *event) { // TODO: This is seriously flawed - the semantics of of X11 Keyboard // events mean the there's no guarantee that key up/down events will // be received in pairs. if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) { // if(event->state & GDK_CONTROL_MASK) // SetLongParameter(LP_BOOSTFACTOR, 25); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) { // if(event->state & GDK_SHIFT_MASK) // SetLongParameter(LP_BOOSTFACTOR, 175); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyUp(get_time(), iKeyVal); // } } return 0; } gint CDasherControl::KeyPressEvent(GdkEventKey *event) { // if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) // SetLongParameter(LP_BOOSTFACTOR, 175); // else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) // SetLongParameter(LP_BOOSTFACTOR, 25); // else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyDown(get_time(), iKeyVal); // } // } return 0; } void CDasherControl::CanvasDestroyEvent() { // Delete the screen if(m_pScreen != NULL) { delete m_pScreen; m_pScreen = NULL; } } // Tell the logging object that a new user trial is starting. void CDasherControl::UserLogNewTrial() { CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { pUserLog->NewTrial(); } } int CDasherControl::GetFileSize(const std::string &strFileName) { struct stat sStatInfo; if(!stat(strFileName.c_str(), &sStatInfo)) return sStatInfo.st_size; else return 0; } // "C" style callbacks - these are here just because it's not possible // (or at least not easy) to connect a callback directly to a C++ // method, so we pass a pointer to th object in the user_data field // and use a wrapper function. Please do not put any functional code // here. extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data) { static_cast < CDasherControl * >(user_data)->RealizeCanvas(widget); } extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) { return static_cast < CDasherControl * >(data)->ButtonPressEvent(event); } extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { return static_cast < CDasherControl * >(data)->KeyPressEvent(event); } extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { return static_cast < CDasherControl * >(data)->CanvasConfigureEvent(); } extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData) { static_cast<CDasherControl*>(pUserData)->CanvasDestroyEvent(); } extern "C" gint key_release_event(GtkWidget *pWidget, GdkEventKey *event, gpointer pUserData) { return static_cast<CDasherControl*>(pUserData)->KeyReleaseEvent(event); } extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return static_cast < CDasherControl * >(data)->FocusEvent(widget, event); } extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data) { return ((CDasherControl*)data)->ExposeEvent(); } diff --git a/Src/Gtk2/DasherControl.h b/Src/Gtk2/DasherControl.h index 0a82963..55f6d62 100644 --- a/Src/Gtk2/DasherControl.h +++ b/Src/Gtk2/DasherControl.h @@ -1,207 +1,209 @@ #ifndef __dashercontrol_h__ #define __dashercontrol_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "PangoCache.h" #include "Canvas.h" #include "../DasherCore/SocketInput.h" #ifdef JOYSTICK #include "joystick_input.h" #endif #ifdef TILT #include "tilt_input.h" #endif #include "mouse_input.h" #include "GtkDasherControl.h" +#include "dasher_editor.h" //#include "KeyboardHelper.h" //#include "../DasherCore/DasherSettingsInterface.h" #include "../DasherCore/DasherInterfaceBase.h" #include "../DasherCore/GnomeSettingsStore.h" #include "../DasherCore/UserLog.h" /// /// \brief C++ core of the Dasher GTK UI component. /// /// Class representing the Dasher UI component (ie the canvas and speed slider) /// \todo It would really be more sensible for CDasherControl to inheret from CDasherInterface rather than contain a pointer to it /// class CDasherControl : public CDasherInterfaceBase { public: /// /// \param pVBox GTK VBox to populate with the DasherControl /// component widgets. This needs to be created externally by the /// GObject wrapper and passed to the C++ class rather than being /// created internally. /// \param pDasherControl Pointer to the GObject wrapper. This is /// needed so that we can emit signals from the GObject. /// CDasherControl(GtkVBox * pVbox, GtkDasherControl * pDasherControl); ~CDasherControl(); // Event handlers // FIXME - we should probably pass all parameters to these from the "C" callbacks void SetFocus(); /// /// GTK Signal handler for the canvas getting the focus (which it gives away to the edit box) /// bool FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent); /// /// Called when the canvas gets realized (ie when internal resources have been allocated), so we can finalise setup. /// void RealizeCanvas(GtkWidget *pWidget); /// /// Called periodically by a timer. Used to prompt the interface to perform a redraw /// \todo There's rather a lot which happens in this /// function. Ideally it should just be a simple call to the core /// which then figures out whether we're paused or not etc. /// int TimerEvent(); int LongTimerEvent(); /// /// Mouse button pressed on the canvas /// gboolean ButtonPressEvent(GdkEventButton * event); /// /// Called when the canvas has been resized, prompts the (re)creation of the CCanvas object. /// int CanvasConfigureEvent(); /// /// Speed slider has been moved. /// void SliderEvent(); /// /// Called when the canvas GTK widget is destroyed, so we can free any references to it. /// void CanvasDestroyEvent(); /// /// Key press event on the canvas /// gint KeyReleaseEvent(GdkEventKey * event); gint KeyPressEvent(GdkEventKey * event); /// /// Return an array of allowed values for a string parameter. /// \param iParameter The parameter to query. /// \return A GArray of gchar* pointers to strings containing permitted values /// GArray *GetAllowedValues(int iParameter); /// /// Called by UI needs to signal a new user trial is starting. /// void UserLogNewTrial(); void ExternalKeyDown(int iKeyVal); void ExternalKeyUp(int iKeyVal); /** * Instantiate the Game Display object with a reference to the Gtk * table it will be populating. * - * @param pGameDisplay the reference + * @param pGameDisplay reference to gtk widget + * @param pEditor reference to dasher editor */ - void CreateGameDisplay(void* pGameDisplay); + void CreateGameDisplay(GtkWidget *pGameDisplay, void* pEditor); gboolean ExposeEvent(); private: // virtual void CreateSettingsStore(); virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList); virtual void ScanColourFiles(std::vector<std::string> &vFileList); virtual void SetupPaths(); virtual void CreateModules(); virtual void SetupUI(); virtual void CreateSettingsStore(); virtual int GetFileSize(const std::string &strFileName); virtual void WriteTrainFile(const std::string &strNewText); virtual void StartTimer(); virtual void ShutdownTimer(); /// /// Pass events coming from the core to the appropriate handler. /// void ExternalEventHandler(Dasher::CEvent *pEvent); void GameMessageOut(int message, const void* messagedata); /// /// Notification from CDasherInterface that a parameter has changed /// \param iParameter The parameter which has changed /// void HandleParameterNotification(int iParameter); /** * The GTK implementation of the game display widget. Need to keep a * reference so that we can initialize it, then pass it into Game */ GtkWidget *m_pVBox; GtkWidget *m_pCanvas; /// /// Abstracted input device object for mouse input. /// CDasherMouseInput *m_pMouseInput; CDasher1DMouseInput *m_p1DMouseInput; /// /// Cache of Pango layouts /// CPangoCache *m_pPangoCache; /// /// The CCanvas object /// CCanvas *m_pScreen; /// /// The GObject which is wrapping this class /// GtkDasherControl *m_pDasherControl; /// /// Keyboard helper class /// // CKeyboardHelper *m_pKeyboardHelper; }; #endif diff --git a/Src/Gtk2/GtkDasherControl.cpp b/Src/Gtk2/GtkDasherControl.cpp index 3086a37..5b18a73 100644 --- a/Src/Gtk2/GtkDasherControl.cpp +++ b/Src/Gtk2/GtkDasherControl.cpp @@ -1,348 +1,348 @@ // GtkDasherControl.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherControl.h" #include "GtkDasherControl.h" #include "custom_marshal.h" #include "game_mode_helper.h" #include <gtk/gtkmarshal.h> struct _GtkDasherControlPrivate { CDasherControl *pControl; void* pGameHelper; }; typedef struct _GtkDasherControlPrivate GtkDasherControlPrivate; // Signals that this control can emit enum { DASHER_CHANGED, DASHER_START, DASHER_STOP, DASHER_EDIT_INSERT, DASHER_EDIT_DELETE, DASHER_EDIT_CONVERT, DASHER_EDIT_PROTECT, DASHER_CONTROL, DASHER_CONTEXT_REQUEST, DASHER_REQUEST_SETTINGS, DASHER_LOCK_INFO, DASHER_MESSAGE, DASHER_COMMAND, SIGNAL_NUM }; #define GTK_DASHER_CONTROL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), GTK_DASHER_TYPE_CONTROL, GtkDasherControlPrivate)); /* TODO: is it still sensible to derive from VBox, given that its just a cnavas now*/ G_DEFINE_TYPE(GtkDasherControl, gtk_dasher_control, GTK_TYPE_VBOX); static void gtk_dasher_control_finalize(GObject * pObject); static guint gtk_dasher_control_signals[SIGNAL_NUM]; /* TODO: initialise this? */ static void gtk_dasher_control_class_init(GtkDasherControlClass *pClass) { g_type_class_add_private(pClass, sizeof(GtkDasherControlPrivate)); GObjectClass *pObjectClass = (GObjectClass *) pClass; pObjectClass->finalize = gtk_dasher_control_finalize; gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_changed", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_changed), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_START] = g_signal_new("dasher_start", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_start), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_STOP] = g_signal_new("dasher_stop", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_INSERT] = g_signal_new("dasher_edit_insert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_insert), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_DELETE] = g_signal_new("dasher_edit_delete", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_delete), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_CONVERT] = g_signal_new("dasher_edit_convert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_convert), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_PROTECT] = g_signal_new("dasher_edit_protect", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_protect), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("dasher_control", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_control), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_context_request", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_context_request), NULL, NULL, g_cclosure_user_marshal_VOID__INT_INT, G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_INT); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_press_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_press_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_release_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_release_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); gtk_dasher_control_signals[DASHER_REQUEST_SETTINGS] = g_signal_new("dasher_request_settings", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_request_settings), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_LOCK_INFO] = g_signal_new("dasher_lock_info", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_lock), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_MESSAGE] = g_signal_new("dasher_message", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_message), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_COMMAND] = g_signal_new("dasher_command", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_command), NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); pClass->dasher_changed = NULL; pClass->dasher_start = NULL; pClass->dasher_stop = NULL; pClass->dasher_edit_insert = NULL; pClass->dasher_edit_delete = NULL; pClass->dasher_edit_convert = NULL; pClass->dasher_edit_protect = NULL; pClass->dasher_control = NULL; pClass->dasher_context_request = NULL; pClass->dasher_request_settings = NULL; pClass->dasher_lock = NULL; pClass->dasher_message = NULL; pClass->dasher_command = NULL; // pClass->key_press_event = gtk_dasher_control_default_key_press_handler; // pClass->key_release_event = gtk_dasher_control_default_key_release_handler; } static void gtk_dasher_control_init(GtkDasherControl *pDasherControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); pPrivate->pControl = new CDasherControl(&(pDasherControl->box), pDasherControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-press-event", G_CALLBACK(gtk_dasher_control_default_key_press_handler), pPrivate->pControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-release-event", G_CALLBACK(gtk_dasher_control_default_key_release_handler), pPrivate->pControl); } static void gtk_dasher_control_finalize(GObject *pObject) { GtkDasherControl *pDasherControl = GTK_DASHER_CONTROL(pObject); GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); /* TODO: Check that this actually gets called correctly */ /* TODO: Should just call constructor - this should just be a lightweight wrapper class */ pPrivate->pControl->StartShutdown(); delete pPrivate->pControl; // g_free(pDasherControl->private_data); } GtkWidget * gtk_dasher_control_new() { return GTK_WIDGET(g_object_new(GTK_DASHER_TYPE_CONTROL, NULL)); } void gtk_dasher_control_set_parameter_bool(GtkDasherControl *pControl, int iParameter, bool bValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBoolParameter(iParameter, bValue); } void gtk_dasher_control_set_parameter_long(GtkDasherControl *pControl, int iParameter, long lValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetLongParameter(iParameter, lValue); } void gtk_dasher_control_set_parameter_string(GtkDasherControl *pControl, int iParameter, const char *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetStringParameter(iParameter, szValue); } bool gtk_dasher_control_get_parameter_bool(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetBoolParameter(iParameter); } long gtk_dasher_control_get_parameter_long(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetLongParameter(iParameter); } void gtk_dasher_control_reset_parameter(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ResetParameter(iParameter); } const char * gtk_dasher_control_get_parameter_string(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetStringParameter(iParameter).c_str(); } GArray * gtk_dasher_control_get_allowed_values(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetAllowedValues(iParameter); }; void gtk_dasher_control_train(GtkDasherControl *pControl, const gchar *szFilename) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ImportTrainingText(szFilename); }; void gtk_dasher_control_set_context(GtkDasherControl *pControl, const gchar *szContext) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetContext(szContext); } void gtk_dasher_control_set_buffer(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBuffer(iOffset); } void gtk_dasher_control_unset_buffer(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UnsetBuffer(); } void gtk_dasher_control_set_offset(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetOffset(iOffset); } void gtk_dasher_control_register_node(GtkDasherControl *pControl, int iID, const gchar *szLabel, int iColour) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->RegisterNode(iID, szLabel, iColour); } void gtk_dasher_control_connect_node(GtkDasherControl *pControl, int iChild, int iParent, int iAfter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ConnectNode(iChild, iParent, iAfter); } void gtk_dasher_control_disconnect_node(GtkDasherControl *pControl, int iChild, int iParent) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->DisconnectNode(iChild, iParent); } void gtk_dasher_control_external_key_down(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyDown(iKeyVal); } void gtk_dasher_control_external_key_up(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyUp(iKeyVal); } void gtk_dasher_user_log_new_trial(GtkDasherControl * pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UserLogNewTrial(); } void gtk_dasher_control_set_focus(GtkDasherControl * pControl){ GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetFocus(); } // gboolean // gtk_dasher_control_default_key_press_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data){ // static_cast<CDasherControl *>(data)->KeyPressEvent(pEvent); // return FALSE; // } // gboolean // gtk_dasher_control_default_key_release_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data) { // static_cast<CDasherControl *>(data)->KeyReleaseEvent(pEvent); // return FALSE; // } gboolean gtk_dasher_control_get_module_settings(GtkDasherControl * pControl, const gchar *szModule, SModuleSettings **pSettings, gint *iCount) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetModuleSettings(szModule, pSettings, iCount); } void -gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameDisplay) { +gtk_dasher_control_set_game_display(GtkDasherControl *pControl, GtkWidget *p_GameDisplay, void *p_Editor) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); - pPrivate->pControl->CreateGameDisplay(gameDisplay); + pPrivate->pControl->CreateGameDisplay(p_GameDisplay, p_Editor); } void gtk_dasher_control_add_game_mode_string(GtkDasherControl *pControl, const gchar *szString) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddGameModeString(szString); } void gtk_dasher_control_game_messagein(GtkDasherControl *pControl, int message, void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->GameMessageIn(message, messagedata); } void gtk_dasher_control_game_helperreg(GtkDasherControl *pControl, void* gameHelper) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pGameHelper = gameHelper; } void gtk_dasher_control_game_messageout(GtkDasherControl *pControl, int message, const void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); GameModeHelper* pHelper = GAME_MODE_HELPER(pPrivate->pGameHelper); if(pHelper) game_mode_helper_message(pHelper, message, messagedata); } void gtk_dasher_control_force_pause(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->Pause(); } double gtk_dasher_control_get_framerate(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetFramerate(); } void gtk_dasher_control_add_action_button(GtkDasherControl *pControl, const gchar *szCommand) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddActionButton(szCommand); } void gtk_dasher_control_set_control_offset(GtkDasherControl *pControl, gint iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetControlOffset(iOffset); } const char * gtk_dasher_control_cl_set(GtkDasherControl *pControl, const gchar *szKey, const gchar *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->ClSet(szKey, szValue); } diff --git a/Src/Gtk2/GtkDasherControl.h b/Src/Gtk2/GtkDasherControl.h index 07940b8..099d5a7 100644 --- a/Src/Gtk2/GtkDasherControl.h +++ b/Src/Gtk2/GtkDasherControl.h @@ -1,114 +1,114 @@ #ifndef __gtkdashercontrol_h__ #define __gtkdashercontrol_h__ #include <gtk/gtk.h> #include "../Common/ModuleSettings.h" #include "Parameters.h" #include "ControlManager.h" typedef struct _DasherLockInfo DasherLockInfo; struct _DasherLockInfo { const gchar *szMessage; gboolean bLock; gint iPercent; }; typedef struct _DasherMessageInfo DasherMessageInfo; struct _DasherMessageInfo { const gchar *szMessage; gint iID; gint iType; }; G_BEGIN_DECLS #define GTK_DASHER_TYPE_CONTROL (gtk_dasher_control_get_type()) #define GTK_DASHER_CONTROL(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_DASHER_TYPE_CONTROL, GtkDasherControl )) #define GTK_DASHER_CONTROL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_DASHER_TYPE_CONTROL, GtkDasherControlClass )) #define GTK_DASHER_IS_CONTROL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_DASHER_TYPE_CONTROL)) #define GTK_DASHER_IS_CONTROL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_DASHER_TYPE_CONTROL)) typedef struct _GtkDasherControl GtkDasherControl; typedef struct _GtkDasherControlClass GtkDasherControlClass; struct _GtkDasherControl { GtkVBox box; // gpointer private_data; }; struct _GtkDasherControlClass { GtkVBoxClass parent_class; // Signal handlers void (*dasher_changed) (GtkDasherControl * pDasherControl, gint iParameter, gpointer data); void (*dasher_start) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_stop) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_edit_insert) (GtkDasherControl * pDasherControl, const gchar * szText, int iOffset, gpointer data); void (*dasher_edit_delete) (GtkDasherControl * pDasherControl, const gchar * szText, int iOffset, gpointer data); void (*dasher_edit_convert) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_edit_protect) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_control) (GtkDasherControl * pDasherControl, gint iEvent, gpointer data); gboolean (*key_press_event) (GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); gboolean (*key_release_event) (GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); void (*dasher_context_request) (GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); void (*dasher_request_settings) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_lock) (GtkDasherControl * pDasherControl, gpointer pLockInfo, gpointer data); void (*dasher_message) (GtkDasherControl * pDasherControl, gpointer pLockInfo, gpointer data); void (*dasher_command) (GtkDasherControl * pDasherControl, const gchar * szText, gpointer data); }; GtkWidget *gtk_dasher_control_new(); GType gtk_dasher_control_get_type(); gboolean gtk_dasher_control_default_key_press_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); gboolean gtk_dasher_control_default_key_release_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); void gtk_dasher_control_set_parameter_bool(GtkDasherControl * pControl, int iParameter, bool bValue); void gtk_dasher_control_set_parameter_long(GtkDasherControl * pControl, int iParameter, long lValue); void gtk_dasher_control_set_parameter_string(GtkDasherControl * pControl, int iParameter, const char *szValue); bool gtk_dasher_control_get_parameter_bool(GtkDasherControl * pControl, int iParameter); long gtk_dasher_control_get_parameter_long(GtkDasherControl * pControl, int iParameter); void gtk_dasher_control_reset_parameter(GtkDasherControl * pControl, int iParameter); const char *gtk_dasher_control_get_parameter_string(GtkDasherControl * pControl, int iParameter); GArray *gtk_dasher_control_get_allowed_values(GtkDasherControl * pControl, int iParameter); void gtk_dasher_control_train(GtkDasherControl * pControl, const gchar * szFilename); void gtk_dasher_control_set_context(GtkDasherControl *pControl, const gchar *szContext); //void gtk_dasher_control_invalidate_context(GtkDasherControl *pControl, bool bForceStart); void gtk_dasher_control_set_buffer(GtkDasherControl *pControl, int iOffset); void gtk_dasher_control_set_offset(GtkDasherControl *pControl, int iOffset); void gtk_dasher_control_unset_buffer(GtkDasherControl *pControl); void gtk_dasher_control_register_node(GtkDasherControl *pControl, int iID, const gchar *szLabel, int iColour); void gtk_dasher_control_connect_node(GtkDasherControl *pControl, int iChild, int iParent, int iAfter); void gtk_dasher_control_disconnect_node(GtkDasherControl *pControl, int iChild, int iParent); void gtk_dasher_control_external_key_down(GtkDasherControl *pControl, int iKeyVal); void gtk_dasher_control_external_key_up(GtkDasherControl *pControl, int iKeyVal); gboolean gtk_dasher_control_get_module_settings(GtkDasherControl * pControl, const gchar *szModule, SModuleSettings **pSettings, gint *iCount); void gtk_dasher_control_add_game_mode_string(GtkDasherControl *pControl, const gchar *szString); void gtk_dasher_control_game_messagein(GtkDasherControl *pControl, int message, void* messagedata); /** * Pass a reference to the GTK widget containing the game mode display down to DasherControl * so that it can construct the game display UI. * @param pControl reference to GtkDasherControl instance - * @gameDisplay reference to the GTK table containing the game display + * @p_GameDisplay reference to the GTK table containing the game display + * @p_Editor reference to dasher editor */ -void gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameDisplay); - +void gtk_dasher_control_set_game_display(GtkDasherControl *pControl, GtkWidget *p_GameDisplay, void* p_Editor); void gtk_dasher_control_game_helperreg(GtkDasherControl *pControl, void* gameHelper); void gtk_dasher_control_game_messageout(GtkDasherControl *pControl, int message, const void* messagedata); void gtk_dasher_control_force_pause(GtkDasherControl *pControl); double gtk_dasher_control_get_framerate(GtkDasherControl *pControl); void gtk_dasher_control_add_action_button(GtkDasherControl *pControl, const gchar *szCommand); void gtk_dasher_control_set_control_offset(GtkDasherControl *pControl, gint iOffset); void gtk_dasher_user_log_new_trial(GtkDasherControl * pControl); void gtk_dasher_control_set_focus(GtkDasherControl * pControl); const gchar* gtk_dasher_control_cl_set(GtkDasherControl *pControl, const gchar *szKey, const gchar *szValue); G_END_DECLS #endif diff --git a/Src/Gtk2/GtkGameDisplay.cpp b/Src/Gtk2/GtkGameDisplay.cpp index 9a54011..8b6e5ee 100644 --- a/Src/Gtk2/GtkGameDisplay.cpp +++ b/Src/Gtk2/GtkGameDisplay.cpp @@ -1,35 +1,39 @@ #include "GtkGameDisplay.h" using namespace std; void GtkGameDisplay::DisplayChunkText(std::string text, std::vector<std::string>& colors) { std::string markup = "<span font-weight = \"bold\" font_size = \"xx-large\">"; for(int pos = 0; pos < text.length(); pos++) { markup += "<span foreground = \""+ colors[pos]+"\">"+text.substr(pos, 1)+"</span>"; } markup += "</span>"; gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), markup.c_str()); } void GtkGameDisplay::hide() { gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), ""); gtk_widget_set_visible(GTK_WIDGET(m_pContainer), false); } void GtkGameDisplay::alert(std::string message) { GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_OK, message.c_str() ); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(GTK_WIDGET(dialog)); } + +void GtkGameDisplay::ClearEditor() { + dasher_editor_clear_text(m_pEditor); +} diff --git a/Src/Gtk2/GtkGameDisplay.h b/Src/Gtk2/GtkGameDisplay.h index f2bb6ef..4dd29d3 100644 --- a/Src/Gtk2/GtkGameDisplay.h +++ b/Src/Gtk2/GtkGameDisplay.h @@ -1,39 +1,44 @@ #include "../DasherCore/GameDisplay.h" +#include "dasher_editor.h" #include <gtk/gtk.h> #include <string> #include <cstring> class GtkGameDisplay : public Dasher::CGameDisplay { public: /** * @param pContainer - the table that all of the * widgets for the game display live in + * @param pEditor - reference to the dasher editor */ - GtkGameDisplay(GtkWidget *pContainer) : + GtkGameDisplay(GtkWidget *pContainer, DasherEditor *pEditor) : Dasher::CGameDisplay(), - m_pContainer(pContainer) + m_pContainer(pContainer), + m_pEditor(pEditor) { m_pChunkDisplay = gtk_label_new(NULL); gtk_container_add(GTK_CONTAINER(m_pContainer), m_pChunkDisplay); gtk_widget_set_visible(m_pChunkDisplay, true); - } virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors); virtual void hide(); virtual void alert(std::string message); + virtual void ClearEditor(); + private: /** * The Gtk table containing the game mode UI. */ GtkWidget *m_pContainer; GtkWidget *m_pChunkDisplay; + DasherEditor *m_pEditor; }; diff --git a/Src/Gtk2/dasher_editor.cpp b/Src/Gtk2/dasher_editor.cpp index 2b250f3..6bf9b3b 100644 --- a/Src/Gtk2/dasher_editor.cpp +++ b/Src/Gtk2/dasher_editor.cpp @@ -1,364 +1,374 @@ // dasher_editor.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <glib/gi18n.h> #include <gtk/gtk.h> #include "dasher_action_keyboard.h" #ifdef WITH_MAEMO #include "dasher_action_keyboard_maemo.h" #else #include "dasher_action_script.h" #endif #ifdef GNOME_SPEECH #include "dasher_action_speech.h" #endif #include "dasher_editor.h" #include "dasher_external_buffer.h" #include "dasher_internal_buffer.h" #include "dasher_lock_dialogue.h" #include "dasher_main.h" //#include "game_mode_helper.h" #define ACTION_STATE_SHOW 1 #define ACTION_STATE_CONTROL 2 #define ACTION_STATE_AUTO 4 typedef struct _EditorAction EditorAction; struct _EditorAction { DasherAction *pAction; EditorAction *pNext; EditorAction *pPrevious; gint iControlID; gint iID; // TODO: does this need to be separate from iControlID? gboolean bShow; gboolean bControl; gboolean bAuto; gint iNSub; }; typedef struct _DasherEditorPrivate DasherEditorPrivate; struct _DasherEditorPrivate { DasherMain *pDasherMain; GtkTextView *pTextView; GtkTextBuffer *pBuffer; GtkVBox *pActionPane; GtkClipboard *pTextClipboard; GtkClipboard *pPrimarySelection; EditorAction *pActionRing; EditorAction *pActionIter; gboolean bActionIterStarted; gint iNextActionID; IDasherBufferSet *pBufferSet; IDasherBufferSet *pExternalBuffer; IDasherBufferSet *pInternalBuffer; // GameModeHelper *pGameModeHelper; GtkTextMark *pNewMark; DasherAppSettings *pAppSettings; gchar *szFilename; gboolean bFileModified; // TODO: Make this work properly, export to main for quit etc }; #define DASHER_EDITOR_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), DASHER_TYPE_EDITOR, DasherEditorPrivate)) /* Signals */ enum { FILENAME_CHANGED, BUFFER_CHANGED, CONTEXT_CHANGED, SIGNAL_NUM }; static guint dasher_editor_signals[SIGNAL_NUM]; /* TODO: Use appropriate macros here */ /* G-object boilerplate code */ // static void dasher_editor_class_init(DasherEditorClass *pClass); // static void dasher_editor_init(DasherEditor *pEditor); G_DEFINE_TYPE(DasherEditor, dasher_editor, GTK_TYPE_VBOX); static void dasher_editor_finalize(GObject *pObject); static void dasher_editor_class_init(DasherEditorClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherEditorPrivate)); GObjectClass *pObjectClass = G_OBJECT_CLASS(pClass); pObjectClass->finalize = dasher_editor_finalize; /* Setup signals */ dasher_editor_signals[FILENAME_CHANGED] = g_signal_new("filename-changed", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherEditorClass, filename_changed), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); dasher_editor_signals[BUFFER_CHANGED] = g_signal_new("buffer-changed", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherEditorClass, buffer_changed), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); dasher_editor_signals[CONTEXT_CHANGED] = g_signal_new("context-changed", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherEditorClass, context_changed), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); pClass->initialise = NULL; pClass->command = NULL; pClass->action_button = NULL; pClass->actions_start = NULL; pClass->actions_more = NULL; pClass->actions_get_next = NULL; pClass->action_set_show = NULL; pClass->action_set_control = NULL; pClass->action_set_auto = NULL; pClass->get_all_text = NULL; pClass->get_new_text = NULL; pClass->output = NULL; pClass->delete_text = NULL; pClass->start_compose = NULL; pClass->end_compose = NULL; pClass->get_context = NULL; pClass->get_offset = NULL; pClass->handle_parameter_change = NULL; pClass->handle_stop = NULL; pClass->handle_start = NULL; pClass->handle_control = NULL; pClass->grab_focus = NULL; pClass->file_changed = NULL; pClass->get_filename = NULL; pClass->filename_changed = NULL; pClass->buffer_changed = NULL; pClass->context_changed = NULL; } static void dasher_editor_init(DasherEditor *pDasherControl) { DasherEditorPrivate *pPrivate = DASHER_EDITOR_GET_PRIVATE(pDasherControl); pPrivate->pBufferSet = NULL; pPrivate->pInternalBuffer = NULL; pPrivate->pExternalBuffer = NULL; pPrivate->szFilename = NULL; pPrivate->pTextClipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); pPrivate->pPrimarySelection = gtk_clipboard_get(GDK_SELECTION_PRIMARY); pPrivate->pActionRing = NULL; pPrivate->iNextActionID = 0; // pPrivate->pGameModeHelper = NULL; pPrivate->bFileModified = FALSE; } static void dasher_editor_finalize(GObject *pObject) { g_debug("Finalising DasherEditor"); DasherEditorPrivate *pPrivate = DASHER_EDITOR_GET_PRIVATE(pObject); EditorAction *pCurrentAction = pPrivate->pActionRing; if(pCurrentAction) { bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; dasher_action_deactivate(pCurrentAction->pAction); g_object_unref(G_OBJECT(pCurrentAction->pAction)); pCurrentAction = pCurrentAction->pNext; } } if(pPrivate->pBufferSet) g_object_unref(G_OBJECT(pPrivate->pBufferSet)); if(pPrivate->szFilename) g_free(pPrivate->szFilename); } void dasher_editor_initialise(DasherEditor *pSelf, DasherAppSettings *pAppSettings, DasherMain *pDasherMain, GtkBuilder *pXML, const gchar *szFullPath) { if(DASHER_EDITOR_GET_CLASS(pSelf)->initialise) DASHER_EDITOR_GET_CLASS(pSelf)->initialise(pSelf, pAppSettings, pDasherMain, pXML, szFullPath); } void dasher_editor_handle_stop(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->handle_stop) DASHER_EDITOR_GET_CLASS(pSelf)->handle_stop(pSelf); } void dasher_editor_handle_start(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->handle_start) DASHER_EDITOR_GET_CLASS(pSelf)->handle_start(pSelf); } /* TODO: This is obsolete - sort this out when commands are reconsidered */ void dasher_editor_handle_control(DasherEditor *pSelf, int iNodeID) { if(DASHER_EDITOR_GET_CLASS(pSelf)->handle_control) DASHER_EDITOR_GET_CLASS(pSelf)->handle_control(pSelf, iNodeID); } void dasher_editor_action_button(DasherEditor *pSelf, DasherAction *pAction) { if(DASHER_EDITOR_GET_CLASS(pSelf)->action_button) DASHER_EDITOR_GET_CLASS(pSelf)->action_button(pSelf, pAction); } void dasher_editor_actions_start(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->actions_start) DASHER_EDITOR_GET_CLASS(pSelf)->actions_start(pSelf); } bool dasher_editor_actions_more(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->actions_more) return DASHER_EDITOR_GET_CLASS(pSelf)->actions_more(pSelf); else return false; } void dasher_editor_actions_get_next(DasherEditor *pSelf, const gchar **szName, gint *iID, gboolean *bShow, gboolean *bControl, gboolean *bAuto) { if(DASHER_EDITOR_GET_CLASS(pSelf)->actions_get_next) DASHER_EDITOR_GET_CLASS(pSelf)->actions_get_next(pSelf, szName, iID, bShow, bControl, bAuto); } void dasher_editor_action_set_show(DasherEditor *pSelf, int iActionID, bool bValue) { if(DASHER_EDITOR_GET_CLASS(pSelf)->action_set_show) DASHER_EDITOR_GET_CLASS(pSelf)->action_set_show(pSelf, iActionID, bValue); } void dasher_editor_action_set_control(DasherEditor *pSelf, int iActionID, bool bValue) { if(DASHER_EDITOR_GET_CLASS(pSelf)->action_set_control) DASHER_EDITOR_GET_CLASS(pSelf)->action_set_control(pSelf, iActionID, bValue); } void dasher_editor_action_set_auto(DasherEditor *pSelf, int iActionID, bool bValue) { if(DASHER_EDITOR_GET_CLASS(pSelf)->action_set_auto) DASHER_EDITOR_GET_CLASS(pSelf)->action_set_auto(pSelf, iActionID, bValue); } void dasher_editor_grab_focus(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->grab_focus) DASHER_EDITOR_GET_CLASS(pSelf)->grab_focus(pSelf); } void dasher_editor_output(DasherEditor *pSelf, const gchar *szText, int iOffset) { if(DASHER_EDITOR_GET_CLASS(pSelf)->output) DASHER_EDITOR_GET_CLASS(pSelf)->output(pSelf, szText, iOffset); } void dasher_editor_delete(DasherEditor *pSelf, int iLength, int iOffset) { if(DASHER_EDITOR_GET_CLASS(pSelf)->delete_text) DASHER_EDITOR_GET_CLASS(pSelf)->delete_text(pSelf, iLength, iOffset); } void dasher_editor_start_compose(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->start_compose) DASHER_EDITOR_GET_CLASS(pSelf)->start_compose(pSelf); } void dasher_editor_end_compose(DasherEditor *pSelf, bool bKeep) { if(DASHER_EDITOR_GET_CLASS(pSelf)->end_compose) DASHER_EDITOR_GET_CLASS(pSelf)->end_compose(pSelf, bKeep); } +/** + * Clear all text out of the dasher editor. + * @param pSelf a reference to an instance of DasherEditor + */ +void dasher_editor_clear_text(DasherEditor *pSelf) { + + int editorTextLen = strlen(dasher_editor_get_all_text(pSelf)); + dasher_editor_delete(pSelf, editorTextLen, 0); +} + const gchar * dasher_editor_get_context(DasherEditor *pSelf, int iOffset, int iLength) { if(DASHER_EDITOR_GET_CLASS(pSelf)->get_context) return DASHER_EDITOR_GET_CLASS(pSelf)->get_context(pSelf, iOffset, iLength); else return NULL; } gint dasher_editor_get_offset(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->get_offset) return DASHER_EDITOR_GET_CLASS(pSelf)->get_offset(pSelf); else return 0; } gboolean dasher_editor_command(DasherEditor *pSelf, const gchar *szCommand) { if(DASHER_EDITOR_GET_CLASS(pSelf)->command) return DASHER_EDITOR_GET_CLASS(pSelf)->command(pSelf, szCommand); else return false; } gboolean dasher_editor_file_changed(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->file_changed) return DASHER_EDITOR_GET_CLASS(pSelf)->file_changed(pSelf); else return false; } const gchar * dasher_editor_get_filename(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->get_filename) return DASHER_EDITOR_GET_CLASS(pSelf)->get_filename(pSelf); else return NULL; } const gchar * dasher_editor_get_all_text(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->get_all_text) return DASHER_EDITOR_GET_CLASS(pSelf)->get_all_text(pSelf); else return NULL; } const gchar * dasher_editor_get_new_text(DasherEditor *pSelf) { if(DASHER_EDITOR_GET_CLASS(pSelf)->get_new_text) return DASHER_EDITOR_GET_CLASS(pSelf)->get_new_text(pSelf); else return NULL; } void dasher_editor_handle_parameter_change(DasherEditor *pSelf, gint iParameter) { if(DASHER_EDITOR_GET_CLASS(pSelf)->handle_parameter_change) DASHER_EDITOR_GET_CLASS(pSelf)->handle_parameter_change(pSelf, iParameter); } diff --git a/Src/Gtk2/dasher_editor.h b/Src/Gtk2/dasher_editor.h index a86eefa..4f1340a 100644 --- a/Src/Gtk2/dasher_editor.h +++ b/Src/Gtk2/dasher_editor.h @@ -1,115 +1,116 @@ #ifndef __dasher_editor_h__ #define __dasher_editor_h__ #include <glib.h> #include <glib-object.h> #include <gtk/gtk.h> #include "DasherAppSettings.h" #include "dasher_action.h" #include "dasher_buffer_set.h" /* Forward declaration */ typedef struct _DasherMain DasherMain; struct _DasherMain; G_BEGIN_DECLS #define DASHER_TYPE_EDITOR (dasher_editor_get_type()) #define DASHER_EDITOR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), DASHER_TYPE_EDITOR, DasherEditor )) #define DASHER_EDITOR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), DASHER_TYPE_EDITOR, DasherEditorClass )) #define DASHER_IS_EDITOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), DASHER_TYPE_EDITOR)) #define DASHER_IS_EDITOR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), DASHER_TYPE_EDITOR)) #define DASHER_EDITOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), DASHER_TYPE_EDITOR, DasherEditorClass)) typedef struct _DasherEditor DasherEditor; typedef struct _DasherEditorClass DasherEditorClass; struct _DasherEditor { GtkVBox box; }; struct _DasherEditorClass { GtkVBoxClass parent_class; /* VTable */ void (*initialise)(DasherEditor *, DasherAppSettings *, DasherMain *, GtkBuilder *, const gchar *); gboolean (*command)(DasherEditor *, const gchar *); void (*action_button)(DasherEditor *, DasherAction *); void (*actions_start)(DasherEditor *); bool (*actions_more)(DasherEditor *); void (*actions_get_next)(DasherEditor *, const gchar **, gint *, gboolean *, gboolean *, gboolean *); void (*action_set_show)(DasherEditor *, int, bool); void (*action_set_control)(DasherEditor *, int, bool); void (*action_set_auto)(DasherEditor *, int, bool); const gchar *(*get_all_text)(DasherEditor *); const gchar *(*get_new_text)(DasherEditor *); void (*output)(DasherEditor *, const gchar *, int); void (*delete_text)(DasherEditor *, int, int); void (*start_compose)(DasherEditor *); void (*end_compose)(DasherEditor *, bool); const gchar *(*get_context)(DasherEditor *, int, int); gint (*get_offset)(DasherEditor *); void (*handle_parameter_change)(DasherEditor *, gint); void (*handle_start)(DasherEditor *); void (*handle_stop)(DasherEditor *); void (*handle_control)(DasherEditor *, int); void (*grab_focus)(DasherEditor *); gboolean (*file_changed)(DasherEditor *); const gchar *(*get_filename)(DasherEditor *); /* Signal handlers */ void (*filename_changed)(DasherEditor *); void (*buffer_changed)(DasherEditor *); void (*context_changed)(DasherEditor *); }; /* Boilerplate code */ GType dasher_editor_get_type(); /* Functions for initialisation and takedown */ void dasher_editor_initialise(DasherEditor *pSelf, DasherAppSettings *pAppSettings, DasherMain *pDasherMain, GtkBuilder *pXML, const gchar *szFullPath); /* Abstract command handler */ gboolean dasher_editor_command(DasherEditor *pSelf, const gchar *szCommand); /* Action related methods */ void dasher_editor_action_button(DasherEditor *pSelf, DasherAction *pAction); void dasher_editor_actions_start(DasherEditor *pSelf); bool dasher_editor_actions_more(DasherEditor *pSelf); void dasher_editor_actions_get_next(DasherEditor *pSelf, const gchar **szName, gint *iID, gboolean *bShow, gboolean *bControl, gboolean *bAuto); void dasher_editor_action_set_show(DasherEditor *pSelf, int iActionID, bool bValue); void dasher_editor_action_set_control(DasherEditor *pSelf, int iActionID, bool bValue); void dasher_editor_action_set_auto(DasherEditor *pSelf, int iActionID, bool bValue); const gchar *dasher_editor_get_all_text(DasherEditor *pSelf); const gchar *dasher_editor_get_new_text(DasherEditor *pSelf); /* Functions for editing the active buffer */ void dasher_editor_output(DasherEditor *pSelf, const gchar *szText, int iOffset); void dasher_editor_delete(DasherEditor *pSelf, int iLength, int iOffset); void dasher_editor_start_compose(DasherEditor *pSelf); void dasher_editor_end_compose(DasherEditor *pSelf, bool bKeep); /* Function for reading the active buffer */ const gchar *dasher_editor_get_context(DasherEditor *pSelf, int iOffset, int iLength); gint dasher_editor_get_offset(DasherEditor *pSelf); /* Events proagated from main */ void dasher_editor_handle_parameter_change(DasherEditor *pSelf, gint iParameter); void dasher_editor_handle_stop(DasherEditor *pSelf); void dasher_editor_handle_start(DasherEditor *pSelf); void dasher_editor_handle_control(DasherEditor *pSelf, int iNodeID); /* Functions needed to maintain application UI */ void dasher_editor_grab_focus(DasherEditor *pSelf); gboolean dasher_editor_file_changed(DasherEditor *pSelf); const gchar *dasher_editor_get_filename(DasherEditor *pSelf); +void dasher_editor_clear_text(DasherEditor *pSelf); G_END_DECLS #endif diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 0ccb88e..5a06a20 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -1,1638 +1,1629 @@ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <utility> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #ifdef WITH_MAEMOFULLSCREEN #include <hildon-widgets/hildon-program.h> #endif #include <unistd.h> #include "GtkDasherControl.h" #include "dasher_lock_dialogue.h" #ifdef WITH_MAEMO #include "dasher_maemo_helper.h" #endif #include "dasher_main.h" #include "dasher_editor.h" #include "dasher_editor_internal.h" #include "dasher_editor_external.h" /* Static instance of singleton, USE SPARINGLY */ static DasherMain *g_pDasherMain = NULL; // TODO: The following global variable makes control mode editing work // - this needs to be sorted out properly. static gboolean g_bSend = true; enum { REALIZED, SIGNAL_NUM }; static guint dasher_main_signals[SIGNAL_NUM] = { 0 }; G_DEFINE_TYPE(DasherMain, dasher_main, G_TYPE_OBJECT); static void dasher_main_finalize(GObject *pObject); /* Private member functions */ static void dasher_main_setup_window_state(DasherMain *pSelf); static void dasher_main_setup_window_style(DasherMain *pSelf); static void dasher_main_setup_internal_layout(DasherMain *pSelf); static void dasher_main_set_window_title(DasherMain *pSelf); /* ... Table based menu/toolbar commands */ static void dasher_main_command_import(DasherMain *pSelf); static void dasher_main_command_quit(DasherMain *pSelf); static void dasher_main_command_preferences(DasherMain *pSelf); static void dasher_main_command_preferences_alphabet(DasherMain *pSelf); static void dasher_main_command_tutorial(DasherMain *pSelf); static void dasher_main_command_help(DasherMain *pSelf); static void dasher_main_command_about(DasherMain *pSelf); /* c.f. WRAP_CPP_CB below */ extern "C" void dasher_main_cb_import(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_quit(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_preferences(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_help(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_about(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_editor(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_toggle_game_mode(GtkAction*, DasherMain*); static gboolean dasher_main_speed_changed(DasherMain *pSelf); static void dasher_main_alphabet_combo_changed(DasherMain *pSelf); // TODO: populate speed slider static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); /* TODO: order these in file */ static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } g_message("loading interface"); dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); pPrivate->pGameDisplay = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "GameDisplay")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); - - gtk_dasher_control_set_game_display(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), pPrivate->pGameDisplay); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; + + + gtk_dasher_control_set_game_display(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), pPrivate->pGameDisplay, pPrivate->pEditor); + } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // -/** - * Clear all text out of the dasher editor. - * @param pSelf a reference to an instance of DasherMain - */ -void clear_dasher_editor_text(DasherMain *pSelf) { - - DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); - int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); - dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); -} - /** * Start game mode, specify the text to play with, and clear out any text in the dasher editor. * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. * * @param pGameTextFilePath - the absolute path to the text file to play with * @param pSelf - a reference to an instance of DasherMain */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkDasherControl *pControl = GTK_DASHER_CONTROL(pPrivate->pDasherWidget); gtk_widget_set_visible(GTK_WIDGET(pPrivate->pGameDisplay), true); dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); - clear_dasher_editor_text(pSelf); + dasher_editor_clear_text(pPrivate->pEditor); } void init_game_from_default_button(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { init_game_mode(_(""), (DasherMain*)pData); //TODO: this is really ugly - clearly symptomatic of doing something wrong with GTK //but I can't figure out what. For now, it makes the UI behave properly. gtk_widget_destroy(gtk_widget_get_parent( gtk_widget_get_parent( (gtk_widget_get_parent(GTK_WIDGET(pButton)))))); } /** * Event handler which displays a standard GTK file dialog. The dialog allows the user * to specify a text file to play game mode with. * * @param pButton the button that fired the event * @param pWidget reference needed by GTK for callback signature * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references * to the dialog's parent window and an instance of DasherMain */ void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } void quit_game_mode(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE((DasherMain*)pData); } /** * Toggle game mode on and off. Toggling on causes a dialog box to be displayed * welcoming the user to game mode and prompting them to specify a file to play with. * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core * to respond appropriately. * * @param pSelf a reference to an instance of DasherMain */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), GTK_RESPONSE_NONE); gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK(init_game_from_default_button), pSelf); g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Are you sure you wish to turn off game mode? All unsaved changes will be lost.")); GtkWidget *pNoButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_NO, GTK_RESPONSE_REJECT); GtkWidget *pYesButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_YES, GTK_RESPONSE_ACCEPT); //g_signal_connect(pYesButton, "button-press-event", G_CALLBACK(quit_game_mode), (gpointer)pSelf); - switch(gtk_dialog_run(GTK_DIALOG(pDialog))) { - case GTK_RESPONSE_REJECT: - gtk_widget_destroy(GTK_WIDGET(pDialog)); - break; - case GTK_RESPONSE_ACCEPT: + switch(gtk_dialog_run(GTK_DIALOG(pDialog))) { + case GTK_RESPONSE_REJECT: + gtk_widget_destroy(GTK_WIDGET(pDialog)); + break; + case GTK_RESPONSE_ACCEPT: dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); - clear_dasher_editor_text(pSelf); - } + dasher_editor_clear_text(pPrivate->pEditor); + } - if(GTK_IS_WIDGET(pDialog)) { - gtk_widget_destroy(GTK_WIDGET(pDialog)); - } + if(GTK_IS_WIDGET(pDialog)) { + gtk_widget_destroy(GTK_WIDGET(pDialog)); + } } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), - _("Don't save"), GTK_RESPONSE_REJECT, + _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; } } else { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Are you sure you wish to quit?")); gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't quit"), GTK_RESPONSE_REJECT, _("Quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: gtk_main_quit(); } } } static void dasher_main_command_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 0); } static void dasher_main_command_preferences_alphabet(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 1); } static void dasher_main_command_tutorial(DasherMain *pSelf) { // TODO: Implement this } static void dasher_main_command_help(DasherMain *pSelf) { #ifdef HAVE_GTK_SHOW_URI DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GdkScreen *scr; GError *err = NULL; scr = gtk_widget_get_screen(GTK_WIDGET(pPrivate->pMainWindow)); if (!gtk_show_uri(scr, "ghelp:dasher", gtk_get_current_event_time(), &err)) { GtkWidget *d; d = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", _("Unable to open help file")); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d), "%s", err->message); g_signal_connect(d, "response", G_CALLBACK(gtk_widget_destroy), NULL); gtk_window_present(GTK_WINDOW(d)); g_error_free (err); } #endif } static void dasher_main_command_about(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // In alphabetical order - please keep this in sync with the AUTHORS // file at root of the package tree const gchar *authors[] = { "Chris Ball", "Ignas Budvytis", "Peter Conlon", "Phil Cowans", "Frederik Eaton", "Behdad Esfahbod", "Matthew Garrett", "Chris Hack", "Takashi Kaburagi", "Sega Kazue", "Alan Lawrence", "David MacKay", "Iain Murray", "Martijn van Veen", "Keith Vertanen", "Hanna Wallach", "David Ward", "Patrick Welche", "Brian Williams", "Seb Wills", "Will Zou", NULL }; // Yeah, should really do some Gnome documentation for it... const gchar *documenters[] = { "Chris Ball", "Matthew Garrett", "David MacKay", NULL }; gtk_show_about_dialog(GTK_WINDOW(pPrivate->pMainWindow), "authors", authors, "comments", _("Dasher is a predictive text entry application"), "copyright", "Copyright \xC2\xA9 1998-2010 The Dasher Project", "documenters", documenters, "license", "GPL 2+", "logo-icon-name", "dasher", "translator-credits", _("translator-credits"), "version", PACKAGE_VERSION, "website", PACKAGE_URL, "wrap-license", true, NULL); } static gboolean dasher_main_speed_changed(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iNewValue( static_cast<int>(round(gtk_spin_button_get_value(pPrivate->pSpeedBox) * 100))); if(dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) != iNewValue) dasher_app_settings_set_long(pPrivate->pAppSettings, LP_MAX_BITRATE, iNewValue); return true; } static void dasher_main_alphabet_combo_changed(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkTreeIter sIter; if(gtk_combo_box_get_active_iter(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), &sIter)) { char *szSelected; gtk_tree_model_get(GTK_TREE_MODEL(pPrivate->pAlphabetList), &sIter, 0, &szSelected, -1); if(!strcmp("More Alphabets...", szSelected)) { gtk_combo_box_set_active(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), 0); // dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue); dasher_main_command(pSelf, "preferences_alphabet"); } else dasher_app_settings_set_string(pPrivate->pAppSettings, SP_ALPHABET_ID, szSelected); g_free(szSelected); } } static void dasher_main_populate_alphabet_combo(DasherMain *pSelf) { #ifndef WITH_MAEMO DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Disconnect the event handler temporarily, otherwise this will // trigger alphabet changes g_signal_handler_block(pPrivate->pAlphabetCombo, pPrivate->iAlphabetComboHandler); gtk_list_store_clear(pPrivate->pAlphabetList); GtkTreeIter sIter; const char *szValue; szValue = dasher_app_settings_get_string(pPrivate->pAppSettings, SP_ALPHABET_ID); if(strlen(szValue) > 0) { gtk_list_store_append(pPrivate->pAlphabetList, &sIter); gtk_list_store_set(pPrivate->pAlphabetList, &sIter, 0, szValue, -1); gtk_combo_box_set_active_iter(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), &sIter); } szValue = dasher_app_settings_get_string(pPrivate->pAppSettings, SP_ALPHABET_1); if(strlen(szValue) > 0) { gtk_list_store_append(pPrivate->pAlphabetList, &sIter); gtk_list_store_set(pPrivate->pAlphabetList, &sIter, 0, szValue, -1); } szValue = dasher_app_settings_get_string(pPrivate->pAppSettings, SP_ALPHABET_2); if(strlen(szValue) > 0) { gtk_list_store_append(pPrivate->pAlphabetList, &sIter); gtk_list_store_set(pPrivate->pAlphabetList, &sIter, 0, szValue, -1); } szValue = dasher_app_settings_get_string(pPrivate->pAppSettings, SP_ALPHABET_3); if(strlen(szValue) > 0) { gtk_list_store_append(pPrivate->pAlphabetList, &sIter); gtk_list_store_set(pPrivate->pAlphabetList, &sIter, 0, szValue, -1); } szValue = dasher_app_settings_get_string(pPrivate->pAppSettings, SP_ALPHABET_4); if(strlen(szValue) > 0) { gtk_list_store_append(pPrivate->pAlphabetList, &sIter); gtk_list_store_set(pPrivate->pAlphabetList, &sIter, 0, szValue, -1); } gtk_list_store_append(pPrivate->pAlphabetList, &sIter); gtk_list_store_set(pPrivate->pAlphabetList, &sIter, 0, "More Alphabets...", -1); g_signal_handler_unblock(pPrivate->pAlphabetCombo, pPrivate->iAlphabetComboHandler); #endif } static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pKeyboardHelper) return pPrivate->pKeyboardHelper->ConvertKeycode(iKeyVal); else return -1; } gboolean grab_focus() { // TODO: reimplement (text view member of class) // gtk_widget_grab_focus(the_text_view); // g_bForwardKeyboard = true; return true; } /* Callbacks */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data) { if(g_pDasherMain) dasher_main_speed_changed(g_pDasherMain); } extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData) { if(g_pDasherMain) dasher_main_alphabet_combo_changed(g_pDasherMain); } extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData) { if(g_pDasherMain) dasher_main_set_window_title(g_pDasherMain); } extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData) { if(!g_pDasherMain) return; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); gtk_dasher_control_set_buffer(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), dasher_editor_get_offset(pPrivate->pEditor)); } extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData) { if(!g_pDasherMain) return; if(!g_bSend) return; DasherMain *pDasherMain = DASHER_MAIN(g_pDasherMain); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); gtk_dasher_control_set_offset(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), dasher_editor_get_offset(pPrivate->pEditor)); } extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData) { dasher_main_command(g_pDasherMain, "quit"); /* Returning true stops further propagation */ return TRUE; } extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data) { if(g_pDasherMain) dasher_main_handle_parameter_change(g_pDasherMain, iParameter); } // TODO: Not really sure what happens here - need to sort out focus behaviour in general extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return grab_focus(); } extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return true; } extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data) { // g_bForwardKeyboard = false; return false; } extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data) { // TODO: Reimplement // if(g_bForwardKeyboard) { // gboolean *returnType; // g_signal_emit_by_name(GTK_OBJECT(pPrivate->pDasherWidget), "key_press_event", event, &returnType); // return true; // } // else { // return false; // } // TODO: Check callback return functions return false; } extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data) { // TODO: reimplement // if(g_bForwardKeyboard) { // gboolean *returnType; // g_signal_emit_by_name(GTK_OBJECT(pPrivate->pDasherWidget), "key_release_event", event, &returnType); // return true; // } // else { // return false; // } // TODO: Check callback return functions return false; } extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData) { return FALSE; } extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data) { if(!g_pDasherMain) return; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); if(!pPrivate->pEditor || !pPrivate->pDasherWidget) return; gtk_dasher_control_set_context(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), dasher_editor_get_context(pPrivate->pEditor, iOffset, iLength)); } extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data) { if(!g_pDasherMain) return; /* TODO: replace this with something a little more sensible */ switch(iEvent) { case Dasher::CControlManager::CTL_USER + 1: dasher_main_command(g_pDasherMain, "speakall"); return; case Dasher::CControlManager::CTL_USER + 2: dasher_main_command(g_pDasherMain, "speaklast"); return; case Dasher::CControlManager::CTL_USER + 3: dasher_main_command(g_pDasherMain, "speakrepeat"); return; default: break; } // TODO: This is a horrible hack here to make the release work! g_bSend = false; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); dasher_editor_handle_control(pPrivate->pEditor, iEvent); gtk_dasher_control_set_control_offset(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), dasher_editor_get_offset(pPrivate->pEditor)); g_bSend = true; // --- } extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data) { if(!g_pDasherMain) return; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); dasher_editor_grab_focus(pPrivate->pEditor); } // TODO: Make this only work for children of the main window extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData) { DasherMain *pSelf = DASHER_MAIN(pUserData); gint iButton = dasher_main_lookup_key(pSelf, pEvent->keyval); if(iButton != -1) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if (pWidget == GTK_WIDGET(pPrivate->pMainWindow) || gtk_widget_is_ancestor(pWidget, GTK_WIDGET(pPrivate->pMainWindow))) { if(pPrivate->pDasherWidget) { if(pEvent->type == GDK_KEY_PRESS) gtk_dasher_control_external_key_down(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), iButton); else gtk_dasher_control_external_key_up(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), iButton); } return TRUE; } else { return FALSE; } } else { return FALSE; } } // Callbacks from the Dasher widget extern "C" void handle_stop_event(GtkDasherControl *pDasherControl, gpointer data) { if(g_pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); if(pPrivate->pEditor) dasher_editor_handle_stop(pPrivate->pEditor); } } extern "C" void on_message(GtkDasherControl *pDasherControl, gpointer pMessageInfo, gpointer pUserData) { // TODO: I don't believe that this is widely used, but possibly need to reimplement // if(g_pDasherMain) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); // if(pPrivate->pEditor) // dasher_editor_display_message(pPrivate->pEditor, (DasherMessageInfo *)pMessageInfo); // } } extern "C" void on_command(GtkDasherControl *pDasherControl, gchar *szCommand, gpointer pUserData) { if(g_pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); if(pPrivate->pEditor) dasher_editor_command(pPrivate->pEditor, szCommand); } } // TODO: The following two should probably be made the same extern "C" void handle_request_settings(GtkDasherControl * pDasherControl, gpointer data) { // TODO: reimplement // dasher_preferences_dialogue_show(g_pPreferencesDialogue); } extern "C" void gtk2_edit_delete_callback(GtkDasherControl *pDasherControl, const gchar *szText, int iOffset, gpointer user_data) { if(g_pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); if(pPrivate->pEditor) { gint displaylength = g_utf8_strlen(szText, -1); dasher_editor_delete(pPrivate->pEditor, displaylength, iOffset); } } } extern "C" void gtk2_edit_output_callback(GtkDasherControl *pDasherControl, const gchar *szText, int iOffset, gpointer user_data) { if(g_pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(g_pDasherMain); if(pPrivate->pEditor) { dasher_editor_output(pPrivate->pEditor, szText, iOffset); } } } // TODO: The following aren't exported from the editor - need to fix this diff --git a/Src/Gtk2/dasher_main.h b/Src/Gtk2/dasher_main.h index feed7cd..6e0dc79 100644 --- a/Src/Gtk2/dasher_main.h +++ b/Src/Gtk2/dasher_main.h @@ -1,92 +1,93 @@ #ifndef __dasher_main_h__ #define __dasher_main_h__ #include <glib.h> #include <glib-object.h> #include "Preferences.h" #include "KeyboardHelper.h" +#include "dasher_editor.h" #include "DasherAppSettings.h" G_BEGIN_DECLS #define DASHER_TYPE_MAIN (dasher_main_get_type()) #define DASHER_MAIN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), DASHER_TYPE_MAIN, DasherMain )) #define DASHER_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), DASHER_TYPE_MAIN, DasherMainClass )) #define DASHER_IS_MAIN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), DASHER_TYPE_MAIN)) #define DASHER_IS_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), DASHER_TYPE_MAIN)) #define DASHER_MAIN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), DASHER_TYPE_MAIN, DasherMainClass)) // TODO: Make sure this is actually used #define DASHER_MAIN_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), DASHER_TYPE_MAIN, DasherMainPrivate)) typedef struct _DasherMain DasherMain; typedef struct _DasherMainClass DasherMainClass; struct _DasherMain { GObject parent; }; struct _DasherMainClass { GObjectClass parent_class; void (*realized)(DasherMain *pDasherMain); }; struct _DasherMainPrivate { GtkBuilder *pXML; GtkBuilder *pPrefXML; // Child objects owned here DasherAppSettings *pAppSettings; DasherPreferencesDialogue *pPreferencesDialogue; DasherEditor *pEditor; CKeyboardHelper *pKeyboardHelper; // Various widgets which need to be cached: // GtkWidget *pBufferView; GtkPaned *pDivider; GtkWindow *pMainWindow; GtkWidget *pGameDisplay; GtkWidget *pToolbar; GtkSpinButton *pSpeedBox; GtkWidget *pAlphabetCombo; GtkWidget *pStatusControl; GtkWidget *pDasherWidget; GtkListStore *pAlphabetList; GtkAccelGroup *pAccel; gulong iAlphabetComboHandler; // Widgets used for maemo #ifdef WITH_MAEMO DasherMaemoHelper *pMaemoHelper; #ifdef WITH_MAEMOFULLSCREEN HildonProgram *pProgram; HildonWindow *pHWindow; #endif #endif // Properties of the main window int iWidth; int iHeight; bool bWidgetsInitialised; }; typedef struct _DasherMainPrivate DasherMainPrivate; typedef struct _SCommandLine SCommandLine; struct _SCommandLine { gchar *szFilename; gchar *szAppStyle; gchar *szOptions; }; DasherMain *dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine); GType dasher_main_get_type(); //DasherEditorInternal *dasher_main_get_editor(DasherMain *pSelf); void dasher_main_show(DasherMain *pSelf); void dasher_main_toggle_game_mode(DasherMain *pSelf); G_END_DECLS #endif
rgee/HFOSS-Dasher
63ef2ca3fdadf0a8c984e36439c0311d2dd70687
added gamemode directory to version control
diff --git a/Data/gamemode/Makefile.am b/Data/gamemode/Makefile.am new file mode 100644 index 0000000..09a9bde --- /dev/null +++ b/Data/gamemode/Makefile.am @@ -0,0 +1 @@ +pkgdata_DATA = game_mode_english.txt diff --git "a/Data/gamemode/\\" "b/Data/gamemode/\\" new file mode 100644 index 0000000..ef26135 --- /dev/null +++ "b/Data/gamemode/\\" @@ -0,0 +1 @@ +pkgdata_DATA = $(srcdir)/game_mode_*.txt diff --git a/Data/gamemode/game_mode_english.txt b/Data/gamemode/game_mode_english.txt new file mode 100644 index 0000000..ee618b9 --- /dev/null +++ b/Data/gamemode/game_mode_english.txt @@ -0,0 +1,6 @@ +Although my book is intended mainly for the entertainment of boys and +girls, I hope it will not be shunned by men and women on that account, +for part of my plan has been to try to pleasantly remind adults of what +they once were themselves, and of how they felt and thought and talked, +and what queer enterprises they sometimes engaged in. +
rgee/HFOSS-Dasher
c91f88705f8447408912536cfcfd92d2df8632df
Got default game text working and integrated into the build system. Had to do some ugly things in GTK.
diff --git a/Data/Makefile.am b/Data/Makefile.am index 22d07c8..7e9f449 100644 --- a/Data/Makefile.am +++ b/Data/Makefile.am @@ -1,66 +1,66 @@ -SUBDIRS = training alphabets colours controllabels GUI Help +SUBDIRS = training alphabets colours gamemode controllabels GUI Help desktopdir = $(datadir)/applications desktop_in_files = dasher.desktop.in desktop_DATA = $(desktop_in_files:.desktop.in=.desktop) if USE_INTLTOOL @INTLTOOL_DESKTOP_RULE@ else dasher.desktop: dasher.desktop.in cp dasher.desktop.in dasher.desktop endif icondir = $(datadir)/icons/hicolor/48x48/apps icon_DATA = dasher.png svgicondir = $(datadir)/icons/hicolor/scalable/apps svgicon_DATA = dasher.svg gtk_update_icon_cache = gtk-update-icon-cache -f -t $(datadir)/icons/hicolor if GCONF_SCHEMAS_INSTALL schemasdir = $(GCONF_SCHEMA_FILE_DIR) schemas_DATA = dasher.schemas install-data-local: install-schemas # A note on what happens here, as it's a custome step. The GConf # schema is generated directely from the data structures in the # SettingsStore and AppSettings objects, so they stay in sync. This is # done by building generate-schema, a small, non-installed program in # Src/Gtk2/. At install time this gets run to build the schema file, # which is then moved installed in the usual way. None of this happens # if configure is told not to install schemas. dasher.schemas: ../Src/Gtk2/generate-schema echo -n "Generating schema ... "; \ ../Src/Gtk2/generate-schema > dasher.schemas; \ echo "done."; install-schemas: dasher.schemas GCONF_CONFIG_SOURCE=$(GCONF_SCHEMA_CONFIG_SOURCE) \ gconftool-2 --makefile-install-rule dasher.schemas else install-data-local: endif install-data-hook: update-icon-cache uninstall-hook: update-icon-cache update-icon-cache: @-if test -z "$(DESTDIR)"; then \ echo "Updating Gtk icon cache."; \ $(gtk_update_icon_cache); \ else \ echo "*** Icon cache not updated. After (un)install, run this:"; \ echo "*** $(gtk_update_icon_cache)"; \ fi EXTRA_DIST = \ dasher.desktop \ $(icon_DATA) \ $(svgicon_DATA) DISTCLEANFILES = dasher.schemas diff --git a/Data/alphabets/alphabet.english.xml b/Data/alphabets/alphabet.english.xml index 8f3b425..06d39af 100644 --- a/Data/alphabets/alphabet.english.xml +++ b/Data/alphabets/alphabet.english.xml @@ -1,330 +1,334 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE alphabets SYSTEM "alphabet.dtd"> <?xml-stylesheet type="text/xsl" href="alphabet.xsl"?> <alphabets> <alphabet name="English with limited punctuation"> <orientation type="LR"/> <encoding type="Western"/> <palette>European/Asian</palette> <train>training_english_GB.txt</train> +<gamemode>game_mode_english.txt</gamemode> <paragraph d="&#182;" b="9"/> <space d="&#x25a1;" t=" " b="9" note="box" /> <control d="Control" t="" b="8"/> <group name="Lower case Latin letters" b="0"> <s d="a" t="a" b="10"/> <s d="b" t="b" b="11"/> <s d="c" t="c" b="12"/> <s d="d" t="d" b="13"/> <s d="e" t="e" b="14"/> <s d="f" t="f" b="15"/> <s d="g" t="g" b="16"/> <s d="h" t="h" b="17"/> <s d="i" t="i" b="18"/> <s d="j" t="j" b="19"/> <s d="k" t="k" b="20"/> <s d="l" t="l" b="21"/> <s d="m" t="m" b="22"/> <s d="n" t="n" b="23"/> <s d="o" t="o" b="24"/> <s d="p" t="p" b="25"/> <s d="q" t="q" b="26"/> <s d="r" t="r" b="27"/> <s d="s" t="s" b="28"/> <s d="t" t="t" b="29"/> <s d="u" t="u" b="30"/> <s d="v" t="v" b="31"/> <s d="w" t="w" b="32"/> <s d="x" t="x" b="33"/> <s d="y" t="y" b="34"/> <s d="z" t="z" b="35"/> </group> <group name="Upper case Latin letters" b="111"> <s d="A" t="A" b="10"/> <s d="B" t="B" b="11"/> <s d="C" t="C" b="12"/> <s d="D" t="D" b="13"/> <s d="E" t="E" b="14"/> <s d="F" t="F" b="15"/> <s d="G" t="G" b="16"/> <s d="H" t="H" b="17"/> <s d="I" t="I" b="18"/> <s d="J" t="J" b="19"/> <s d="K" t="K" b="20"/> <s d="L" t="L" b="21"/> <s d="M" t="M" b="22"/> <s d="N" t="N" b="23"/> <s d="O" t="O" b="24"/> <s d="P" t="P" b="25"/> <s d="Q" t="Q" b="26"/> <s d="R" t="R" b="27"/> <s d="S" t="S" b="28"/> <s d="T" t="T" b="29"/> <s d="U" t="U" b="30"/> <s d="V" t="V" b="31"/> <s d="W" t="W" b="32"/> <s d="X" t="X" b="33"/> <s d="Y" t="Y" b="34"/> <s d="Z" t="Z" b="35"/> </group> <group name="Punctuation" b="112"> <s d="&amp;" t="&amp;" b="99"/> <s d="&quot;" t="&quot;" b="109"/> <s b="105" d="&#x25cc;&#x0313;" t="&apos;" note=" apostrophe"/> <!-- <s b="105" d="&#x25cc;&#x0313;" t="&apos;" note=" apostrophe"/> --> <!-- <s b="105" d="&#x2323;&#x0313;" t="&apos;" note=" apostrophe above a smile arc"/> --> <!-- <s b="105" d="&#x2319;&#x0313;" t="&apos;" note=" apostrophe"/> --> <s d="?" t="?" b="103"/> <s d="!" t="!" b="104"/> <!-- <s d="&#x2312;&#x0326;" t="," b="100" note="overarced comma"/> --> <s d="," t="," b="100" note="&#x236A; overlined comma"/> <s d="&#183;" t="." b="104"/> </group> </alphabet> <alphabet name="English with numerals and limited punctuation"> <orientation type="LR"/> <encoding type="Western"/> <palette>European/Asian</palette> <train>training_english_GB.txt</train> +<gamemode>game_mode_english.txt</gamemode> <paragraph d="&#182;" b="9"/> <space d="&#x25a1;" t=" " b="9" note="box" /> <control d="Control" t="" b="8"/> <group name="Lower case Latin letters" b="0"> <s d="a" t="a" b="10"/> <s d="b" t="b" b="11"/> <s d="c" t="c" b="12"/> <s d="d" t="d" b="13"/> <s d="e" t="e" b="14"/> <s d="f" t="f" b="15"/> <s d="g" t="g" b="16"/> <s d="h" t="h" b="17"/> <s d="i" t="i" b="18"/> <s d="j" t="j" b="19"/> <s d="k" t="k" b="20"/> <s d="l" t="l" b="21"/> <s d="m" t="m" b="22"/> <s d="n" t="n" b="23"/> <s d="o" t="o" b="24"/> <s d="p" t="p" b="25"/> <s d="q" t="q" b="26"/> <s d="r" t="r" b="27"/> <s d="s" t="s" b="28"/> <s d="t" t="t" b="29"/> <s d="u" t="u" b="30"/> <s d="v" t="v" b="31"/> <s d="w" t="w" b="32"/> <s d="x" t="x" b="33"/> <s d="y" t="y" b="34"/> <s d="z" t="z" b="35"/> </group> <group name="Upper case Latin letters" b="111"> <s d="A" t="A" b="10"/> <s d="B" t="B" b="11"/> <s d="C" t="C" b="12"/> <s d="D" t="D" b="13"/> <s d="E" t="E" b="14"/> <s d="F" t="F" b="15"/> <s d="G" t="G" b="16"/> <s d="H" t="H" b="17"/> <s d="I" t="I" b="18"/> <s d="J" t="J" b="19"/> <s d="K" t="K" b="20"/> <s d="L" t="L" b="21"/> <s d="M" t="M" b="22"/> <s d="N" t="N" b="23"/> <s d="O" t="O" b="24"/> <s d="P" t="P" b="25"/> <s d="Q" t="Q" b="26"/> <s d="R" t="R" b="27"/> <s d="S" t="S" b="28"/> <s d="T" t="T" b="29"/> <s d="U" t="U" b="30"/> <s d="V" t="V" b="31"/> <s d="W" t="W" b="32"/> <s d="X" t="X" b="33"/> <s d="Y" t="Y" b="34"/> <s d="Z" t="Z" b="35"/> </group> <group name="Numbers" b="113"> <s d="1" t="1" b="90"/> <s d="2" t="2" b="91"/> <s d="3" t="3" b="92"/> <s d="4" t="4" b="93"/> <s d="5" t="5" b="94"/> <s d="6" t="6" b="90"/> <s d="7" t="7" b="91"/> <s d="8" t="8" b="92"/> <s d="9" t="9" b="93"/> <s d="0" t="0" b="94"/> </group> <group name="Punctuation" b="112"> <s d="&amp;" t="&amp;" b="99"/> <s d="&quot;" t="&quot;" b="109"/> <s b="105" d="&#x25cc;&#x0313;" t="&apos;" note=" apostrophe"/> <s d="?" t="?" b="103"/> <s d="!" t="!" b="104"/> <s d="," t="," b="100"/> <s d="&#183;" t="." b="104"/> </group> </alphabet> <alphabet name="English with numerals and lots of punctuation"> <orientation type="LR"/> <encoding type="Western"/> <palette>European/Asian</palette> <train>training_english_GB.txt</train> +<gamemode>game_mode_english.txt</gamemode> <space d="&#x25a1;" t=" " b="9"/> <control d="Control" t=""/> <paragraph d="&#182;" b="9"/> <group name="Lower case Latin letters" b="0"> <s d="a" t="a" b="10"/> <s d="b" t="b" b="11"/> <s d="c" t="c" b="12"/> <s d="d" t="d" b="13"/> <s d="e" t="e" b="14"/> <s d="f" t="f" b="15"/> <s d="g" t="g" b="16"/> <s d="h" t="h" b="17"/> <s d="i" t="i" b="18"/> <s d="j" t="j" b="19"/> <s d="k" t="k" b="20"/> <s d="l" t="l" b="21"/> <s d="m" t="m" b="22"/> <s d="n" t="n" b="23"/> <s d="o" t="o" b="24"/> <s d="p" t="p" b="25"/> <s d="q" t="q" b="26"/> <s d="r" t="r" b="27"/> <s d="s" t="s" b="28"/> <s d="t" t="t" b="29"/> <s d="u" t="u" b="30"/> <s d="v" t="v" b="31"/> <s d="w" t="w" b="32"/> <s d="x" t="x" b="33"/> <s d="y" t="y" b="34"/> <s d="z" t="z" b="35"/> </group> <group name="Upper case Latin letters" b="111"> <s d="A" t="A" b="10"/> <s d="B" t="B" b="11"/> <s d="C" t="C" b="12"/> <s d="D" t="D" b="13"/> <s d="E" t="E" b="14"/> <s d="F" t="F" b="15"/> <s d="G" t="G" b="16"/> <s d="H" t="H" b="17"/> <s d="I" t="I" b="18"/> <s d="J" t="J" b="19"/> <s d="K" t="K" b="20"/> <s d="L" t="L" b="21"/> <s d="M" t="M" b="22"/> <s d="N" t="N" b="23"/> <s d="O" t="O" b="24"/> <s d="P" t="P" b="25"/> <s d="Q" t="Q" b="26"/> <s d="R" t="R" b="27"/> <s d="S" t="S" b="28"/> <s d="T" t="T" b="29"/> <s d="U" t="U" b="30"/> <s d="V" t="V" b="31"/> <s d="W" t="W" b="32"/> <s d="X" t="X" b="33"/> <s d="Y" t="Y" b="34"/> <s d="Z" t="Z" b="35"/> </group> <group name="Numbers" b="113"> <s d="1" t="1" b="90"/> <s d="2" t="2" b="91"/> <s d="3" t="3" b="92"/> <s d="4" t="4" b="93"/> <s d="5" t="5" b="94"/> <s d="6" t="6" b="90"/> <s d="7" t="7" b="91"/> <s d="8" t="8" b="92"/> <s d="9" t="9" b="93"/> <s d="0" t="0" b="94"/> </group> <group name="Punctuation" b="112"> <s b="90" d="%" t="%"/> <s b="91" d="*" t="*"/> <s b="92" d="+" t="+"/> <s b="93" d="=" t="="/> <s b="94" d="/" t="/"/> <s b="95" d="#" t="#"/> <s d="&#8364;" t="&#8364;" b="96" note="euro" /> <s b="97" d="&#163;" t="&#163;" note="Pound" /> <s b="98" d="$" t="$"/> <s b="99" d="|" t="|"/> <s b="95" d="\" t="\"/> <s b="96" d="~" t="~"/> <s b="97" d="^" t="^"/> <s b="98" d="_" t="_"/> <s b="99" d="&amp;" t="&amp;"/> <s b="95" d="@" t="@"/> <s b="105" d="[" t="["/> <s b="106" d="]" t="]"/> <s b="107" d="{" t="{"/> <s b="108" d="}" t="}"/> <s b="109" d="&lt;" t="&lt;"/> <s b="105" d="&gt;" t="&gt;"/> <s b="106" d="(" t="("/> <s b="107" d=")" t=")"/> <s b="108" d="&#x201C;" t="&#x201C;" note="left double quotation mark" /> <s b="109" d="&#x0022;" t="&#x0022;" note="deprecated vertical double quotation mark" /> <s b="106" d="&#x201D;" t="&#x201D;" note="right double quotation mark" /> <s b="107" d="&#x2018;" t="&#x2018;" note="left single quotation mark" /> <s b="108" d="&#x2019;" t="&#x2019;" note="right single quotation mark and apostrophe" /> <s b="109" d="`" t="`" note="left quote from keyboard" /> <s b="105" d="&#x25cc;&#x0313;" t="&apos;" note=" apostrophe"/> <s b="9" d="&#x25CA;" t="&#x9;" note="TAB (represented by a diamond)"/> <s b="100" d="-" t="-"/> <s b="101" d=":" t=":"/> <s b="102" d=";" t=";"/> <s b="103" d="?" t="?"/> <s b="104" d="!" t="!"/> <s b="100" d="," t=","/> <s d="&#183;" t="." b="104"/> </group> </alphabet> <alphabet name="English, lower case"> <orientation type="LR"/> <encoding type="Western"/> <palette>European/Asian</palette> <train>training_englishLC_GB.txt</train> +<gamemode>game_mode_english.txt</gamemode> <space d="&#x25a1;" t=" " b="9" note="box" /> <control d="Control" t="" b="8"/> <group name="Lower case Latin letters" b="0"> <s d="a" t="a" b="10"/> <s d="b" t="b" b="11"/> <s d="c" t="c" b="12"/> <s d="d" t="d" b="13"/> <s d="e" t="e" b="14"/> <s d="f" t="f" b="15"/> <s d="g" t="g" b="16"/> <s d="h" t="h" b="17"/> <s d="i" t="i" b="18"/> <s d="j" t="j" b="19"/> <s d="k" t="k" b="20"/> <s d="l" t="l" b="21"/> <s d="m" t="m" b="22"/> <s d="n" t="n" b="23"/> <s d="o" t="o" b="24"/> <s d="p" t="p" b="25"/> <s d="q" t="q" b="26"/> <s d="r" t="r" b="27"/> <s d="s" t="s" b="28"/> <s d="t" t="t" b="29"/> <s d="u" t="u" b="30"/> <s d="v" t="v" b="31"/> <s d="w" t="w" b="32"/> <s d="x" t="x" b="33"/> <s d="y" t="y" b="34"/> <s d="z" t="z" b="35"/> </group> <group name="Punctuation" b="112"> <s b="105" d="&#x25cc;&#x0313;" t="&apos;" /> <s b="103" d="?" t="?" /> <s b="104" d="!" t="!" /> <s b="100" d="," t="," /> <s b="104" d="&#183;" t="." /> </group> </alphabet> </alphabets> diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 2f1b3ef..b62a10b 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1190 +1,1195 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <tr1/memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; m_pGameDisplay = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); InitGameModule(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); case BP_GAME_MODE: if(GetBoolParameter(BP_GAME_MODE)) { InitGameModule(); } else if(m_pGameModule){ + CreateModel(0); ResetGameModule(); } default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } else if(pEvent->m_iEventType == EV_GAME_MODE_COMPLETE) { SetBoolParameter(BP_GAME_MODE, false); Pause(); } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule && GetBoolParameter(BP_GAME_MODE)) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } /** * Reset the dasher model, fetch the game module from the module manager, * set its word generator, and make it available via m_pGameModule. */ void CDasherInterfaceBase::InitGameModule() { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); if(GetBoolParameter(BP_GAME_MODE)) { - //CreateModel(0); + + if(GetStringParameter(SP_GAME_TEXT_FILE) == "") + SetStringParameter(SP_GAME_TEXT_FILE, + GetStringParameter(SP_SYSTEM_LOC) + m_Alphabet->GetGameModeFile()); + m_pGameModule->SetWordGenerator(new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE))); } } /** - * Reset the game module, reset the dasher model, and set m_pGameModule to NULL. + * Reset the game module, and set m_pGameModule to NULL. */ void CDasherInterfaceBase::ResetGameModule() { if(m_pGameModule) { m_pGameModule->reset(); - CreateModel(0); + SetStringParameter(SP_GAME_TEXT_FILE, ""); m_pGameModule = NULL; } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index ce33f65..727f34a 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,215 +1,216 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, }; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); } case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; DecorateDisplay(); m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; if(m_pGameDisplay) m_pGameDisplay->hide(); if(m_pWordGenerator) delete m_pWordGenerator; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); std::string nextWord; for(int i = 0; i < m_iTargetChunkSize; i++) { nextWord = m_pWordGenerator->GetNextWord(); //done with game text if(nextWord == "") { m_sTargetString = ""; m_pGameDisplay->alert("Congratulations! You've completed Dasher game mode!"); m_pEventHandler->InsertEvent(new CGameModeCompleteEvent()); return; } else { m_sTargetString += nextWord; m_sTargetString += " "; } } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); DecorateDisplay(); } void CGameModule::DecorateDisplay() { + if(m_pGameDisplay == NULL) return; std::vector<std::string> colors = std::vector<std::string>(); for(int pos = 0; pos < m_sTargetString.length(); pos++) { if(pos < m_iCurrentStringPos + 1) { colors.push_back("blue"); } else if(pos == m_iCurrentStringPos + 1) { colors.push_back("red"); } else { colors.push_back("black"); } } m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { m_pGameDisplay = pGameDisplay; } diff --git a/Src/Gtk2/DasherControl.cpp b/Src/Gtk2/DasherControl.cpp index 951ba87..1088feb 100644 --- a/Src/Gtk2/DasherControl.cpp +++ b/Src/Gtk2/DasherControl.cpp @@ -1,637 +1,638 @@ #include "../Common/Common.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <iostream> #include "DasherControl.h" #include "Timer.h" #include "../DasherCore/Event.h" #include "../DasherCore/ModuleManager.h" #include "GtkGameDisplay.h" #include <fcntl.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <sys/stat.h> #include <unistd.h> using namespace std; // 'Private' methods (only used in this file) extern "C" gint key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data); extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data); extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data); extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData); extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data); static bool g_iTimeoutID = 0; // CDasherControl class definitions CDasherControl::CDasherControl(GtkVBox *pVBox, GtkDasherControl *pDasherControl) { m_pPangoCache = NULL; m_pScreen = NULL; m_pDasherControl = pDasherControl; m_pVBox = GTK_WIDGET(pVBox); Realize(); // m_pKeyboardHelper = new CKeyboardHelper(this); // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); } void CDasherControl::CreateModules() { - g_message("Creating modules"); - CDasherInterfaceBase::CreateModules(); //create default set first // Create locally cached copies of the mouse input objects, as we // need to pass coordinates to them from the timer callback m_pMouseInput = (CDasherMouseInput *) RegisterModule(new CDasherMouseInput(m_pEventHandler, m_pSettingsStore)); SetDefaultInputDevice(m_pMouseInput); m_p1DMouseInput = (CDasher1DMouseInput *)RegisterModule(new CDasher1DMouseInput(m_pEventHandler, m_pSettingsStore)); RegisterModule(new CSocketInput(m_pEventHandler, m_pSettingsStore)); #ifdef JOYSTICK RegisterModule(new CDasherJoystickInput(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CDasherJoystickInputDiscrete(m_pEventHandler, m_pSettingsStore, this)); #endif #ifdef TILT RegisterModule(new CDasherTiltInput(m_pEventHandler, m_pSettingsStore, this)); #endif } void CDasherControl::SetupUI() { m_pCanvas = gtk_drawing_area_new(); #if GTK_CHECK_VERSION (2,18,0) gtk_widget_set_can_focus(m_pCanvas, TRUE); #else GTK_WIDGET_SET_FLAGS(m_pCanvas, GTK_CAN_FOCUS); #endif gtk_widget_set_double_buffered(m_pCanvas, FALSE); GtkWidget *pFrame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(pFrame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(pFrame), m_pCanvas); gtk_box_pack_start(GTK_BOX(m_pVBox), pFrame, TRUE, TRUE, 0); gtk_widget_show_all(GTK_WIDGET(m_pVBox)); // Connect callbacks - note that we need to implement the callbacks // as "C" style functions and pass this as user data so they can // call the object g_signal_connect(m_pCanvas, "button_press_event", G_CALLBACK(button_press_event), this); g_signal_connect(m_pCanvas, "button_release_event", G_CALLBACK(button_press_event), this); g_signal_connect_after(m_pCanvas, "realize", G_CALLBACK(realize_canvas), this); g_signal_connect(m_pCanvas, "configure_event", G_CALLBACK(canvas_configure_event), this); g_signal_connect(m_pCanvas, "destroy", G_CALLBACK(canvas_destroy_event), this); g_signal_connect(m_pCanvas, "key-release-event", G_CALLBACK(key_release_event), this); g_signal_connect(m_pCanvas, "key_press_event", G_CALLBACK(key_press_event), this); g_signal_connect(m_pCanvas, "focus_in_event", G_CALLBACK(canvas_focus_event), this); g_signal_connect(m_pCanvas, "expose_event", G_CALLBACK(canvas_expose_event), this); //g_signal_connect(m_pDasher) // Create the Pango cache // TODO: Use system defaults? if(GetStringParameter(SP_DASHER_FONT) == "") SetStringParameter(SP_DASHER_FONT, "Sans 10"); m_pPangoCache = new CPangoCache(GetStringParameter(SP_DASHER_FONT)); } void CDasherControl::SetupPaths() { char *home_dir; char *user_data_dir; const char *system_data_dir; home_dir = getenv("HOME"); user_data_dir = new char[strlen(home_dir) + 10]; sprintf(user_data_dir, "%s/.dasher/", home_dir); mkdir(user_data_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // PROGDATA is provided by the makefile system_data_dir = PROGDATA "/"; SetStringParameter(SP_SYSTEM_LOC, system_data_dir); SetStringParameter(SP_USER_LOC, user_data_dir); delete[] user_data_dir; } void CDasherControl::CreateGameDisplay(void* pGameDisplay) { m_pGameDisplay = new GtkGameDisplay(GTK_WIDGET(pGameDisplay)); InitGameModule(); m_pGameModule->SetGameDisplay(m_pGameDisplay); } void CDasherControl::CreateSettingsStore() { m_pSettingsStore = new CGnomeSettingsStore(m_pEventHandler); } void CDasherControl::ScanAlphabetFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *alphabetglob; alphabetglob = g_pattern_spec_new("alphabet*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(alphabetglob); } void CDasherControl::ScanColourFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *colourglob; colourglob = g_pattern_spec_new("colour*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(colourglob); } CDasherControl::~CDasherControl() { if(m_pMouseInput) { m_pMouseInput = NULL; } if(m_p1DMouseInput) { m_p1DMouseInput = NULL; } if(m_pPangoCache) { delete m_pPangoCache; m_pPangoCache = NULL; } // if(m_pKeyboardHelper) { // delete m_pKeyboardHelper; // m_pKeyboardHelper = 0; // } } bool CDasherControl::FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent) { if((pEvent->type == GDK_FOCUS_CHANGE) && (pEvent->in)) { GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); gboolean *returnType; focusEvent->type = GDK_FOCUS_CHANGE; focusEvent->window = (GdkWindow *) m_pDasherControl; focusEvent->send_event = FALSE; focusEvent->in = TRUE; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "focus_in_event", GTK_WIDGET(m_pDasherControl), focusEvent, NULL, &returnType); } return true; } void CDasherControl::SetFocus() { gtk_widget_grab_focus(m_pCanvas); } void CDasherControl::GameMessageOut(int message, const void* messagedata) { gtk_dasher_control_game_messageout(m_pDasherControl, message, messagedata); } GArray *CDasherControl::GetAllowedValues(int iParameter) { // Glib version of the STL based core function GArray *pRetVal(g_array_new(false, false, sizeof(gchar *))); std::vector < std::string > vList; GetPermittedValues(iParameter, vList); for(std::vector < std::string >::iterator it(vList.begin()); it != vList.end(); ++it) { // For internal glib reasons we need to make a variable and then // pass - we can't use the iterator directly const char *pTemp(it->c_str()); char *pTempNew = new char[strlen(pTemp) + 1]; strcpy(pTempNew, pTemp); g_array_append_val(pRetVal, pTempNew); } return pRetVal; } void CDasherControl::RealizeCanvas(GtkWidget *pWidget) { // TODO: Pointless function - call directly from C callback. #ifdef DEBUG std::cout << "RealizeCanvas()" << std::endl; #endif OnUIRealised(); } void CDasherControl::StartTimer() { // Start the timer loops as everything is set up. // Aim for 40 frames per second, computers are getting faster. if(g_iTimeoutID == 0) { g_iTimeoutID = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 25, timer_callback, this, NULL); // TODO: Reimplement this (or at least reimplement some kind of status reporting) //g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 5000, long_timer_callback, this, NULL); } } void CDasherControl::ShutdownTimer() { // TODO: Figure out how to implement this - at the moment it's done // through a return value from the timer callback, but it would be // nicer to prevent any further calls as soon as the shutdown signal // has been receieved. } int CDasherControl::CanvasConfigureEvent() { GtkAllocation a; #if GTK_CHECK_VERSION (2,18,0) gtk_widget_get_allocation(m_pCanvas, &a); #else a.width = m_pCanvas->allocation.width; a.height = m_pCanvas->allocation.height; #endif if(m_pScreen != NULL) delete m_pScreen; m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache, a.width, a.height); ChangeScreen(m_pScreen); return 0; } void CDasherControl::ExternalEventHandler(Dasher::CEvent *pEvent) { // Convert events coming from the core to Glib signals. if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); HandleParameterNotification(pEvt->m_iParameter); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_changed", pEvt->m_iParameter); } else if(pEvent->m_iEventType == EV_EDIT) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { // Insert event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_insert", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 2) { // Delete event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 10) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_convert"); } else if(pEditEvent->m_iEditType == 11) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_protect"); } } else if(pEvent->m_iEventType == EV_EDIT_CONTEXT) { CEditContextEvent *pEditContextEvent(static_cast < CEditContextEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_context_request", pEditContextEvent->m_iOffset, pEditContextEvent->m_iLength); } else if(pEvent->m_iEventType == EV_START) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_start"); } else if(pEvent->m_iEventType == EV_STOP) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_stop"); } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast < CControlEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_control", pControlEvent->m_iID); } else if(pEvent->m_iEventType == EV_LOCK) { CLockEvent *pLockEvent(static_cast<CLockEvent *>(pEvent)); DasherLockInfo sInfo; sInfo.szMessage = pLockEvent->m_strMessage.c_str(); sInfo.bLock = pLockEvent->m_bLock; sInfo.iPercent = pLockEvent->m_iPercent; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_lock_info", &sInfo); } else if(pEvent->m_iEventType == EV_MESSAGE) { CMessageEvent *pMessageEvent(static_cast<CMessageEvent *>(pEvent)); DasherMessageInfo sInfo; sInfo.szMessage = pMessageEvent->m_strMessage.c_str(); sInfo.iID = pMessageEvent->m_iID; sInfo.iType = pMessageEvent->m_iType; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_message", &sInfo); } else if(pEvent->m_iEventType == EV_COMMAND) { CCommandEvent *pCommandEvent(static_cast<CCommandEvent *>(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_command", pCommandEvent->m_strCommand.c_str()); } + else if(pEvent->m_iEventType == EV_GAME_MODE_COMPLETE) { + //TODO: clear the dasher editor text here! + } }; void CDasherControl::WriteTrainFile(const std::string &strNewText) { if(strNewText.length() == 0) return; std::string strFilename(GetStringParameter(SP_USER_LOC) + GetStringParameter(SP_TRAIN_FILE)); int fd=open(strFilename.c_str(),O_CREAT|O_WRONLY|O_APPEND,S_IRUSR|S_IWUSR); write(fd,strNewText.c_str(),strNewText.length()); close(fd); } // TODO: Sort these methods out void CDasherControl::ExternalKeyDown(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyDown(get_time(), iButtonID); // } KeyDown(get_time(), iKeyVal); } void CDasherControl::ExternalKeyUp(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyUp(get_time(), iButtonID); // } KeyUp(get_time(), iKeyVal); } void CDasherControl::HandleParameterNotification(int iParameter) { switch(iParameter) { case SP_DASHER_FONT: if(m_pPangoCache) { m_pPangoCache->ChangeFont(GetStringParameter(SP_DASHER_FONT)); ScheduleRedraw(); } break; case BP_GLOBAL_KEYBOARD: // TODO: reimplement // if(m_pKeyboardHelper) // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); break; } } int CDasherControl::TimerEvent() { int x, y; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_pointer(gtk_widget_get_window(m_pCanvas), &x, &y, NULL); #else gdk_window_get_pointer(m_pCanvas->window, &x, &y, NULL); #endif m_pMouseInput->SetCoordinates(x, y); gdk_window_get_pointer(gdk_get_default_root_window(), &x, &y, NULL); int iRootWidth; int iRootHeight; gdk_drawable_get_size(gdk_get_default_root_window(), &iRootWidth, &iRootHeight); if(GetLongParameter(LP_YSCALE) < 10) SetLongParameter(LP_YSCALE, 10); y = (y - iRootHeight / 2); m_p1DMouseInput->SetCoordinates(y, GetLongParameter(LP_YSCALE)); NewFrame(get_time(), false); // Update our UserLog object about the current mouse position CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { // We want current canvas and window coordinates so normalization // is done properly with respect to the canvas. GdkRectangle sWindowRect; GdkRectangle sCanvasRect; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_frame_extents(gtk_widget_get_window(m_pCanvas), &sWindowRect); #else gdk_window_get_frame_extents(m_pCanvas->window, &sWindowRect); #endif pUserLog->AddWindowSize(sWindowRect.y, sWindowRect.x, sWindowRect.y + sWindowRect.height, sWindowRect.x + sWindowRect.width); if (m_pScreen != NULL) { if (m_pScreen->GetCanvasSize(&sCanvasRect)) pUserLog->AddCanvasSize(sCanvasRect.y, sCanvasRect.x, sCanvasRect.y + sCanvasRect.height, sCanvasRect.x + sCanvasRect.width); } int iMouseX = 0; int iMouseY = 0; gdk_window_get_pointer(NULL, &iMouseX, &iMouseY, NULL); // TODO: This sort of thing shouldn't be in specialised methods, move into base class somewhere pUserLog->AddMouseLocationNormalized(iMouseX, iMouseY, true, GetNats()); } return 1; // See CVS for code which used to be here } int CDasherControl::LongTimerEvent() { // std::cout << "Framerate: " << GetFramerate() << std::endl; // std::cout << "Render count: " << GetRenderCount() << std::endl; return 1; } gboolean CDasherControl::ExposeEvent() { NewFrame(get_time(), true); return 0; } gboolean CDasherControl::ButtonPressEvent(GdkEventButton *event) { // Take the focus if we click on the canvas // GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); // gboolean *returnType; // focusEvent->type = GDK_FOCUS_CHANGE; // focusEvent->window = (GdkWindow *) m_pCanvas; // focusEvent->send_event = FALSE; // focusEvent->in = TRUE; // gtk_widget_grab_focus(GTK_WIDGET(m_pCanvas)); // g_signal_emit_by_name(GTK_OBJECT(m_pCanvas), "focus_in_event", GTK_WIDGET(m_pCanvas), focusEvent, NULL, &returnType); // No - don't take the focus - give it to the text area instead if(event->type == GDK_BUTTON_PRESS) HandleClickDown(get_time(), (int)event->x, (int)event->y); else if(event->type == GDK_BUTTON_RELEASE) HandleClickUp(get_time(), (int)event->x, (int)event->y); return false; } gint CDasherControl::KeyReleaseEvent(GdkEventKey *event) { // TODO: This is seriously flawed - the semantics of of X11 Keyboard // events mean the there's no guarantee that key up/down events will // be received in pairs. if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) { // if(event->state & GDK_CONTROL_MASK) // SetLongParameter(LP_BOOSTFACTOR, 25); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) { // if(event->state & GDK_SHIFT_MASK) // SetLongParameter(LP_BOOSTFACTOR, 175); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyUp(get_time(), iKeyVal); // } } return 0; } gint CDasherControl::KeyPressEvent(GdkEventKey *event) { // if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) // SetLongParameter(LP_BOOSTFACTOR, 175); // else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) // SetLongParameter(LP_BOOSTFACTOR, 25); // else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyDown(get_time(), iKeyVal); // } // } return 0; } void CDasherControl::CanvasDestroyEvent() { // Delete the screen if(m_pScreen != NULL) { delete m_pScreen; m_pScreen = NULL; } } // Tell the logging object that a new user trial is starting. void CDasherControl::UserLogNewTrial() { CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { pUserLog->NewTrial(); } } int CDasherControl::GetFileSize(const std::string &strFileName) { struct stat sStatInfo; if(!stat(strFileName.c_str(), &sStatInfo)) return sStatInfo.st_size; else return 0; } // "C" style callbacks - these are here just because it's not possible // (or at least not easy) to connect a callback directly to a C++ // method, so we pass a pointer to th object in the user_data field // and use a wrapper function. Please do not put any functional code // here. extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data) { static_cast < CDasherControl * >(user_data)->RealizeCanvas(widget); } extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) { return static_cast < CDasherControl * >(data)->ButtonPressEvent(event); } extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { return static_cast < CDasherControl * >(data)->KeyPressEvent(event); } extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { return static_cast < CDasherControl * >(data)->CanvasConfigureEvent(); } extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData) { static_cast<CDasherControl*>(pUserData)->CanvasDestroyEvent(); } extern "C" gint key_release_event(GtkWidget *pWidget, GdkEventKey *event, gpointer pUserData) { return static_cast<CDasherControl*>(pUserData)->KeyReleaseEvent(event); } extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return static_cast < CDasherControl * >(data)->FocusEvent(widget, event); } extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data) { return ((CDasherControl*)data)->ExposeEvent(); } diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index d2312c0..0ccb88e 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -90,1091 +90,1101 @@ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } g_message("loading interface"); dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); pPrivate->pGameDisplay = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "GameDisplay")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); gtk_dasher_control_set_game_display(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), pPrivate->pGameDisplay); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // /** * Clear all text out of the dasher editor. * @param pSelf a reference to an instance of DasherMain */ void clear_dasher_editor_text(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } /** * Start game mode, specify the text to play with, and clear out any text in the dasher editor. * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. * * @param pGameTextFilePath - the absolute path to the text file to play with * @param pSelf - a reference to an instance of DasherMain */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkDasherControl *pControl = GTK_DASHER_CONTROL(pPrivate->pDasherWidget); gtk_widget_set_visible(GTK_WIDGET(pPrivate->pGameDisplay), true); dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); clear_dasher_editor_text(pSelf); } +void init_game_from_default_button(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { + init_game_mode(_(""), (DasherMain*)pData); + + //TODO: this is really ugly - clearly symptomatic of doing something wrong with GTK + //but I can't figure out what. For now, it makes the UI behave properly. + gtk_widget_destroy(gtk_widget_get_parent( + gtk_widget_get_parent( + (gtk_widget_get_parent(GTK_WIDGET(pButton)))))); +} + /** * Event handler which displays a standard GTK file dialog. The dialog allows the user * to specify a text file to play game mode with. * * @param pButton the button that fired the event * @param pWidget reference needed by GTK for callback signature * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references * to the dialog's parent window and an instance of DasherMain */ void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } void quit_game_mode(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE((DasherMain*)pData); } /** * Toggle game mode on and off. Toggling on causes a dialog box to be displayed * welcoming the user to game mode and prompting them to specify a file to play with. * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core * to respond appropriately. * * @param pSelf a reference to an instance of DasherMain */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); - GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); + GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), GTK_RESPONSE_NONE); gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); - //g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) + g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK(init_game_from_default_button), pSelf); g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Are you sure you wish to turn off game mode? All unsaved changes will be lost.")); GtkWidget *pNoButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_NO, GTK_RESPONSE_REJECT); GtkWidget *pYesButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_YES, GTK_RESPONSE_ACCEPT); //g_signal_connect(pYesButton, "button-press-event", G_CALLBACK(quit_game_mode), (gpointer)pSelf); switch(gtk_dialog_run(GTK_DIALOG(pDialog))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialog)); break; case GTK_RESPONSE_ACCEPT: dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); clear_dasher_editor_text(pSelf); } if(GTK_IS_WIDGET(pDialog)) { gtk_widget_destroy(GTK_WIDGET(pDialog)); } } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; } } else { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Are you sure you wish to quit?")); gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't quit"), GTK_RESPONSE_REJECT, _("Quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: gtk_main_quit(); } } } static void dasher_main_command_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 0); } static void dasher_main_command_preferences_alphabet(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 1); } static void dasher_main_command_tutorial(DasherMain *pSelf) { // TODO: Implement this } static void dasher_main_command_help(DasherMain *pSelf) { #ifdef HAVE_GTK_SHOW_URI DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GdkScreen *scr; GError *err = NULL; scr = gtk_widget_get_screen(GTK_WIDGET(pPrivate->pMainWindow)); if (!gtk_show_uri(scr, "ghelp:dasher", gtk_get_current_event_time(), &err)) { GtkWidget *d; diff --git a/configure.ac b/configure.ac index 66f6757..2e691c3 100644 --- a/configure.ac +++ b/configure.ac @@ -1,417 +1,418 @@ AC_PREREQ(2.5) AC_INIT([dasher],[4.11]) # This becomes part of AC_INIT in autoconf 2.64 m4_ifndef([AC_PACKAGE_URL], [m4_define([AC_PACKAGE_URL],["http://www.inference.phy.cam.ac.uk/dasher/"]) AC_DEFINE_UNQUOTED([PACKAGE_URL], [AC_PACKAGE_URL], [Define to the home page for this package.]) AC_SUBST([PACKAGE_URL],[AC_PACKAGE_URL])]) AC_CONFIG_SRCDIR([Src/main.cc]) AC_CONFIG_HEADERS(config.h) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE AM_MAINTAINER_MODE AC_PROG_MAKE_SET # IT_PROG_INTLTOOL requires AM_NLS but ignores --enable-nls AM_NLS AM_CONDITIONAL(USE_INTLTOOL, test "x$USE_NLS" = "xyes") AS_IF([test "x$USE_NLS" = "xyes"],[ IT_PROG_INTLTOOL([0.40.1]) ], [touch po/Makefile.in.in]) dnl as intltoolize insists LT_INIT([disable-static]) dnl AM_ICONV GETTEXT_PACKAGE=dasher AC_SUBST(GETTEXT_PACKAGE) AC_DEFINE_UNQUOTED(GETTEXT_PACKAGE,"$GETTEXT_PACKAGE", [Gettext package]) AM_GLIB_GNU_GETTEXT AC_PROG_CXX AC_PROG_LD_GNU WITHGTK2=true; PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.6) AC_LANG_PUSH(C++) AC_CHECK_FUNCS(lldiv) AC_CHECK_FUNC(socket,,[AC_CHECK_LIB(socket,socket)]) AC_LANG_POP(C++) AC_ARG_ENABLE(debug, AS_HELP_STRING([--enable-debug], [build with additional debugging checks (default is NO)]), if test "x$enable_debug" = "xno"; then DEBUG=false else DEBUG=true fi, DEBUG=false) AC_ARG_WITH([gnome], AS_HELP_STRING([--with-gnome],[build GNOME documentation (default is YES)]), if test "x$with_gnome" = "xno"; then WITHGNOME=false else WITHGNOME=true # Need to work out how to translate replaced variables before uncommenting # AC_CONFIG_FILES([Data/Help/Gnome/C/dasher.xml]) fi, WITHGNOME=true) dnl Just useful for debugging AC_ARG_WITH([gvfs], AS_HELP_STRING([--with-gvfs], [build with gvfs from gio in glib (default is YES)]), [], with_gvfs="yes") if test "x$with_gvfs" != "xno"; then PKG_CHECK_MODULES(GIO, gio-2.0, [have_gio=true AC_DEFINE(HAVE_GIO, 1, [gio exists so use gvfs])], [have_gio=false]) fi AC_ARG_ENABLE([speech], AS_HELP_STRING([--enable-speech],[build with speech support (default is NO)]), if test "x$enableval" = "xno"; then WITHSPEECH=false; else WITHSPEECH=true; fi, WITHSPEECH=false) AC_ARG_WITH([qte], AS_HELP_STRING([--with-qte],[build with QTE support (default is NO -- currently untested)]), if test "x$withval" = "xno"; then WITHQTE=false; else WITHQTE=true; fi, WITHQTE=false) AC_ARG_WITH([gpe], AS_HELP_STRING([--with-gpe],[build with GPE support (default is NO -- currently untested)]), if test "x$withval" = "xno"; then WITHGPE=false; else WITHGPE=true; fi, WITHGPE=false) AC_ARG_ENABLE([a11y], AS_HELP_STRING([--enable-a11y],[build with support for the GNOME accessibility framework (default is YES)]), if test "x$enableval" = "xno"; then WITHA11Y=false; else WITHA11Y=true; fi, WITHA11Y=true) AC_ARG_ENABLE([japanese], AS_HELP_STRING([--enable-japanese],[build with support for Japanese Kanji entry (experimental -- default is NO)]), if test "x$enableval" = "xno"; then WITHJAPANESE=false; else AC_CHECK_LIB(canna, RkBgnBun,, AC_MSG_ERROR([Canna library not found (required for Japanese).])) WITHJAPANESE=true; fi, WITHJAPANESE=false) AC_ARG_ENABLE([joystick], AS_HELP_STRING([--enable-joystick],[Build with Linux joystick support (note that other UNIX based operating systems aren't supported here)]), if test "x$enableval" = "xno"; then WITHJOYSTICK=false; else WITHJOYSTICK=true; fi, WITHJOYSTICK=false) AC_ARG_ENABLE([tilt], AS_HELP_STRING([--enable-tilt],[Build with experimental support for tilt sensor input (experimental -- default is NO)]), if test "x$enableval" = "xno"; then WITHTILT=false; else WITHTILT=true; fi, WITHTILT=false) AC_ARG_WITH([maemo], AS_HELP_STRING([--with-maemo],[build with Maemo support (default is NO)]), if test "x$withval" = "xyes"; then WITHMAEMO=true; WITHGNOME=false; WITHA11Y=false; else WITHMAEMO=false; fi, WITHMAEMO=false) AC_ARG_WITH([maemo-fullscreen], AS_HELP_STRING([--with-maemo-fullscreen],[build as standalone Maemo fullscreen app (default is NO)]), if test "x$withval" = "xyes"; then WITHMAEMOFULLSCREEN=true; WITHMAEMO=true; WITHGNOME=false; WITHA11Y=false; else WITHMAEMOFULLSCREEN=false; fi, WITHMAEMOFULLSCREEN=false) dnl AC_ARG_WITH([darwin], dnl AS_HELP_STRING([--with-darwin],[build with Darwin (Mac OS X) support (default is NO)]), dnl if test "x$withval" = "xyes"; then dnl WITHDARWIN=true; dnl else dnl WITHDARWIN=false; dnl fi, dnl WITHDARWIN=false) AC_ARG_WITH([cairo], AS_HELP_STRING([--with-cairo],[build with cairo support (default is YES)]), if test "x$withval" = "xno"; then WITHCAIRO=false; else WITHCAIRO=true; fi, WITHCAIRO=true) if test x"$WITHGTK2" = xtrue then PKG_CHECK_MODULES(GTK2, gtk+-2.0 >= 2.6.0,[GTK2HERE=true],[GTK2HERE=false]) fi if test x"$GTK2HERE" = xtrue -a x"$WITHGTK2" = xtrue -a x"$WITHQTE" != xtrue then BUILDGTK2=true elif test x"$GTK2HERE" = xtrue -a x"$WITHQTE" != xtrue then BUILDGTK2=true else BUILDGTK2=false fi DAM_GCONF_SOURCE_2 if test x$BUILDGTK2 = xtrue then PKG_CHECK_MODULES(GCONF, gconf-2.0, [AC_DEFINE([WITH_GCONF], 1, [Use GConf])], [AC_MSG_WARN([GConf was not detected - user preferences will not be stored.])]) save_CFLAGS="$CFLAGS" save_LIBS="$LIBS" CFLAGS="$CFLAGS $GTK2_CFLAGS" LIBS="$LIBS $GTK2_LIBS" AC_CHECK_FUNCS([gtk_builder_new gtk_show_uri], [], [if test "x$ac_cv_func_gtk_builder_new" = "xno"; then AC_MSG_ERROR([A version of GTK+ providing GtkBuilder is necessary.]) fi if test "x$ac_cv_func_gtk_show_uri" = "xno"; then AC_MSG_WARN([This version of GTK+ doesn't provide gtk_show_uri - help will not be displayed from within dasher.]) fi] ) CFLAGS="$save_CFLAGS" LIBS="$save_LIBS" # GtkBuilder's autoconnect feature requires dasher to be linked with # the --export-dynamic flag. pkg-config does not provide it, and libtool # knows what to do with -export-dynamic. # (We need this e.g., for <object class="DasherEditor">) GTK2_LIBS="$GTK2_LIBS -export-dynamic" else AC_MSG_ERROR("Unable to find GTK2 or another necessary library.") fi if test x"$DEBUG" = xtrue; then AC_DEFINE([DEBUG], 1, [Additional debug checks enabled]) fi if test x"$WITHSPEECH" = xtrue; then PKG_CHECK_MODULES(gnome_speech, gnome-speech-1.0 bonobo-activation-2.0 libbonobo-2.0 ORBit-2.0) AC_DEFINE([GNOME_SPEECH], 1, [gnome_speech-1 libraries are present]) # SPEECH_SOURCES='speech.$(OBJEXT)' fi if test x"$WITHA11Y" = xtrue; then PKG_CHECK_MODULES(gnome_a11y, bonobo-activation-2.0 libbonobo-2.0 ORBit-2.0 libgnomeui-2.0 cspi-1.0 atk) AC_DEFINE([GNOME_A11Y], 1, [gnome_a11y libraries are present]) fi AC_PATH_XTRA AC_CHECK_LIB(expat, XML_Parse,,[ if test x$no_x = xyes ; then AC_MSG_ERROR([Expat library not found.]) else CPPFLAGS="$CPPFLAGS $X_CFLAGS" LDFLAGS="$LDFLAGS $X_LIBS" dnl Check for different function to avoid cached "no" result. AC_CHECK_LIB(expat, XML_SetElementHandler,, [AC_MSG_ERROR([Expat library not found.])]) fi ]) if test x"$WITHQTE" != xtrue -a x"$WITHA11Y" != xtrue; then if test x$no_x = xyes ; then AC_MSG_ERROR([X development libraries not found]) else X_LIBS="$X_LIBS $X_PRE_LIBS -lX11 $X_EXTRA_LIBS" fi save_LIBS="$LIBS" AC_CHECK_LIB([Xtst], [XTestFakeKeyEvent], [X_LIBS="$X_LIBS -lXtst" AC_DEFINE(HAVE_XTST, 1, [The XTest extension is present])], [AC_MSG_ERROR([Couldn't find the Xtst library. Check config.log for details])], $X_LIBS) LIBS="$save_LIBS" AC_SUBST(X_LIBS) fi if test x"$WITHJAPANESE" = xtrue; then AC_DEFINE([JAPANESE], 1, [Japanese support enabled]) JAPANESE_SOURCES='CannaConversionHelper.$(OBJEXT)' else JAPANESE_SOURCES= fi AC_SUBST(JAPANESE_SOURCES) if test x"$WITHJOYSTICK" = xtrue; then AC_DEFINE([JOYSTICK], 1, [Linux joystick support enabled]) fi if test x"$WITHTILT" = xtrue; then AC_DEFINE([TILT], 1, [Tilt input support enabled]) fi if test x"$WITHGPE" = xtrue; then AC_DEFINE([WITH_GPE], 1, [gpe is present]) fi dnl if test x"$WITHDARWIN" = xtrue ; then dnl AC_DEFINE([WITH_DARWIN], 1, [Targeting Darwin/X11]) dnl fi if test x"$WITHMAEMO" = xtrue; then AC_DEFINE([WITH_MAEMO], 1, [Maemo is present]) PKG_CHECK_MODULES(hildon, hildon-libs) AC_CHECK_LIB(osso, osso_initialize,, AC_MSG_ERROR([Osso library not found.])) fi if test x"$WITHMAEMOFULLSCREEN" = xtrue; then AC_DEFINE([WITH_MAEMOFULLSCREEN], 1, [Building as fullscreen Maemo app]) fi if test x"$WITHCAIRO" = xtrue; then PKG_CHECK_MODULES(cairo, gtk+-2.0 >= 2.8.0) AC_DEFINE([WITH_CAIRO], 1, [use cairo (needs Gtk+ >= 2.8.0)]) fi if test x"$BUILDGTK2" = xtrue; then PKG_CHECK_MODULES(gthread, gthread-2.0) fi AC_SUBST(gnome_speech_LIBS) AC_SUBST(gnome_speech_CFLAGS) AC_SUBST([SPEECH_SOURCES]) AC_SUBST(gnome_a11y_LIBS) AC_SUBST(gnome_a11y_CFLAGS) AC_SUBST([A11Y_SOURCES]) AC_SUBST(gnome_LIBS) AC_SUBST(gnome_CFLAGS) AC_SUBST(gthread_LIBS) AC_SUBST(gthread_CFLAGS) AC_SUBST(hildon_LIBS) AC_SUBST(hildon_CFLAGS) AC_SUBST(GETTEXT_PACKAGE) AM_CONDITIONAL(DOGTK2, test x$BUILDGTK2 = xtrue) AM_CONDITIONAL(DOQTE, test x$WITHQTE = xtrue) AM_CONDITIONAL(GNOME_SPEECH, test x$WITHSPEECH = xtrue) AM_CONDITIONAL(GNOME_A11Y, test x$WITHA11Y = xtrue) AM_CONDITIONAL(GNOME_HELP, test x$WITHGNOME = xtrue) AM_CONDITIONAL(WITH_GPE, test x$WITHGPE = xtrue) AM_CONDITIONAL(WITH_MAEMO, test x$WITHMAEMO = xtrue) AM_CONDITIONAL(WITH_MAEMOFULLSCREEN, test x$WITHMAEMOFULLSCREEN = xtrue) AM_CONDITIONAL(JAPANESE, test x$WITHJAPANESE = xtrue) AM_CONDITIONAL(JOYSTICK, test x$WITHJOYSTICK = xtrue) AC_SUBST(GTK2_CFLAGS) AC_SUBST(GTK2_LIBS) AC_SUBST(GCONF_CFLAGS) AC_SUBST(GCONF_LIBS) if test x"$WITHGPE" = xtrue ; then SETTINGS_CFLAGS=" " SETTINGS_LIBS="-lgpewidget -lXsettings-client -lXsettings" else SETTINGS_CFLAGS=$GCONF_CFLAGS SETTINGS_LIBS=$GCONF_LIBS fi AC_SUBST(SETTINGS_CFLAGS) AC_SUBST(SETTINGS_LIBS) GTK2BUILD_CFLAGS="$GTK2_CFLAGS $GIO_CFLAGS $SETTINGS_CFLAGS $gthread_CFLAGS $gnome_speech_CFLAGS $gnome_a11y_CFLAGS $gnome_CFLAGS $hildon_CFLAGS" GTK2BUILD_LIBS="$X_LIBS $GTK2_LIBS $GIO_LIBS $SETTINGS_LIBS $gthread_LIBS $gnome_speech_LIBS $gnome_a11y_LIBS $gnome_LIBS $hildon_LIBS" AC_SUBST(GTK2BUILD_CFLAGS) AC_SUBST(GTK2BUILD_LIBS) AC_MSG_CHECKING([for gnome-doc-utils]) dnl Avoid default action which is to complain if not found GNOME_DOC_INIT([0.9.0],[gdu_cv_have_gdu=yes],[gdu_cv_have_gdu=no]) AC_MSG_RESULT($gdu_cv_have_gdu) if test x"$WITHGNOME" = xtrue -a x"$gdu_cv_have_gdu" = xno ; then AC_MSG_ERROR([gnome-doc-utils not found!]) fi dnl XXX PRLW How is this better than the standard dnl gdu_cv_have_gdu && enable_scrollkeeper ? AM_CONDITIONAL(ENABLE_SK, test x"$WITHGNOME" = xfalse -a x"$enable_scrollkeeper" = "xyes") AC_CONFIG_FILES([Data/dasher.desktop.in Data/Makefile Data/training/Makefile Data/alphabets/Makefile Data/colours/Makefile Data/controllabels/Makefile + Data/gamemode/Makefile Data/GUI/Makefile Data/Help/Makefile Data/Help/Gnome/Makefile Doc/Makefile Doc/user/Makefile Makefile Src/Makefile Src/Common/Makefile Src/DasherCore/Makefile Src/DasherCore/LanguageModelling/Makefile Src/DasherIM/Makefile Src/Gtk2/Makefile Src/Installer/Makefile Src/InstallerTobii/Makefile Src/InstallerW2K/Makefile Src/Win32/Makefile po/Makefile.in ]) AC_OUTPUT
rgee/HFOSS-Dasher
2761c68066702c278f0525b965fb68472039c58f
Forgot the add anything before committing. Tend to do that a lot.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 0cb8253..2f1b3ef 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1183 +1,1190 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <tr1/memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; m_pGameDisplay = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); InitGameModule(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); case BP_GAME_MODE: if(GetBoolParameter(BP_GAME_MODE)) { InitGameModule(); } else if(m_pGameModule){ ResetGameModule(); } default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } + else if(pEvent->m_iEventType == EV_GAME_MODE_COMPLETE) { + SetBoolParameter(BP_GAME_MODE, false); + Pause(); + } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule && GetBoolParameter(BP_GAME_MODE)) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } /** * Reset the dasher model, fetch the game module from the module manager, * set its word generator, and make it available via m_pGameModule. */ void CDasherInterfaceBase::InitGameModule() { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); if(GetBoolParameter(BP_GAME_MODE)) { //CreateModel(0); m_pGameModule->SetWordGenerator(new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE))); } } /** * Reset the game module, reset the dasher model, and set m_pGameModule to NULL. */ void CDasherInterfaceBase::ResetGameModule() { - m_pGameModule->reset(); - CreateModel(0); - m_pGameModule = NULL; + + if(m_pGameModule) { + m_pGameModule->reset(); + CreateModel(0); + m_pGameModule = NULL; + } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/GameDisplay.h b/Src/DasherCore/GameDisplay.h index 342c31a..6ef87b6 100644 --- a/Src/DasherCore/GameDisplay.h +++ b/Src/DasherCore/GameDisplay.h @@ -1,37 +1,48 @@ #ifndef _GameDisplay_H_ #define _GameDisplay_H_ #include <vector> #include <string> using namespace std; namespace Dasher { /** * A class which allows GameModule to display formatted * information in a separate area on the screen. Currently, * the only information it can display is a color coded * representation of the current text chunk (see DispayChunkText). * There is a lot of room for extending this to support new features, * different types of games, etc. */ class CGameDisplay { public: CGameDisplay() {} /** TODO: Improve this documentation * Display a colored sequence of characters in the game display window. * @param text the sequence of characters * @param colors the color to give each index of text */ virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors) = 0; + + /** + * Hide the display and clear the text in the label. + */ + virtual void hide() = 0; + + /** + * Display a dialog alerting the user about something + * related to game mode. + */ + virtual void alert(std::string message) = 0; }; } #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 8084b34..ce33f65 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,203 +1,215 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, }; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); } case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; DecorateDisplay(); m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { - delete m_pWordGenerator; + m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; + + if(m_pGameDisplay) + m_pGameDisplay->hide(); + + if(m_pWordGenerator) + delete m_pWordGenerator; + } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); std::string nextWord; for(int i = 0; i < m_iTargetChunkSize; i++) { nextWord = m_pWordGenerator->GetNextWord(); - if(nextWord == "") { + + //done with game text + if(nextWord == "") { + m_sTargetString = ""; + m_pGameDisplay->alert("Congratulations! You've completed Dasher game mode!"); m_pEventHandler->InsertEvent(new CGameModeCompleteEvent()); + return; } else { m_sTargetString += nextWord; m_sTargetString += " "; } } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); DecorateDisplay(); } void CGameModule::DecorateDisplay() { if(m_pGameDisplay == NULL) return; std::vector<std::string> colors = std::vector<std::string>(); for(int pos = 0; pos < m_sTargetString.length(); pos++) { if(pos < m_iCurrentStringPos + 1) { colors.push_back("blue"); } else if(pos == m_iCurrentStringPos + 1) { colors.push_back("red"); } else { colors.push_back("black"); } } m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { m_pGameDisplay = pGameDisplay; } diff --git a/Src/Gtk2/GtkGameDisplay.cpp b/Src/Gtk2/GtkGameDisplay.cpp index e5bd0b9..9a54011 100644 --- a/Src/Gtk2/GtkGameDisplay.cpp +++ b/Src/Gtk2/GtkGameDisplay.cpp @@ -1,16 +1,35 @@ #include "GtkGameDisplay.h" using namespace std; void GtkGameDisplay::DisplayChunkText(std::string text, std::vector<std::string>& colors) { std::string markup = "<span font-weight = \"bold\" font_size = \"xx-large\">"; for(int pos = 0; pos < text.length(); pos++) { markup += "<span foreground = \""+ colors[pos]+"\">"+text.substr(pos, 1)+"</span>"; } markup += "</span>"; gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), markup.c_str()); } + +void GtkGameDisplay::hide() { + + gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), ""); + gtk_widget_set_visible(GTK_WIDGET(m_pContainer), false); +} + +void GtkGameDisplay::alert(std::string message) { + + GtkWidget *dialog = gtk_message_dialog_new(NULL, + GTK_DIALOG_MODAL, + GTK_MESSAGE_OTHER, + GTK_BUTTONS_OK, + message.c_str() + ); + + gtk_dialog_run(GTK_DIALOG(dialog)); + gtk_widget_destroy(GTK_WIDGET(dialog)); +} diff --git a/Src/Gtk2/GtkGameDisplay.h b/Src/Gtk2/GtkGameDisplay.h index 7865d7e..f2bb6ef 100644 --- a/Src/Gtk2/GtkGameDisplay.h +++ b/Src/Gtk2/GtkGameDisplay.h @@ -1,36 +1,39 @@ #include "../DasherCore/GameDisplay.h" #include <gtk/gtk.h> #include <string> #include <cstring> class GtkGameDisplay : public Dasher::CGameDisplay { public: /** * @param pContainer - the table that all of the * widgets for the game display live in */ GtkGameDisplay(GtkWidget *pContainer) : Dasher::CGameDisplay(), m_pContainer(pContainer) { m_pChunkDisplay = gtk_label_new(NULL); gtk_container_add(GTK_CONTAINER(m_pContainer), m_pChunkDisplay); - //gtk_misc_set_alignment(GTK_MISC(m_pChunkDisplay), 0, .5); gtk_widget_set_visible(m_pChunkDisplay, true); } virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors); + virtual void hide(); + + virtual void alert(std::string message); + private: /** * The Gtk table containing the game mode UI. */ GtkWidget *m_pContainer; GtkWidget *m_pChunkDisplay; };
rgee/HFOSS-Dasher
ca77d8657f9aefbb719cfd8984afe707d3169677
Added enum to events to maintain the number of them in a reasonable place.
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 21f1789..52d0154 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,228 +1,228 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; class CNoGameNodeEvent; class CGameModeCompleteEvent; } /* * The enumeration of event types. Whenever you add a new event type, * you must add its enum representation here. You must also make sure * to change the constant in EventHandler that refers to the number of events * or you will likely get errors. */ enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, - EV_GAME_MODE_COMPLETE + EV_GAME_MODE_COMPLETE, NUM_EVENTS = 13 }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; /** * This is an event to signal that the user has finished typing the game mode * target. Appropriate action should be taken by visual components to * congratulate them in response to this evt. */ class Dasher::CGameModeCompleteEvent : public Dasher::CEvent { public: CGameModeCompleteEvent() { m_iEventType = EV_GAME_MODE_COMPLETE; } }; /** An event that represents when the game target node cannot be found * among the current last-typed node's children. Since the set of child * nodes is a set consisting of all possible characters in the current * alphabet, the only way for it not to exist at all is if it was not * drawn yet. */ class Dasher::CNoGameNodeEvent : public Dasher::CEvent { public: CNoGameNodeEvent(std::pair<CDasherNode*, CDasherNode*> pNodes) : m_pNodes(pNodes) { m_iEventType = EV_NO_GAME_NODE; } /** * The pair of nodes that represent the closest drawn nodes to the top * and bottom of where the target node /should/ be. * * If the left of this pair is null, the target node is at the top-most * node in the current subtree of the model (in Dasher space). * * Conversely, if the right of this pair is null, the target node exists * at the bottom of the current subtree of the model. */ std::pair<CDasherNode*, CDasherNode*> m_pNodes; }; /** * An event that notifies listeners that a node previously flagged for * game mode has been drawn. */ class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; /** * The node itself. */ CDasherNode* m_pNode; /** * the coordinates at which m_pNode was drawn. */ screenint m_iX, m_iY; /** * View object for manipulating the screen. */ CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 4b6ef71..5d49b2f 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,167 +1,167 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ /** * This class handles the dispatch and management of events throughout Dasher. * Any class that derives from CDasherComponent can subscribe to events. These * events are enumerated in Event.h. All CDasherComponents are automatically * registered for their selected events on construction. * * Components SHOULD specify exactly which events they're interested in * instead of omitting this information. This allows the event management * system to make optimal use of time in dispatching events. (i.e. cuts * down on unused event dispatching) */ class Dasher::CEventHandler { public: - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(12), m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(NUM_EVENTS), m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. * * @warning If this is called from an Event Handler, (i.e. While events * are being processed) the event is enqueued to be dispatched * and NOT immediately dispatched. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for all events. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; /** * Dispatch all the events in the event queue, and take * care of all the pending additions/deletions to m_vSpecificListeners * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and * m_vPendSpecificUnreg */ void ProcessEventQueue(); /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif
rgee/HFOSS-Dasher
2e2477ae8ffd0228389f341f254e4dbdcba48746
Game module now signals with an event when the user has completed the target.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index a7bf737..0cb8253 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,790 +1,784 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <tr1/memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; m_pGameDisplay = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); - - g_pLogger->Log(m_pGameDisplay == NULL ? "null in ibase" : "not null in ibase"); - CreateInput(); CreateInputFilter(); SetupActionButtons(); InitGameModule(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { - - g_pLogger->Log(m_pGameDisplay == NULL ? "NULL" : "NOT NULL"); - if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); case BP_GAME_MODE: if(GetBoolParameter(BP_GAME_MODE)) { InitGameModule(); } else if(m_pGameModule){ ResetGameModule(); } default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule && GetBoolParameter(BP_GAME_MODE)) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 79e6907..21f1789 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,214 +1,228 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; class CNoGameNodeEvent; + class CGameModeCompleteEvent; } /* * The enumeration of event types. Whenever you add a new event type, * you must add its enum representation here. You must also make sure * to change the constant in EventHandler that refers to the number of events * or you will likely get errors. */ enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, + EV_GAME_MODE_COMPLETE }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; - /* An event that represents when the game target node cannot be found +/** + * This is an event to signal that the user has finished typing the game mode + * target. Appropriate action should be taken by visual components to + * congratulate them in response to this evt. + */ +class Dasher::CGameModeCompleteEvent : public Dasher::CEvent { +public: + CGameModeCompleteEvent() { + m_iEventType = EV_GAME_MODE_COMPLETE; + } +}; + + /** An event that represents when the game target node cannot be found * among the current last-typed node's children. Since the set of child * nodes is a set consisting of all possible characters in the current * alphabet, the only way for it not to exist at all is if it was not * drawn yet. */ class Dasher::CNoGameNodeEvent : public Dasher::CEvent { public: CNoGameNodeEvent(std::pair<CDasherNode*, CDasherNode*> pNodes) : m_pNodes(pNodes) { m_iEventType = EV_NO_GAME_NODE; } /** * The pair of nodes that represent the closest drawn nodes to the top * and bottom of where the target node /should/ be. * * If the left of this pair is null, the target node is at the top-most * node in the current subtree of the model (in Dasher space). * * Conversely, if the right of this pair is null, the target node exists * at the bottom of the current subtree of the model. */ std::pair<CDasherNode*, CDasherNode*> m_pNodes; }; /** * An event that notifies listeners that a node previously flagged for * game mode has been drawn. */ class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; /** * The node itself. */ CDasherNode* m_pNode; /** * the coordinates at which m_pNode was drawn. */ screenint m_iX, m_iY; /** * View object for manipulating the screen. */ CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 2ab3d36..8d54d79 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,56 +1,58 @@ #include "FileWordGenerator.h" - +#include "DasherInterfaceBase.h" using namespace Dasher; bool CFileWordGenerator::Generate() { if(!m_sFileHandle.is_open()) { m_sFileHandle.open(m_sPath.c_str()); } if(m_sFileHandle.fail()) { throw std::runtime_error("File: " + m_sPath + " cannot be read."); } m_uiPos = 0; m_sGeneratedString.clear(); if(m_sFileHandle.eof()) { return false; } else if(m_sFileHandle.good()) { std::getline(m_sFileHandle, m_sGeneratedString); return true; } else { return false; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")+1); } std::string CFileWordGenerator::GetNextWord() { - if(m_uiPos >= m_sGeneratedString.length()) { + if(m_uiPos >= m_sGeneratedString.length()) { + // Attempt to reload the buffer. if(!Generate()) return ""; } size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); std::string result; // If there are no space characters. if(found != string::npos) { result = m_sGeneratedString.substr(m_uiPos, found); m_uiPos += (found + 1); } else { result = m_sGeneratedString.substr(m_uiPos); + m_uiPos = m_sGeneratedString.length(); }; return result; } diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 0bc6642..ee3923a 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,203 +1,200 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, }; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { - g_pLogger->Log(m_pGameDisplay == NULL ? "NULL" : "NOT NULL"); switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); - std::stringstream log_stream; - log_stream << "First: " << evt->m_pNodes.first << "Second: " << evt->m_pNodes.first << endl; - g_pLogger->Log(log_stream.str()); } case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; DecorateDisplay(); m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); - - g_pLogger->Log(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); - } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { delete m_pWordGenerator; m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); - //pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); - //pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { - return ((m_iCurrentStringPos == -1) ? - "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); + return ((m_iCurrentStringPos == -1) ? + "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); + + std::string nextWord; + for(int i = 0; i < m_iTargetChunkSize; i++) { - m_sTargetString += m_pWordGenerator->GetNextWord(); - m_sTargetString += " "; + nextWord = m_pWordGenerator->GetNextWord(); + if(nextWord == "") { + m_sTargetString = ""; + m_pEventHandler->InsertEvent(new CGameModeCompleteEvent()); + return; + } else { + m_sTargetString += nextWord; + m_sTargetString += " "; + } } m_pEventHandler->InsertEvent( - new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) - ); + new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) + ); DecorateDisplay(); - g_pLogger->Log(m_sTargetString); } void CGameModule::DecorateDisplay() { - - //if(m_pGameDisplay == NULL) return; - - std::vector<std::string> *colors = new std::vector<std::string>(); - - for(int pos = 0; pos < m_sTargetString.length(); pos++) { - - if(pos < m_iCurrentStringPos + 1) { - colors->push_back("blue"); - } - else if(pos == m_iCurrentStringPos + 1) { - colors->push_back("red"); - } - else { - colors->push_back("black"); - } - } - - m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); + std::vector<std::string> *colors = new std::vector<std::string>(); + + for(int pos = 0; pos < m_sTargetString.length(); pos++) { + + if(pos < m_iCurrentStringPos + 1) { + colors->push_back("blue"); + } + else if(pos == m_iCurrentStringPos + 1) { + colors->push_back("red"); + } + else { + colors->push_back("black"); + } + } + + m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { - m_pGameDisplay = pGameDisplay; + m_pGameDisplay = pGameDisplay; }
rgee/HFOSS-Dasher
751f135b9ecc8dca789f4128e0efd4a197724f45
Fixed both 1 off errors, but unwittingly introduced ridiculous, inexplicable problems with the file chooser. I'm ecstatic and baffled at the same time.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index e050421..a7bf737 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1189 +1,1189 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <tr1/memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; m_pGameDisplay = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); + g_pLogger->Log(m_pGameDisplay == NULL ? "null in ibase" : "not null in ibase"); + CreateInput(); CreateInputFilter(); SetupActionButtons(); - - if(GetBoolParameter(BP_GAME_MODE)) - InitGameModule(); - + InitGameModule(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { + g_pLogger->Log(m_pGameDisplay == NULL ? "NULL" : "NOT NULL"); + if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); case BP_GAME_MODE: if(GetBoolParameter(BP_GAME_MODE)) { InitGameModule(); } else if(m_pGameModule){ ResetGameModule(); } default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } - if(m_pGameModule) { + if(m_pGameModule && GetBoolParameter(BP_GAME_MODE)) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } /** * Reset the dasher model, fetch the game module from the module manager, * set its word generator, and make it available via m_pGameModule. */ void CDasherInterfaceBase::InitGameModule() { - if(m_pGameModule == NULL) { - CreateModel(0); - m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); - m_pGameModule->SetWordGenerator(new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE))); - m_pGameModule->SetGameDisplay(m_pGameDisplay); + m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); - } + if(GetBoolParameter(BP_GAME_MODE)) { + //CreateModel(0); + m_pGameModule->SetWordGenerator(new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE))); + } } /** * Reset the game module, reset the dasher model, and set m_pGameModule to NULL. */ void CDasherInterfaceBase::ResetGameModule() { m_pGameModule->reset(); CreateModel(0); m_pGameModule = NULL; } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherInterfaceBase.h b/Src/DasherCore/DasherInterfaceBase.h index ec099cc..1dc9f0d 100644 --- a/Src/DasherCore/DasherInterfaceBase.h +++ b/Src/DasherCore/DasherInterfaceBase.h @@ -1,607 +1,607 @@ // DasherInterfaceBase.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherInterfaceBase_h__ #define __DasherInterfaceBase_h__ /// /// \mainpage /// /// This is the Dasher source code documentation. Please try to keep /// it up to date! /// // TODO - there is a list of things to be configurable in my notes // Check that everything that is not self-contained within the GUI is covered. #include "../Common/NoClones.h" #include "../Common/ModuleSettings.h" #include "ActionButton.h" #include "Alphabet/Alphabet.h" #include "Alphabet/AlphIO.h" #include "AutoSpeedControl.h" #include "ColourIO.h" #include "InputFilter.h" #include "ModuleManager.h" #include "GameModule.h" #include "GameDisplay.h" #include <map> #include <algorithm> namespace Dasher { class CDasherScreen; class CDasherView; class CDasherInput; class CDasherModel; class CEventHandler; class CEvent; class CGameModule; class CDasherInterfaceBase; } class CSettingsStore; class CUserLogBase; class CNodeCreationManager; /// \defgroup Core Core Dasher classes /// @{ struct Dasher::SLockData { std::string strDisplay; int iPercent; }; /// The central class in the core of Dasher. Ties together the rest of /// the platform independent stuff and provides a single interface for /// the UI to use. class Dasher::CDasherInterfaceBase:private NoClones { public: CDasherInterfaceBase(); virtual ~CDasherInterfaceBase(); /// @name Access to internal member classes /// Access various classes contained within the interface. These /// should be considered dangerous and use minimised. Eventually to /// be replaced by properly encapsulated equivalents. /// @{ /// /// Return a pointer to the current EventHandler (the one /// which the CSettingsStore is using to notify parameter /// changes) /// virtual CEventHandler *GetEventHandler() { return m_pEventHandler; }; /// /// \deprecated In situ alphabet editing is no longer supported /// \todo Document this /// const CAlphIO::AlphInfo & GetInfo(const std::string & AlphID); /// \todo Document this void SetInfo(const CAlphIO::AlphInfo & NewInfo); /// \todo Document this void DeleteAlphabet(const std::string & AlphID); /// Get a pointer to the current alphabet object CAlphabet *GetAlphabet() { return m_Alphabet; } /// Gets a pointer to the object doing user logging CUserLogBase* GetUserLogPtr(); // @} /// /// @name Parameter manipulation /// Members for manipulating the parameters of the core Dasher object. /// //@{ /// /// Set a boolean parameter. /// \param iParameter The parameter to set. /// \param bValue The new value. /// void SetBoolParameter(int iParameter, bool bValue); /// /// Set a long integer parameter. /// \param iParameter The parameter to set. /// \param lValue The new value. /// void SetLongParameter(int iParameter, long lValue); /// /// Set a string parameter. /// \param iParameter The parameter to set. /// \param sValue The new value. /// void SetStringParameter(int iParameter, const std::string & sValue); /// Get a boolean parameter /// \param iParameter The parameter to get. /// \retval The current value. bool GetBoolParameter(int iParameter); /// Get a long integer parameter /// \param iParameter The parameter to get. /// \retval The current value. long GetLongParameter(int iParameter); /// Get a string parameter /// \param iParameter The parameter to get. /// \retval The current value. std::string GetStringParameter(int iParameter); /// /// Reset a parameter to the default value /// void ResetParameter(int iParmater); /// /// Obtain the permitted values for a string parameter - used to /// geneate preferences dialogues etc. /// void GetPermittedValues(int iParameter, std::vector<std::string> &vList); /// /// Get a list of settings which apply to a particular module /// bool GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount); //@} /// Forward events to listeners in the SettingsUI and Editbox. /// \param pEvent The event to forward. /// \todo Should be protected. virtual void ExternalEventHandler(Dasher::CEvent * pEvent) {}; /// Interface level event handler. For example, responsible for /// restarting the Dasher model whenever parameter changes make it /// invalid. /// \param pEvent The event. /// \todo Should be protected. void InterfaceEventHandler(Dasher::CEvent * pEvent); void PreSetNotify(int iParameter, const std::string &sValue); /// @name Starting and stopping /// Methods used to instruct dynamic motion of Dasher to start or stop /// @{ /// Resets the Dasher model. Doesn't actually unpause Dasher. /// \deprecated Use InvalidateContext() instead // void Start(); /// Pause Dasher. Sets BP_DASHER_PAUSED and broadcasts a StopEvent. /// (But does nothing if BP_DASHER_PAUSED is not set) void Pause(); // are required to make /// Unpause Dasher. Clears BP_DASHER_PAUSED, broadcasts a StartEvent. /// (But does nothing if BP_DASHER_PAUSED is currently set). /// \param Time Time in ms, used to keep a constant frame rate void Unpause(unsigned long Time); // Dasher run at the /// @} // App Interface // ----------------------------------------------------- // std::map<int, std::string>& GetAlphabets(); // map<key, value> int is a UID string can change. Store UID in preferences. Display string to user. // std::vector<std::string>& GetAlphabets(); // std::vector<std::string>& GetLangModels(); // std::vector<std::string>& GetViews(); /// Supply a new CDasherScreen object to do the rendering. /// \param NewScreen Pointer to the new CDasherScreen. void ChangeScreen(CDasherScreen * NewScreen); // We may change the widgets Dasher uses /// Train Dasher from a file /// All traing data must be in UTF-8 /// \param Filename File to load. /// \param iTotalBytes documentme /// \param iOffset Document me // int TrainFile(std::string Filename, int iTotalBytes, int iOffset); /// Set the context in which Dasher makes predictions /// \param strNewContext The new context (UTF-8) void SetContext(std::string strNewContext); /// New control mechanisms: void SetBuffer(int iOffset); void UnsetBuffer(); void SetOffset(int iOffset); /// @name Status reporting /// Get information about the runtime status of Dasher which might /// be of interest for debugging purposes etc. /// @{ /// Get the current rate of text entry. /// \retval The rate in characters per minute. /// TODO: Check that this is still used double GetCurCPM(); /// Get current refresh rate. /// \retval The rate in frames per second /// TODO: Check that this is still used double GetCurFPS(); /// Get the total number of nats (base-e bits) entered. /// \retval The current total /// \todo Obsolete since new logging code? double GetNats() const; /// Reset the count of nats entered. /// \todo Obsolete since new logging code? void ResetNats(); double GetFramerate(); /// @} /// @name Control hierarchy and action buttons /// Manipulate the hierarchy of commands presented in control mode etc /// @{ void RegisterNode( int iID, const std::string &strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); void ExecuteCommand(const std::string &strName); void AddActionButton(const std::string &strName); /// @} /// @name User input /// Deals with forwarding user input to the core /// @{ void KeyDown(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void KeyUp(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void HandleClickUp(int iTime, int iX, int iY); void HandleClickDown(int iTime, int iX, int iY); /// @} // Module management functions CDasherModule *RegisterModule(CDasherModule *pModule); CDasherModule *GetModule(ModuleID_t iID); CDasherModule *GetModuleByName(const std::string &strName); CDasherModule *GetDefaultInputDevice(); CDasherModule *GetDefaultInputMethod(); void SetDefaultInputDevice(CDasherModule *); void SetDefaultInputMethod(CDasherModule *); void StartShutdown(); void AddGameModeString(const std::string &strText) { m_deGameModeStrings.push_back(strText); Pause(); // CreateDasherModel(); CreateNCManager(); // Start(); }; void GameMessageIn(int message, void* messagedata); virtual void GameMessageOut(int message, const void* messagedata) {} void ScheduleRedraw() { m_bRedrawScheduled = true; }; std::string GetContext(int iStart, int iLength); void SetControlOffset(int iOffset); /// Set a key value pair by name - designed to allow operation from /// the command line. Returns 0 on success, an error string on failure. /// const char* ClSet(const std::string &strKey, const std::string &strValue); void ImportTrainingText(const std::string &strPath); protected: /// @name Startup /// Interaction with the derived class during core startup /// @{ /// /// Allocate resources, create alphabets etc. This is a separate /// routine to the constructor to give us a chance to set up /// parameters before things are created. /// void Realize(); /// /// Notify the core that the UI has been realised. At this point drawing etc. is expected to work /// void OnUIRealised(); /// /// Creates a default set of modules. Override in subclasses to create any /// extra/different modules specific to the platform (eg input device drivers) /// virtual void CreateModules(); /// @} /// Draw a new Dasher frame, regardless of whether we're paused etc. /// \param iTime Current time in ms. /// \param bForceRedraw /// \todo See comments in cpp file for some functionality which needs to be re-implemented void NewFrame(unsigned long iTime, bool bForceRedraw); + /** + * Initialize m_pGameModule by fetching the + * constructed module from the module manager. + */ + void InitGameModule(); + enum ETransition { TR_MODEL_INIT = 0, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN, TR_NUM }; enum EState { ST_START = 0, ST_MODEL, ST_UI, ST_NORMAL, ST_LOCKED, ST_SHUTDOWN, ST_NUM, ST_FORBIDDEN, ST_DELAY }; /// @name State machine functions /// ... /// @{ void ChangeState(ETransition iTransition); /// @} CEventHandler *m_pEventHandler; CSettingsStore *m_pSettingsStore; /** * The display widget used by GameModule to display a helpful UI. * Insantiated by platform specific implementations of DasherIntefaceBase. */ CGameDisplay *m_pGameDisplay; + /** + * The game mode module - only + * initialized if game mode is enabled + */ + CGameModule *m_pGameModule; + private: //The default expansion policy to use - an amortized policy depending on the LP_NODE_BUDGET parameter. CExpansionPolicy *m_defaultPolicy; /// @name Platform dependent utility functions /// These functions provide various platform dependent functions /// required by the core. A derived class is created for each /// supported platform which implements these. // @{ /// /// Initialise the SP_SYSTEM_LOC and SP_USER_LOC paths - the exact /// method of doing this will be OS dependent /// virtual void SetupPaths() = 0; /// /// Produce a list of filenames for alphabet files /// virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList) = 0; /// /// Produce a list of filenames for colour files /// virtual void ScanColourFiles(std::vector<std::string> &vFileList) = 0; /// /// Set up the platform dependent UI for the widget (not the wider /// app). Note that the constructor of the derived class will /// probably want to return details of what was created - this will /// have to happen separately, but we'll need to be careful with the /// semantics. /// virtual void SetupUI() = 0; /// /// Create settings store object, which will be platform dependent /// TODO: Can this not be done just by selecting which settings /// store implementation to instantiate? /// virtual void CreateSettingsStore() = 0; /// /// Obtain the size in bytes of a file - the way to do this is /// dependent on the OS (TODO: Check this - any posix on Windows?) /// virtual int GetFileSize(const std::string &strFileName) = 0; /// /// Start the callback timer /// virtual void StartTimer() = 0; /// /// Shutdown the callback timer (permenantly - this is called once /// Dasher is committed to closing). /// virtual void ShutdownTimer() = 0; /// /// Append text to the training file - used to store state between /// sessions /// @todo Pass file path to the function rather than having implementations work it out themselves /// virtual void WriteTrainFile(const std::string &strNewText) { }; /// @} /// Provide a new CDasherInput input device object. void CreateInput(); - /** - * Initialize m_pGameModule by fetching the - * constructed module from the module manager. - */ - void InitGameModule(); - /** * Reset m_pGameModule - called when game mode is disabled. */ void ResetGameModule(); void CreateInputFilter(); void CreateModel(int iOffset); void CreateNCManager(); void ChangeAlphabet(); void ChangeColours(); void ChangeView(); void Redraw(bool bRedrawNodes, CExpansionPolicy &policy); void SetupActionButtons(); void DestroyActionButtons(); void PositionActionButtons(); bool DrawActionButtons(); void WriteTrainFileFull(); void WriteTrainFilePartial(); std::deque<std::string> m_deGameModeStrings; std::vector<CActionButton *> m_vLeftButtons; std::vector<CActionButton *> m_vRightButtons; /// @name Child components /// Various objects which are 'owned' by the core. /// @{ CAlphabet *m_Alphabet; CDasherModel *m_pDasherModel; CDasherScreen *m_DasherScreen; CDasherView *m_pDasherView; CDasherInput *m_pInput; CInputFilter* m_pInputFilter; CModuleManager m_oModuleManager; CAlphIO *m_AlphIO; CColourIO *m_ColourIO; CNodeCreationManager *m_pNCManager; - CUserLogBase *m_pUserLog; - - /** - * The game mode module - only - * initialized if game mode is enabled - */ - CGameModule *m_pGameModule; + CUserLogBase *m_pUserLog; /// @} std::string strTrainfileBuffer; std::string strCurrentContext; std::string m_strContext; /// @name State variables /// Represent the current overall state of the core /// @{ // bool m_bGlobalLock; // The big lock bool m_bRedrawScheduled; EState m_iCurrentState; bool m_bOldVisible; /// @} bool m_bLastChanged; }; /// @} #endif /* #ifndef __DasherInterfaceBase_h__ */ diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 778851c..0bc6642 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,209 +1,203 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ -const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE}; +const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE, }; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { - //std::stringstream ss; - //ss << m_iCurrentStringPos; - //g_pLogger->Log(ss.str()); - - //if(!m_bIsActive) - // return; + g_pLogger->Log(m_pGameDisplay == NULL ? "NULL" : "NOT NULL"); switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); std::stringstream log_stream; log_stream << "First: " << evt->m_pNodes.first << "Second: " << evt->m_pNodes.first << endl; g_pLogger->Log(log_stream.str()); } case EV_EDIT: { - DecorateDisplay(); - CEditEvent* evt = static_cast<CEditEvent*>(pEvent); + switch(evt->m_iEditType) { - - DecorateDisplay(); - // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; + + DecorateDisplay(); + m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); g_pLogger->Log(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { delete m_pWordGenerator; m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); //pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); //pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); DecorateDisplay(); g_pLogger->Log(m_sTargetString); } void CGameModule::DecorateDisplay() { - if(m_pGameDisplay == NULL) return; + //if(m_pGameDisplay == NULL) return; std::vector<std::string> *colors = new std::vector<std::string>(); for(int pos = 0; pos < m_sTargetString.length(); pos++) { if(pos < m_iCurrentStringPos + 1) { colors->push_back("blue"); } else if(pos == m_iCurrentStringPos + 1) { colors->push_back("red"); } else { colors->push_back("black"); } } m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { m_pGameDisplay = pGameDisplay; } diff --git a/Src/Gtk2/DasherControl.cpp b/Src/Gtk2/DasherControl.cpp index 40de89b..951ba87 100644 --- a/Src/Gtk2/DasherControl.cpp +++ b/Src/Gtk2/DasherControl.cpp @@ -1,631 +1,637 @@ #include "../Common/Common.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <iostream> #include "DasherControl.h" #include "Timer.h" #include "../DasherCore/Event.h" #include "../DasherCore/ModuleManager.h" #include "GtkGameDisplay.h" #include <fcntl.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <sys/stat.h> #include <unistd.h> using namespace std; // 'Private' methods (only used in this file) extern "C" gint key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data); extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data); extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data); extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData); extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data); static bool g_iTimeoutID = 0; // CDasherControl class definitions CDasherControl::CDasherControl(GtkVBox *pVBox, GtkDasherControl *pDasherControl) { m_pPangoCache = NULL; m_pScreen = NULL; m_pDasherControl = pDasherControl; m_pVBox = GTK_WIDGET(pVBox); Realize(); // m_pKeyboardHelper = new CKeyboardHelper(this); // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); } void CDasherControl::CreateModules() { + + g_message("Creating modules"); + CDasherInterfaceBase::CreateModules(); //create default set first // Create locally cached copies of the mouse input objects, as we // need to pass coordinates to them from the timer callback m_pMouseInput = (CDasherMouseInput *) RegisterModule(new CDasherMouseInput(m_pEventHandler, m_pSettingsStore)); SetDefaultInputDevice(m_pMouseInput); m_p1DMouseInput = (CDasher1DMouseInput *)RegisterModule(new CDasher1DMouseInput(m_pEventHandler, m_pSettingsStore)); RegisterModule(new CSocketInput(m_pEventHandler, m_pSettingsStore)); #ifdef JOYSTICK RegisterModule(new CDasherJoystickInput(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CDasherJoystickInputDiscrete(m_pEventHandler, m_pSettingsStore, this)); #endif #ifdef TILT RegisterModule(new CDasherTiltInput(m_pEventHandler, m_pSettingsStore, this)); #endif } void CDasherControl::SetupUI() { m_pCanvas = gtk_drawing_area_new(); #if GTK_CHECK_VERSION (2,18,0) gtk_widget_set_can_focus(m_pCanvas, TRUE); #else GTK_WIDGET_SET_FLAGS(m_pCanvas, GTK_CAN_FOCUS); #endif gtk_widget_set_double_buffered(m_pCanvas, FALSE); GtkWidget *pFrame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(pFrame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(pFrame), m_pCanvas); gtk_box_pack_start(GTK_BOX(m_pVBox), pFrame, TRUE, TRUE, 0); gtk_widget_show_all(GTK_WIDGET(m_pVBox)); // Connect callbacks - note that we need to implement the callbacks // as "C" style functions and pass this as user data so they can // call the object g_signal_connect(m_pCanvas, "button_press_event", G_CALLBACK(button_press_event), this); g_signal_connect(m_pCanvas, "button_release_event", G_CALLBACK(button_press_event), this); g_signal_connect_after(m_pCanvas, "realize", G_CALLBACK(realize_canvas), this); g_signal_connect(m_pCanvas, "configure_event", G_CALLBACK(canvas_configure_event), this); g_signal_connect(m_pCanvas, "destroy", G_CALLBACK(canvas_destroy_event), this); g_signal_connect(m_pCanvas, "key-release-event", G_CALLBACK(key_release_event), this); g_signal_connect(m_pCanvas, "key_press_event", G_CALLBACK(key_press_event), this); g_signal_connect(m_pCanvas, "focus_in_event", G_CALLBACK(canvas_focus_event), this); g_signal_connect(m_pCanvas, "expose_event", G_CALLBACK(canvas_expose_event), this); //g_signal_connect(m_pDasher) // Create the Pango cache // TODO: Use system defaults? if(GetStringParameter(SP_DASHER_FONT) == "") SetStringParameter(SP_DASHER_FONT, "Sans 10"); m_pPangoCache = new CPangoCache(GetStringParameter(SP_DASHER_FONT)); } void CDasherControl::SetupPaths() { char *home_dir; char *user_data_dir; const char *system_data_dir; home_dir = getenv("HOME"); user_data_dir = new char[strlen(home_dir) + 10]; sprintf(user_data_dir, "%s/.dasher/", home_dir); mkdir(user_data_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // PROGDATA is provided by the makefile system_data_dir = PROGDATA "/"; SetStringParameter(SP_SYSTEM_LOC, system_data_dir); SetStringParameter(SP_USER_LOC, user_data_dir); delete[] user_data_dir; } void CDasherControl::CreateGameDisplay(void* pGameDisplay) { + m_pGameDisplay = new GtkGameDisplay(GTK_WIDGET(pGameDisplay)); + InitGameModule(); + m_pGameModule->SetGameDisplay(m_pGameDisplay); } void CDasherControl::CreateSettingsStore() { m_pSettingsStore = new CGnomeSettingsStore(m_pEventHandler); } void CDasherControl::ScanAlphabetFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *alphabetglob; alphabetglob = g_pattern_spec_new("alphabet*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(alphabetglob); } void CDasherControl::ScanColourFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *colourglob; colourglob = g_pattern_spec_new("colour*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(colourglob); } CDasherControl::~CDasherControl() { if(m_pMouseInput) { m_pMouseInput = NULL; } if(m_p1DMouseInput) { m_p1DMouseInput = NULL; } if(m_pPangoCache) { delete m_pPangoCache; m_pPangoCache = NULL; } // if(m_pKeyboardHelper) { // delete m_pKeyboardHelper; // m_pKeyboardHelper = 0; // } } bool CDasherControl::FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent) { if((pEvent->type == GDK_FOCUS_CHANGE) && (pEvent->in)) { GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); gboolean *returnType; focusEvent->type = GDK_FOCUS_CHANGE; focusEvent->window = (GdkWindow *) m_pDasherControl; focusEvent->send_event = FALSE; focusEvent->in = TRUE; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "focus_in_event", GTK_WIDGET(m_pDasherControl), focusEvent, NULL, &returnType); } return true; } void CDasherControl::SetFocus() { gtk_widget_grab_focus(m_pCanvas); } void CDasherControl::GameMessageOut(int message, const void* messagedata) { gtk_dasher_control_game_messageout(m_pDasherControl, message, messagedata); } GArray *CDasherControl::GetAllowedValues(int iParameter) { // Glib version of the STL based core function GArray *pRetVal(g_array_new(false, false, sizeof(gchar *))); std::vector < std::string > vList; GetPermittedValues(iParameter, vList); for(std::vector < std::string >::iterator it(vList.begin()); it != vList.end(); ++it) { // For internal glib reasons we need to make a variable and then // pass - we can't use the iterator directly const char *pTemp(it->c_str()); char *pTempNew = new char[strlen(pTemp) + 1]; strcpy(pTempNew, pTemp); g_array_append_val(pRetVal, pTempNew); } return pRetVal; } void CDasherControl::RealizeCanvas(GtkWidget *pWidget) { // TODO: Pointless function - call directly from C callback. #ifdef DEBUG std::cout << "RealizeCanvas()" << std::endl; #endif OnUIRealised(); } void CDasherControl::StartTimer() { // Start the timer loops as everything is set up. // Aim for 40 frames per second, computers are getting faster. if(g_iTimeoutID == 0) { g_iTimeoutID = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 25, timer_callback, this, NULL); // TODO: Reimplement this (or at least reimplement some kind of status reporting) //g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 5000, long_timer_callback, this, NULL); } } void CDasherControl::ShutdownTimer() { // TODO: Figure out how to implement this - at the moment it's done // through a return value from the timer callback, but it would be // nicer to prevent any further calls as soon as the shutdown signal // has been receieved. } int CDasherControl::CanvasConfigureEvent() { GtkAllocation a; #if GTK_CHECK_VERSION (2,18,0) gtk_widget_get_allocation(m_pCanvas, &a); #else a.width = m_pCanvas->allocation.width; a.height = m_pCanvas->allocation.height; #endif if(m_pScreen != NULL) delete m_pScreen; m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache, a.width, a.height); ChangeScreen(m_pScreen); return 0; } void CDasherControl::ExternalEventHandler(Dasher::CEvent *pEvent) { // Convert events coming from the core to Glib signals. if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); HandleParameterNotification(pEvt->m_iParameter); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_changed", pEvt->m_iParameter); } else if(pEvent->m_iEventType == EV_EDIT) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { // Insert event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_insert", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 2) { // Delete event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 10) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_convert"); } else if(pEditEvent->m_iEditType == 11) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_protect"); } } else if(pEvent->m_iEventType == EV_EDIT_CONTEXT) { CEditContextEvent *pEditContextEvent(static_cast < CEditContextEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_context_request", pEditContextEvent->m_iOffset, pEditContextEvent->m_iLength); } else if(pEvent->m_iEventType == EV_START) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_start"); } else if(pEvent->m_iEventType == EV_STOP) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_stop"); } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast < CControlEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_control", pControlEvent->m_iID); } else if(pEvent->m_iEventType == EV_LOCK) { CLockEvent *pLockEvent(static_cast<CLockEvent *>(pEvent)); DasherLockInfo sInfo; sInfo.szMessage = pLockEvent->m_strMessage.c_str(); sInfo.bLock = pLockEvent->m_bLock; sInfo.iPercent = pLockEvent->m_iPercent; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_lock_info", &sInfo); } else if(pEvent->m_iEventType == EV_MESSAGE) { CMessageEvent *pMessageEvent(static_cast<CMessageEvent *>(pEvent)); DasherMessageInfo sInfo; sInfo.szMessage = pMessageEvent->m_strMessage.c_str(); sInfo.iID = pMessageEvent->m_iID; sInfo.iType = pMessageEvent->m_iType; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_message", &sInfo); } else if(pEvent->m_iEventType == EV_COMMAND) { CCommandEvent *pCommandEvent(static_cast<CCommandEvent *>(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_command", pCommandEvent->m_strCommand.c_str()); } }; void CDasherControl::WriteTrainFile(const std::string &strNewText) { if(strNewText.length() == 0) return; std::string strFilename(GetStringParameter(SP_USER_LOC) + GetStringParameter(SP_TRAIN_FILE)); int fd=open(strFilename.c_str(),O_CREAT|O_WRONLY|O_APPEND,S_IRUSR|S_IWUSR); write(fd,strNewText.c_str(),strNewText.length()); close(fd); } // TODO: Sort these methods out void CDasherControl::ExternalKeyDown(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyDown(get_time(), iButtonID); // } KeyDown(get_time(), iKeyVal); } void CDasherControl::ExternalKeyUp(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyUp(get_time(), iButtonID); // } KeyUp(get_time(), iKeyVal); } void CDasherControl::HandleParameterNotification(int iParameter) { switch(iParameter) { case SP_DASHER_FONT: if(m_pPangoCache) { m_pPangoCache->ChangeFont(GetStringParameter(SP_DASHER_FONT)); ScheduleRedraw(); } break; case BP_GLOBAL_KEYBOARD: // TODO: reimplement // if(m_pKeyboardHelper) // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); break; } } int CDasherControl::TimerEvent() { int x, y; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_pointer(gtk_widget_get_window(m_pCanvas), &x, &y, NULL); #else gdk_window_get_pointer(m_pCanvas->window, &x, &y, NULL); #endif m_pMouseInput->SetCoordinates(x, y); gdk_window_get_pointer(gdk_get_default_root_window(), &x, &y, NULL); int iRootWidth; int iRootHeight; gdk_drawable_get_size(gdk_get_default_root_window(), &iRootWidth, &iRootHeight); if(GetLongParameter(LP_YSCALE) < 10) SetLongParameter(LP_YSCALE, 10); y = (y - iRootHeight / 2); m_p1DMouseInput->SetCoordinates(y, GetLongParameter(LP_YSCALE)); NewFrame(get_time(), false); // Update our UserLog object about the current mouse position CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { // We want current canvas and window coordinates so normalization // is done properly with respect to the canvas. GdkRectangle sWindowRect; GdkRectangle sCanvasRect; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_frame_extents(gtk_widget_get_window(m_pCanvas), &sWindowRect); #else gdk_window_get_frame_extents(m_pCanvas->window, &sWindowRect); #endif pUserLog->AddWindowSize(sWindowRect.y, sWindowRect.x, sWindowRect.y + sWindowRect.height, sWindowRect.x + sWindowRect.width); if (m_pScreen != NULL) { if (m_pScreen->GetCanvasSize(&sCanvasRect)) pUserLog->AddCanvasSize(sCanvasRect.y, sCanvasRect.x, sCanvasRect.y + sCanvasRect.height, sCanvasRect.x + sCanvasRect.width); } int iMouseX = 0; int iMouseY = 0; gdk_window_get_pointer(NULL, &iMouseX, &iMouseY, NULL); // TODO: This sort of thing shouldn't be in specialised methods, move into base class somewhere pUserLog->AddMouseLocationNormalized(iMouseX, iMouseY, true, GetNats()); } return 1; // See CVS for code which used to be here } int CDasherControl::LongTimerEvent() { // std::cout << "Framerate: " << GetFramerate() << std::endl; // std::cout << "Render count: " << GetRenderCount() << std::endl; return 1; } gboolean CDasherControl::ExposeEvent() { NewFrame(get_time(), true); return 0; } gboolean CDasherControl::ButtonPressEvent(GdkEventButton *event) { // Take the focus if we click on the canvas // GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); // gboolean *returnType; // focusEvent->type = GDK_FOCUS_CHANGE; // focusEvent->window = (GdkWindow *) m_pCanvas; // focusEvent->send_event = FALSE; // focusEvent->in = TRUE; // gtk_widget_grab_focus(GTK_WIDGET(m_pCanvas)); // g_signal_emit_by_name(GTK_OBJECT(m_pCanvas), "focus_in_event", GTK_WIDGET(m_pCanvas), focusEvent, NULL, &returnType); // No - don't take the focus - give it to the text area instead if(event->type == GDK_BUTTON_PRESS) HandleClickDown(get_time(), (int)event->x, (int)event->y); else if(event->type == GDK_BUTTON_RELEASE) HandleClickUp(get_time(), (int)event->x, (int)event->y); return false; } gint CDasherControl::KeyReleaseEvent(GdkEventKey *event) { // TODO: This is seriously flawed - the semantics of of X11 Keyboard // events mean the there's no guarantee that key up/down events will // be received in pairs. if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) { // if(event->state & GDK_CONTROL_MASK) // SetLongParameter(LP_BOOSTFACTOR, 25); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) { // if(event->state & GDK_SHIFT_MASK) // SetLongParameter(LP_BOOSTFACTOR, 175); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyUp(get_time(), iKeyVal); // } } return 0; } gint CDasherControl::KeyPressEvent(GdkEventKey *event) { // if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) // SetLongParameter(LP_BOOSTFACTOR, 175); // else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) // SetLongParameter(LP_BOOSTFACTOR, 25); // else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyDown(get_time(), iKeyVal); // } // } return 0; } void CDasherControl::CanvasDestroyEvent() { // Delete the screen if(m_pScreen != NULL) { delete m_pScreen; m_pScreen = NULL; } } // Tell the logging object that a new user trial is starting. void CDasherControl::UserLogNewTrial() { CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { pUserLog->NewTrial(); } } int CDasherControl::GetFileSize(const std::string &strFileName) { struct stat sStatInfo; if(!stat(strFileName.c_str(), &sStatInfo)) return sStatInfo.st_size; else return 0; } // "C" style callbacks - these are here just because it's not possible // (or at least not easy) to connect a callback directly to a C++ // method, so we pass a pointer to th object in the user_data field // and use a wrapper function. Please do not put any functional code // here. extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data) { static_cast < CDasherControl * >(user_data)->RealizeCanvas(widget); } extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) { return static_cast < CDasherControl * >(data)->ButtonPressEvent(event); } extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { return static_cast < CDasherControl * >(data)->KeyPressEvent(event); } extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { return static_cast < CDasherControl * >(data)->CanvasConfigureEvent(); } extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData) { static_cast<CDasherControl*>(pUserData)->CanvasDestroyEvent(); } extern "C" gint key_release_event(GtkWidget *pWidget, GdkEventKey *event, gpointer pUserData) { return static_cast<CDasherControl*>(pUserData)->KeyReleaseEvent(event); } extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return static_cast < CDasherControl * >(data)->FocusEvent(widget, event); } extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data) { return ((CDasherControl*)data)->ExposeEvent(); } diff --git a/Src/Gtk2/GtkDasherControl.cpp b/Src/Gtk2/GtkDasherControl.cpp index 128f8de..3086a37 100644 --- a/Src/Gtk2/GtkDasherControl.cpp +++ b/Src/Gtk2/GtkDasherControl.cpp @@ -1,348 +1,348 @@ // GtkDasherControl.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherControl.h" #include "GtkDasherControl.h" #include "custom_marshal.h" #include "game_mode_helper.h" #include <gtk/gtkmarshal.h> struct _GtkDasherControlPrivate { CDasherControl *pControl; void* pGameHelper; }; typedef struct _GtkDasherControlPrivate GtkDasherControlPrivate; // Signals that this control can emit enum { DASHER_CHANGED, DASHER_START, DASHER_STOP, DASHER_EDIT_INSERT, DASHER_EDIT_DELETE, DASHER_EDIT_CONVERT, DASHER_EDIT_PROTECT, DASHER_CONTROL, DASHER_CONTEXT_REQUEST, DASHER_REQUEST_SETTINGS, DASHER_LOCK_INFO, DASHER_MESSAGE, DASHER_COMMAND, SIGNAL_NUM }; #define GTK_DASHER_CONTROL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), GTK_DASHER_TYPE_CONTROL, GtkDasherControlPrivate)); /* TODO: is it still sensible to derive from VBox, given that its just a cnavas now*/ G_DEFINE_TYPE(GtkDasherControl, gtk_dasher_control, GTK_TYPE_VBOX); static void gtk_dasher_control_finalize(GObject * pObject); static guint gtk_dasher_control_signals[SIGNAL_NUM]; /* TODO: initialise this? */ static void gtk_dasher_control_class_init(GtkDasherControlClass *pClass) { g_type_class_add_private(pClass, sizeof(GtkDasherControlPrivate)); GObjectClass *pObjectClass = (GObjectClass *) pClass; pObjectClass->finalize = gtk_dasher_control_finalize; gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_changed", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_changed), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_START] = g_signal_new("dasher_start", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_start), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_STOP] = g_signal_new("dasher_stop", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_INSERT] = g_signal_new("dasher_edit_insert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_insert), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_DELETE] = g_signal_new("dasher_edit_delete", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_delete), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_CONVERT] = g_signal_new("dasher_edit_convert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_convert), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_PROTECT] = g_signal_new("dasher_edit_protect", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_protect), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("dasher_control", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_control), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_context_request", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_context_request), NULL, NULL, g_cclosure_user_marshal_VOID__INT_INT, G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_INT); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_press_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_press_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_release_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_release_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); gtk_dasher_control_signals[DASHER_REQUEST_SETTINGS] = g_signal_new("dasher_request_settings", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_request_settings), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_LOCK_INFO] = g_signal_new("dasher_lock_info", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_lock), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_MESSAGE] = g_signal_new("dasher_message", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_message), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_COMMAND] = g_signal_new("dasher_command", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_command), NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); pClass->dasher_changed = NULL; pClass->dasher_start = NULL; pClass->dasher_stop = NULL; pClass->dasher_edit_insert = NULL; pClass->dasher_edit_delete = NULL; pClass->dasher_edit_convert = NULL; pClass->dasher_edit_protect = NULL; pClass->dasher_control = NULL; pClass->dasher_context_request = NULL; pClass->dasher_request_settings = NULL; pClass->dasher_lock = NULL; pClass->dasher_message = NULL; pClass->dasher_command = NULL; // pClass->key_press_event = gtk_dasher_control_default_key_press_handler; // pClass->key_release_event = gtk_dasher_control_default_key_release_handler; } static void gtk_dasher_control_init(GtkDasherControl *pDasherControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); pPrivate->pControl = new CDasherControl(&(pDasherControl->box), pDasherControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-press-event", G_CALLBACK(gtk_dasher_control_default_key_press_handler), pPrivate->pControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-release-event", G_CALLBACK(gtk_dasher_control_default_key_release_handler), pPrivate->pControl); } static void gtk_dasher_control_finalize(GObject *pObject) { GtkDasherControl *pDasherControl = GTK_DASHER_CONTROL(pObject); GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); /* TODO: Check that this actually gets called correctly */ /* TODO: Should just call constructor - this should just be a lightweight wrapper class */ pPrivate->pControl->StartShutdown(); delete pPrivate->pControl; // g_free(pDasherControl->private_data); } GtkWidget * gtk_dasher_control_new() { return GTK_WIDGET(g_object_new(GTK_DASHER_TYPE_CONTROL, NULL)); } void gtk_dasher_control_set_parameter_bool(GtkDasherControl *pControl, int iParameter, bool bValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBoolParameter(iParameter, bValue); } void gtk_dasher_control_set_parameter_long(GtkDasherControl *pControl, int iParameter, long lValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetLongParameter(iParameter, lValue); } void gtk_dasher_control_set_parameter_string(GtkDasherControl *pControl, int iParameter, const char *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetStringParameter(iParameter, szValue); } bool gtk_dasher_control_get_parameter_bool(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetBoolParameter(iParameter); } long gtk_dasher_control_get_parameter_long(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetLongParameter(iParameter); } void gtk_dasher_control_reset_parameter(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ResetParameter(iParameter); } const char * gtk_dasher_control_get_parameter_string(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetStringParameter(iParameter).c_str(); } GArray * gtk_dasher_control_get_allowed_values(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetAllowedValues(iParameter); }; void gtk_dasher_control_train(GtkDasherControl *pControl, const gchar *szFilename) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ImportTrainingText(szFilename); }; void gtk_dasher_control_set_context(GtkDasherControl *pControl, const gchar *szContext) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetContext(szContext); } void gtk_dasher_control_set_buffer(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBuffer(iOffset); } void gtk_dasher_control_unset_buffer(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UnsetBuffer(); } void gtk_dasher_control_set_offset(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetOffset(iOffset); } void gtk_dasher_control_register_node(GtkDasherControl *pControl, int iID, const gchar *szLabel, int iColour) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->RegisterNode(iID, szLabel, iColour); } void gtk_dasher_control_connect_node(GtkDasherControl *pControl, int iChild, int iParent, int iAfter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ConnectNode(iChild, iParent, iAfter); } void gtk_dasher_control_disconnect_node(GtkDasherControl *pControl, int iChild, int iParent) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->DisconnectNode(iChild, iParent); } void gtk_dasher_control_external_key_down(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyDown(iKeyVal); } void gtk_dasher_control_external_key_up(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyUp(iKeyVal); } void gtk_dasher_user_log_new_trial(GtkDasherControl * pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UserLogNewTrial(); } void gtk_dasher_control_set_focus(GtkDasherControl * pControl){ GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetFocus(); } // gboolean // gtk_dasher_control_default_key_press_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data){ // static_cast<CDasherControl *>(data)->KeyPressEvent(pEvent); // return FALSE; // } // gboolean // gtk_dasher_control_default_key_release_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data) { // static_cast<CDasherControl *>(data)->KeyReleaseEvent(pEvent); // return FALSE; // } gboolean gtk_dasher_control_get_module_settings(GtkDasherControl * pControl, const gchar *szModule, SModuleSettings **pSettings, gint *iCount) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetModuleSettings(szModule, pSettings, iCount); } void gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameDisplay) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); - pPrivate->pControl->CreateGameDisplay(gameDisplay); + pPrivate->pControl->CreateGameDisplay(gameDisplay); } void gtk_dasher_control_add_game_mode_string(GtkDasherControl *pControl, const gchar *szString) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddGameModeString(szString); } void gtk_dasher_control_game_messagein(GtkDasherControl *pControl, int message, void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->GameMessageIn(message, messagedata); } void gtk_dasher_control_game_helperreg(GtkDasherControl *pControl, void* gameHelper) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pGameHelper = gameHelper; } void gtk_dasher_control_game_messageout(GtkDasherControl *pControl, int message, const void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); GameModeHelper* pHelper = GAME_MODE_HELPER(pPrivate->pGameHelper); if(pHelper) game_mode_helper_message(pHelper, message, messagedata); } void gtk_dasher_control_force_pause(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->Pause(); } double gtk_dasher_control_get_framerate(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetFramerate(); } void gtk_dasher_control_add_action_button(GtkDasherControl *pControl, const gchar *szCommand) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddActionButton(szCommand); } void gtk_dasher_control_set_control_offset(GtkDasherControl *pControl, gint iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetControlOffset(iOffset); } const char * gtk_dasher_control_cl_set(GtkDasherControl *pControl, const gchar *szKey, const gchar *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->ClSet(szKey, szValue); } diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 37d30b8..1b13fcb 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -1,1101 +1,1103 @@ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <utility> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #ifdef WITH_MAEMOFULLSCREEN #include <hildon-widgets/hildon-program.h> #endif #include <unistd.h> #include "GtkDasherControl.h" #include "dasher_lock_dialogue.h" #ifdef WITH_MAEMO #include "dasher_maemo_helper.h" #endif #include "dasher_main.h" #include "dasher_editor.h" #include "dasher_editor_internal.h" #include "dasher_editor_external.h" /* Static instance of singleton, USE SPARINGLY */ static DasherMain *g_pDasherMain = NULL; // TODO: The following global variable makes control mode editing work // - this needs to be sorted out properly. static gboolean g_bSend = true; enum { REALIZED, SIGNAL_NUM }; static guint dasher_main_signals[SIGNAL_NUM] = { 0 }; G_DEFINE_TYPE(DasherMain, dasher_main, G_TYPE_OBJECT); static void dasher_main_finalize(GObject *pObject); /* Private member functions */ static void dasher_main_setup_window_state(DasherMain *pSelf); static void dasher_main_setup_window_style(DasherMain *pSelf); static void dasher_main_setup_internal_layout(DasherMain *pSelf); static void dasher_main_set_window_title(DasherMain *pSelf); /* ... Table based menu/toolbar commands */ static void dasher_main_command_import(DasherMain *pSelf); static void dasher_main_command_quit(DasherMain *pSelf); static void dasher_main_command_preferences(DasherMain *pSelf); static void dasher_main_command_preferences_alphabet(DasherMain *pSelf); static void dasher_main_command_tutorial(DasherMain *pSelf); static void dasher_main_command_help(DasherMain *pSelf); static void dasher_main_command_about(DasherMain *pSelf); /* c.f. WRAP_CPP_CB below */ extern "C" void dasher_main_cb_import(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_quit(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_preferences(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_help(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_about(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_editor(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_toggle_game_mode(GtkAction*, DasherMain*); static gboolean dasher_main_speed_changed(DasherMain *pSelf); static void dasher_main_alphabet_combo_changed(DasherMain *pSelf); // TODO: populate speed slider static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); /* TODO: order these in file */ static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } + g_message("loading interface"); + dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); pPrivate->pGameDisplay = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "GameDisplay")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); + gtk_dasher_control_set_game_display(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), pPrivate->pGameDisplay); + #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // /** * Clear all text out of the dasher editor. * @param pSelf a reference to an instance of DasherMain */ void clear_dasher_editor_text(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } /** * Start game mode, specify the text to play with, and clear out any text in the dasher editor. * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. * * @param pGameTextFilePath - the absolute path to the text file to play with * @param pSelf - a reference to an instance of DasherMain */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkDasherControl *pControl = GTK_DASHER_CONTROL(pPrivate->pDasherWidget); - gtk_dasher_control_set_game_display(pControl, pPrivate->pGameDisplay); - gtk_widget_set_visible(GTK_WIDGET(pPrivate->pGameDisplay), true); dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); clear_dasher_editor_text(pSelf); } /** * Event handler which displays a standard GTK file dialog. The dialog allows the user * to specify a text file to play game mode with. * * @param pButton the button that fired the event * @param pWidget reference needed by GTK for callback signature * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references * to the dialog's parent window and an instance of DasherMain */ void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } /** * Toggle game mode on and off. Toggling on causes a dialog box to be displayed * welcoming the user to game mode and prompting them to specify a file to play with. * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core * to respond appropriately. * * @param pSelf a reference to an instance of DasherMain */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); GtkWidget *pCancelButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); //g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); clear_dasher_editor_text(pSelf); } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue));
rgee/HFOSS-Dasher
f0ce014fe5d589d36755d686105b91a2b8aff94c
Made game mode menu item a toggle button.
diff --git a/Data/GUI/dasher.traditional.ui b/Data/GUI/dasher.traditional.ui index 0e3e1c6..464cea4 100644 --- a/Data/GUI/dasher.traditional.ui +++ b/Data/GUI/dasher.traditional.ui @@ -1,501 +1,501 @@ <?xml version="1.0"?> <!--*- mode: xml -*--> <interface> <object class="GtkAdjustment" id="adjustment1"> <property name="upper">8</property> <property name="lower">0.1</property> <property name="page_increment">1</property> <property name="step_increment">0.1</property> <property name="page_size">0</property> <property name="value">1</property> </object> <object class="GtkUIManager" id="uimanager1"> <child> <object class="GtkActionGroup" id="actiongroup1"> <child> <object class="GtkAction" id="file_menu"> <property name="label" translatable="yes">_File</property> </object> </child> <child> <object class="GtkAction" id="action_new"> <property name="stock_id">gtk-new</property> <property name="tooltip" translatable="yes">New file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_open"> <property name="stock_id">gtk-open</property> <property name="tooltip" translatable="yes">Open file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_save"> <property name="stock_id">gtk-save</property> <property name="tooltip" translatable="yes">Save file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_saveas"> <property name="stock_id">gtk-save-as</property> <property name="tooltip" translatable="yes">Save file as</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_append"> <property name="name">action_append</property> <property name="label" translatable="yes">A_ppend to file…</property> </object> </child> <child> <object class="GtkAction" id="action_import"> <property name="label" translatable="yes">_Import Training Text…</property> <signal name="activate" handler="dasher_main_cb_import"/> </object> </child> <child> <object class="GtkAction" id="action_quit"> <property name="stock_id">gtk-quit</property> <property name="tooltip" translatable="yes">Quit</property> <signal name="activate" handler="dasher_main_cb_quit"/> </object> </child> <child> <object class="GtkAction" id="edit_menu"> <property name="label" translatable="yes">_Edit</property> </object> </child> <child> <object class="GtkAction" id="action_cut"> <property name="stock_id">gtk-cut</property> <property name="tooltip" translatable="yes">Cut</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copy"> <property name="stock_id">gtk-copy</property> <property name="tooltip" translatable="yes">Copy</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copyall"> <property name="label" translatable="yes">Copy _All</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_paste"> <property name="stock_id">gtk-paste</property> <property name="tooltip" translatable="yes">Paste</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_preferences"> <property name="stock_id">gtk-preferences</property> <property name="label" translatable="yes">Pr_eferences…</property> <property name="tooltip" translatable="yes">Preferences</property> <signal name="activate" handler="dasher_main_cb_preferences"/> </object> <accelerator key="S" modifiers="GDK_CONTROL_MASK | GDK_SHIFT_MASK"/> </child> <child> <object class="GtkAction" id="help_menu"> <property name="label" translatable="yes">_Help</property> </object> </child> <child> <object class="GtkAction" id="action_help"> <property name="stock_id">gtk-help</property> <property name="label" translatable="yes">_Contents…</property> <property name="tooltip" translatable="yes">Help</property> <signal name="activate" handler="dasher_main_cb_help"/> </object> <accelerator key="F1" modifiers="0"/> </child> <child> <object class="GtkAction" id="action_about"> <property name="stock_id">gtk-about</property> <property name="label" translatable="yes">_About…</property> <signal name="activate" handler="dasher_main_cb_about"/> </object> </child> <child> - <object class="GtkAction" id="action_toggle_game_mode"> + <object class="GtkToggleAction" id="action_toggle_game_mode"> <property name="stock_id">action_toggle_game_mode</property> <property name="tooltip" translatable="yes">_Game Mode</property> <property name = "label" translatable="yes">_Game Mode</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> </object> </child> <ui> <menubar name="dasher_menu_bar"> <menu action="file_menu"> <menuitem action="action_new"/> <menuitem action="action_open"/> <menuitem action="action_save"/> <menuitem action="action_saveas"/> <menuitem action="action_append"/> <menuitem action="action_toggle_game_mode"/> <separator/> <menuitem action="action_import"/> <menuitem action="action_quit"/> </menu> <menu action="edit_menu"> <menuitem action="action_cut"/> <menuitem action="action_copy"/> <menuitem action="action_copyall"/> <menuitem action="action_paste"/> <separator/> <menuitem action="action_preferences"/> </menu> <menu action="help_menu"> <menuitem action="action_help"/> <menuitem action="action_about"/> </menu> </menubar> <toolbar name="dasher_tool_bar"> <toolitem action="action_new"/> <toolitem action="action_open"/> <toolitem action="action_save"/> <toolitem action="action_saveas"/> <separator/> <toolitem action="action_cut"/> <toolitem action="action_copy"/> <toolitem action="action_paste"/> <separator/> <toolitem action="action_preferences"/> <toolitem action="action_help"/> <separator/> <toolitem action="action_quit"/> </toolbar> </ui> </object> <object class="GtkWindow" id="window"> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="events">GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">Dasher</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_NONE</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">False</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <signal handler="dasher_main_cb_window_close" name="delete_event"/> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkMenuBar" constructor="uimanager1" id="dasher_menu_bar"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Quit</property> <property name="pack_direction">GTK_PACK_DIRECTION_LTR</property> <property name="child_pack_direction">GTK_PACK_DIRECTION_LTR</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkToolbar" constructor="uimanager1" id="dasher_tool_bar"> <property name="toolbar_style">GTK_TOOLBAR_ICONS</property> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkVPaned" id="main_divider"> <property name="visible">True</property> <property name="position">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="DasherEditorInternal" id="DasherEditor"> <property name="visible">True</property> <property name="can_focus">True</property> <signal handler="dasher_main_cb_filename_changed" name="filename_changed"/> <signal handler="dasher_main_cb_buffer_changed" name="buffer_changed"/> <signal handler="dasher_main_cb_context_changed" name="context_changed"/> </object> <packing> <property name="shrink">True</property> <property name="resize">False</property> </packing> </child> <child> <object class = "GtkTable" id = "BottomTable"> <property name = "n-columns">1</property> <property name = "n-rows">2</property> <property name = "row-spacing">0</property> <property name = "column-spacing">0</property> <property name = "visible">True</property> <child> <object class = "GtkHBox" id = "GameDisplay"> <property name = "visible">False</property> <property name = "height_request">30</property> </object> <packing> <property name = "y-options">GTK_FILL</property> <property name = "x-padding">10</property> <property name = "y-padding">10</property> </packing> </child> <child> <object class="GtkDasherControl" id="DasherControl"> <property name="width_request">200</property> <property name="height_request">200</property> <property name="visible">True</property> <signal handler="parameter_notification" name="dasher_changed"/> <signal handler="handle_start_event" name="dasher_start"/> <signal handler="handle_stop_event" name="dasher_stop"/> <signal handler="handle_control_event" name="dasher_control"/> <signal handler="gtk2_edit_output_callback" name="dasher_edit_insert"/> <signal handler="gtk2_edit_delete_callback" name="dasher_edit_delete"/> <signal handler="handle_context_request" name="dasher_context_request"/> <signal handler="handle_request_settings" name="dasher_request_settings"/> <signal handler="focus_in_event" name="focus_in_event"/> <signal handler="on_lock_info" name="dasher_lock_info"/> <signal handler="on_message" name="dasher_message"/> <signal handler="convert_cb" name="dasher_edit_convert"/> <signal handler="protect_cb" name="dasher_edit_protect"/> <signal handler="on_command" name="dasher_command"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name = "top-attach">1</property> <property name = "bottom-attach">2</property> </packing> </child> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkHBox" id="hbox8"> <property name="border_width">2</property> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">2</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkLabel" id="label109"> <property name="visible">True</property> <property name="label" translatable="yes">Speed:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbutton1"> <property name="width_request">64</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="climb_rate">0.10000000149</property> <property name="digits">1</property> <property name="numeric">True</property> <property name="update_policy">GTK_UPDATE_IF_VALID</property> <property name="snap_to_ticks">False</property> <property name="wrap">False</property> <property name="adjustment">adjustment1</property> <signal handler="speed_changed" name="value-changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label110"> <property name="visible">True</property> <property name="label" translatable="yes">Alphabet:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkComboBox" id="combobox1"> <property name="width_request">32</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="add_tearoffs">False</property> <property name="focus_on_click">True</property> <signal handler="alphabet_combo_changed" name="changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">True</property> </packing> </child> </object> </child> </object> <object class="GtkWindow" id="lock_window"> <property name="visible">True</property> <property name="title" translatable="yes">Please Wait…</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">True</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <child> <object class="GtkVBox" id="vbox43"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkLabel" id="lock_message"> <property name="visible">True</property> <property name="label"/> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">0</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> </object> <packing> <property name="padding">8</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkAlignment" id="alignment38"> <property name="border_width">8</property> <property name="visible">True</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xscale">1</property> <property name="yscale">1</property> <property name="top_padding">0</property> <property name="bottom_padding">0</property> <property name="left_padding">0</property> <property name="right_padding">0</property> <child> <object class="GtkProgressBar" id="lock_progress"> <property name="visible">True</property> <property name="orientation">GTK_PROGRESS_LEFT_TO_RIGHT</property> <property name="fraction">0</property> <property name="pulse_step">0.10000000149</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> </object> </child> </object> </interface>
rgee/HFOSS-Dasher
441d3e6df2c68f643fcde736481fa626c6ba1a3c
Made DisplayChunkText take a reference to a string. No need for a pointer here.
diff --git a/Src/DasherCore/GameDisplay.h b/Src/DasherCore/GameDisplay.h index 6107c03..342c31a 100644 --- a/Src/DasherCore/GameDisplay.h +++ b/Src/DasherCore/GameDisplay.h @@ -1,37 +1,37 @@ #ifndef _GameDisplay_H_ #define _GameDisplay_H_ #include <vector> #include <string> using namespace std; namespace Dasher { /** * A class which allows GameModule to display formatted * information in a separate area on the screen. Currently, * the only information it can display is a color coded * representation of the current text chunk (see DispayChunkText). * There is a lot of room for extending this to support new features, * different types of games, etc. */ class CGameDisplay { public: CGameDisplay() {} /** TODO: Improve this documentation * Display a colored sequence of characters in the game display window. * @param text the sequence of characters * @param colors the color to give each index of text */ - virtual void DisplayChunkText(std::string text, std::vector<std::string> *colors) = 0; + virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors) = 0; }; } #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 778851c..057f261 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,209 +1,209 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { //std::stringstream ss; //ss << m_iCurrentStringPos; //g_pLogger->Log(ss.str()); //if(!m_bIsActive) // return; switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); std::stringstream log_stream; log_stream << "First: " << evt->m_pNodes.first << "Second: " << evt->m_pNodes.first << endl; g_pLogger->Log(log_stream.str()); } case EV_EDIT: { DecorateDisplay(); CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { DecorateDisplay(); // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); g_pLogger->Log(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { delete m_pWordGenerator; m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); //pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); //pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); DecorateDisplay(); g_pLogger->Log(m_sTargetString); } void CGameModule::DecorateDisplay() { if(m_pGameDisplay == NULL) return; - std::vector<std::string> *colors = new std::vector<std::string>(); + std::vector<std::string> colors = std::vector<std::string>(); for(int pos = 0; pos < m_sTargetString.length(); pos++) { if(pos < m_iCurrentStringPos + 1) { - colors->push_back("blue"); + colors.push_back("blue"); } else if(pos == m_iCurrentStringPos + 1) { - colors->push_back("red"); + colors.push_back("red"); } else { - colors->push_back("black"); + colors.push_back("black"); } } m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); } void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { m_pGameDisplay = pGameDisplay; } diff --git a/Src/Gtk2/GtkGameDisplay.cpp b/Src/Gtk2/GtkGameDisplay.cpp index 27c1100..e5bd0b9 100644 --- a/Src/Gtk2/GtkGameDisplay.cpp +++ b/Src/Gtk2/GtkGameDisplay.cpp @@ -1,16 +1,16 @@ #include "GtkGameDisplay.h" using namespace std; -void GtkGameDisplay::DisplayChunkText(std::string text, std::vector<std::string> *colors) { +void GtkGameDisplay::DisplayChunkText(std::string text, std::vector<std::string>& colors) { std::string markup = "<span font-weight = \"bold\" font_size = \"xx-large\">"; for(int pos = 0; pos < text.length(); pos++) { - markup += "<span foreground = \""+(*colors)[pos]+"\">"+text.substr(pos, 1)+"</span>"; + markup += "<span foreground = \""+ colors[pos]+"\">"+text.substr(pos, 1)+"</span>"; } markup += "</span>"; gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), markup.c_str()); } diff --git a/Src/Gtk2/GtkGameDisplay.h b/Src/Gtk2/GtkGameDisplay.h index fe66e83..7865d7e 100644 --- a/Src/Gtk2/GtkGameDisplay.h +++ b/Src/Gtk2/GtkGameDisplay.h @@ -1,36 +1,36 @@ #include "../DasherCore/GameDisplay.h" #include <gtk/gtk.h> #include <string> #include <cstring> class GtkGameDisplay : public Dasher::CGameDisplay { public: /** * @param pContainer - the table that all of the * widgets for the game display live in */ GtkGameDisplay(GtkWidget *pContainer) : Dasher::CGameDisplay(), m_pContainer(pContainer) { m_pChunkDisplay = gtk_label_new(NULL); gtk_container_add(GTK_CONTAINER(m_pContainer), m_pChunkDisplay); //gtk_misc_set_alignment(GTK_MISC(m_pChunkDisplay), 0, .5); gtk_widget_set_visible(m_pChunkDisplay, true); } - virtual void DisplayChunkText(std::string text, std::vector<std::string> *colors); + virtual void DisplayChunkText(std::string text, std::vector<std::string>& colors); private: /** * The Gtk table containing the game mode UI. */ GtkWidget *m_pContainer; GtkWidget *m_pChunkDisplay; };
rgee/HFOSS-Dasher
ea9e28b7e737a7921b3d39ff254a6ede8a3eaea9
Forget GtkGameDisplay
diff --git a/Src/Gtk2/GtkGameDisplay.cpp b/Src/Gtk2/GtkGameDisplay.cpp new file mode 100644 index 0000000..27c1100 --- /dev/null +++ b/Src/Gtk2/GtkGameDisplay.cpp @@ -0,0 +1,16 @@ +#include "GtkGameDisplay.h" + +using namespace std; + +void GtkGameDisplay::DisplayChunkText(std::string text, std::vector<std::string> *colors) { + + std::string markup = "<span font-weight = \"bold\" font_size = \"xx-large\">"; + + for(int pos = 0; pos < text.length(); pos++) { + markup += "<span foreground = \""+(*colors)[pos]+"\">"+text.substr(pos, 1)+"</span>"; + } + + markup += "</span>"; + + gtk_label_set_markup(GTK_LABEL(m_pChunkDisplay), markup.c_str()); +} diff --git a/Src/Gtk2/GtkGameDisplay.h b/Src/Gtk2/GtkGameDisplay.h new file mode 100644 index 0000000..fe66e83 --- /dev/null +++ b/Src/Gtk2/GtkGameDisplay.h @@ -0,0 +1,36 @@ +#include "../DasherCore/GameDisplay.h" +#include <gtk/gtk.h> +#include <string> +#include <cstring> + +class GtkGameDisplay : public Dasher::CGameDisplay { + + public: + + + /** + * @param pContainer - the table that all of the + * widgets for the game display live in + */ + GtkGameDisplay(GtkWidget *pContainer) : + Dasher::CGameDisplay(), + m_pContainer(pContainer) + { + m_pChunkDisplay = gtk_label_new(NULL); + gtk_container_add(GTK_CONTAINER(m_pContainer), m_pChunkDisplay); + //gtk_misc_set_alignment(GTK_MISC(m_pChunkDisplay), 0, .5); + gtk_widget_set_visible(m_pChunkDisplay, true); + + } + + virtual void DisplayChunkText(std::string text, std::vector<std::string> *colors); + + private: + + /** + * The Gtk table containing the game mode UI. + */ + GtkWidget *m_pContainer; + GtkWidget *m_pChunkDisplay; + +};
rgee/HFOSS-Dasher
aad00102b651d64f4d8f3aa6b6d1115b4258e05b
Apparently GameDisplay.h was not in version control.
diff --git a/Src/DasherCore/GameDisplay.h b/Src/DasherCore/GameDisplay.h new file mode 100644 index 0000000..6107c03 --- /dev/null +++ b/Src/DasherCore/GameDisplay.h @@ -0,0 +1,37 @@ +#ifndef _GameDisplay_H_ +#define _GameDisplay_H_ + +#include <vector> +#include <string> + +using namespace std; + +namespace Dasher { + +/** + * A class which allows GameModule to display formatted + * information in a separate area on the screen. Currently, + * the only information it can display is a color coded + * representation of the current text chunk (see DispayChunkText). + * There is a lot of room for extending this to support new features, + * different types of games, etc. + */ +class CGameDisplay { + + public: + + CGameDisplay() {} + + /** + TODO: Improve this documentation + + * Display a colored sequence of characters in the game display window. + * @param text the sequence of characters + * @param colors the color to give each index of text + */ + virtual void DisplayChunkText(std::string text, std::vector<std::string> *colors) = 0; +}; + +} + +#endif
rgee/HFOSS-Dasher
fe289087819bc6a5e60ae01bd13908333889334f
Added some method signature documentation to DasherModel. Made sure to check for game mode's toggle status in key places in the model's code.
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 7ab8643..1051b80 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,913 +1,919 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <sstream> #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::GetSymbolList(CDasherNode* pNode, std::deque<CAlphabetManager::CSymbolNode*>& result) { for(std::deque<CDasherNode*>::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if((*it)->GetType() == NT_SYMBOL) { result.push_back(static_cast<CAlphabetManager::CSymbolNode*>(*it)); } else if((*it)->GetType() == NT_GROUP) { std::deque<CAlphabetManager::CSymbolNode*> group_results; GetSymbolList(*it, group_results); result.insert(result.end(), group_results.begin(), group_results.end()); } } } void CDasherModel::GameApproximate() { // Get a list of the symbol IDs of all the currently drawn children. std::deque<CAlphabetManager::CSymbolNode*> vNodes; GetSymbolList(Get_node_under_crosshair(), vNodes); std::vector<int> iTargetSymbols; m_pNodeCreationManager->GetAlphabet()->GetSymbols(iTargetSymbols, m_strGameTarget); int iTargetSymbol = iTargetSymbols.front(); // Check if the target is off to the high end if( iTargetSymbol > vNodes.front()->iSymbol ) { m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), vNodes.front())) ); } // Check if the target is off to the low end if( iTargetSymbol < vNodes.back()->iSymbol) { m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair(vNodes.back(), static_cast<CDasherNode*>(NULL))) ); } for(std::deque<CAlphabetManager::CSymbolNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it) { if( iTargetSymbol < (*it)->iSymbol ) { CAlphabetManager::CSymbolNode* prev = *(--it); m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair( static_cast<CDasherNode*>(NULL), static_cast<CDasherNode*>(NULL)))); } } } void CDasherModel::GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode) { std::vector<int> iTargetSymbols; m_pNodeCreationManager->GetAlphabet()->GetSymbols(iTargetSymbols, m_strGameTarget); int iTargetSymbol = iTargetSymbols.front(); g_pLogger->Log("Begin search for approximate game nodes..."); // If the first symbol is greater than the target, we know the target // must be off the child list to the left if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().begin()))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), (*pNode->GetChildren().begin())))); return; } // If the last symbol is less than the target, we know the target must // be off the child list to the right if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().end()))->iSymbol < iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair( (*pNode->GetChildren().end()), static_cast<CDasherNode*>(NULL) ))); return; } // Otherwise, it's between two elements of the child list. Find those // elements and send them out. for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( static_cast<CAlphabetManager::CSymbolNode*>((*it))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent( std::make_pair( (*--it), (*it) ) )); return; } } } bool CDasherModel::GameSearchChildren(CDasherNode* pNode) { + for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( GameSearchIndividual((*it)) ) return true; } // If we cannot find the target string, it must not be drawn. We know this because every subtree // in the dasher model has one instance of each node in the alphabet. It must be there // somewhere or it's not drawn OR it's not in the alphabet at all. In the last case, we have // larger problems... if(m_strGameTarget != "") { /* std::stringstream ss; ss << Get_node_under_crosshair()->GetChildren().size(); g_pLogger->Log(ss.str()); */ //GameApproximate(); } return false; } bool CDasherModel::GameSearchIndividual(CDasherNode* pNode) { int iType = pNode->GetType(); if(iType == NT_GROUP) { if(GameSearchChildren(pNode)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } else if(iType == NT_SYMBOL) { if(pNode->IsTarget(m_strGameTarget)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); + GameSearchChildren(Get_node_under_crosshair()); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; - // Search from the current root. - GameSearchChildren(Get_node_under_crosshair()); + if(m_bGameMode) { + // Search from the current root. + GameSearchChildren(Get_node_under_crosshair()); + } } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); - // We get here if all our children (groups) and grandchildren (symbols) are created. - // So lets find the correct letters. - if(pNode->GetFlag(NF_GAME)) { - GameSearchChildren(Get_node_under_crosshair()); + if(m_bGameMode) { + // We get here if all our children (groups) and grandchildren (symbols) are created. + // So lets find the correct letters. + if(pNode->GetFlag(NF_GAME)) { + GameSearchChildren(Get_node_under_crosshair()); + } } } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 8235418..8491e2a 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,426 +1,435 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// /// The structure of this tree is the following (English used as an example. /// Specifics may change for other languages, but this is a high-level overview) : /// - Non-Group node has six group nodes for children: /// 1) A non-visible group node that has, 26 children. One for every lower-case /// character. /// 2) A yellow group node with 26 children. One for every upper-case character. /// 3) A green group node who's parent to punctuation nodes. /// 4) The space character/symbol. /// 5) The paragraph/newline symbol. /// 6) A control node, if control mode is turned on. /// /// - Therefore, each level of the tree alternates between 6 group nodes /// and n other nodes where n is defined by the current alphabet. /// /// (rgee: This is my current understanding of the Model. Please correct /// or rephrase any incorrect information.) /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; /** * The string a user must type if game mode is active. */ std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); - + + /** + * Approximate position of target game node. Used when the node cannot be found visible. + */ void GameApproximate(); + + /** + * Gets a collection of all the current symbols under pNode + * @param pNode The node to search under. + * @param result The collection to be populated by the function. + */ void GetSymbolList(CDasherNode* pNode, std::deque<CAlphabetManager::CSymbolNode*>& result); /// /// Search the model for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchChildren(CDasherNode* pNode); /// /// Search the model (recursively) for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchIndividual(CDasherNode* pNode); /// /// Approximate the position of the target node, if it was not /// explicitly found. /// /// \param pNode The node to begin the search from /// \warning Currently only works for symbol or group nodes. This /// needs to be improved. void GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */
rgee/HFOSS-Dasher
a7e27ec54016dadf98a173643c18497db9356b2f
Huge progress on UI today, but still wrestling with 1 off issues.
diff --git a/Data/GUI/dasher.traditional.ui b/Data/GUI/dasher.traditional.ui index d7e1f86..0e3e1c6 100644 --- a/Data/GUI/dasher.traditional.ui +++ b/Data/GUI/dasher.traditional.ui @@ -1,523 +1,501 @@ <?xml version="1.0"?> <!--*- mode: xml -*--> <interface> <object class="GtkAdjustment" id="adjustment1"> <property name="upper">8</property> <property name="lower">0.1</property> <property name="page_increment">1</property> <property name="step_increment">0.1</property> <property name="page_size">0</property> <property name="value">1</property> </object> <object class="GtkUIManager" id="uimanager1"> <child> <object class="GtkActionGroup" id="actiongroup1"> <child> <object class="GtkAction" id="file_menu"> <property name="label" translatable="yes">_File</property> </object> </child> <child> <object class="GtkAction" id="action_new"> <property name="stock_id">gtk-new</property> <property name="tooltip" translatable="yes">New file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_open"> <property name="stock_id">gtk-open</property> <property name="tooltip" translatable="yes">Open file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_save"> <property name="stock_id">gtk-save</property> <property name="tooltip" translatable="yes">Save file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_saveas"> <property name="stock_id">gtk-save-as</property> <property name="tooltip" translatable="yes">Save file as</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_append"> <property name="name">action_append</property> <property name="label" translatable="yes">A_ppend to file…</property> </object> </child> <child> <object class="GtkAction" id="action_import"> <property name="label" translatable="yes">_Import Training Text…</property> <signal name="activate" handler="dasher_main_cb_import"/> </object> </child> <child> <object class="GtkAction" id="action_quit"> <property name="stock_id">gtk-quit</property> <property name="tooltip" translatable="yes">Quit</property> <signal name="activate" handler="dasher_main_cb_quit"/> </object> </child> <child> <object class="GtkAction" id="edit_menu"> <property name="label" translatable="yes">_Edit</property> </object> </child> <child> <object class="GtkAction" id="action_cut"> <property name="stock_id">gtk-cut</property> <property name="tooltip" translatable="yes">Cut</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copy"> <property name="stock_id">gtk-copy</property> <property name="tooltip" translatable="yes">Copy</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copyall"> <property name="label" translatable="yes">Copy _All</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_paste"> <property name="stock_id">gtk-paste</property> <property name="tooltip" translatable="yes">Paste</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_preferences"> <property name="stock_id">gtk-preferences</property> <property name="label" translatable="yes">Pr_eferences…</property> <property name="tooltip" translatable="yes">Preferences</property> <signal name="activate" handler="dasher_main_cb_preferences"/> </object> <accelerator key="S" modifiers="GDK_CONTROL_MASK | GDK_SHIFT_MASK"/> </child> <child> <object class="GtkAction" id="help_menu"> <property name="label" translatable="yes">_Help</property> </object> </child> <child> <object class="GtkAction" id="action_help"> <property name="stock_id">gtk-help</property> <property name="label" translatable="yes">_Contents…</property> <property name="tooltip" translatable="yes">Help</property> <signal name="activate" handler="dasher_main_cb_help"/> </object> <accelerator key="F1" modifiers="0"/> </child> <child> <object class="GtkAction" id="action_about"> <property name="stock_id">gtk-about</property> <property name="label" translatable="yes">_About…</property> <signal name="activate" handler="dasher_main_cb_about"/> </object> </child> <child> <object class="GtkAction" id="action_toggle_game_mode"> <property name="stock_id">action_toggle_game_mode</property> <property name="tooltip" translatable="yes">_Game Mode</property> <property name = "label" translatable="yes">_Game Mode</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> </object> </child> <ui> <menubar name="dasher_menu_bar"> <menu action="file_menu"> <menuitem action="action_new"/> <menuitem action="action_open"/> <menuitem action="action_save"/> <menuitem action="action_saveas"/> <menuitem action="action_append"/> <menuitem action="action_toggle_game_mode"/> <separator/> <menuitem action="action_import"/> <menuitem action="action_quit"/> </menu> <menu action="edit_menu"> <menuitem action="action_cut"/> <menuitem action="action_copy"/> <menuitem action="action_copyall"/> <menuitem action="action_paste"/> <separator/> <menuitem action="action_preferences"/> </menu> <menu action="help_menu"> <menuitem action="action_help"/> <menuitem action="action_about"/> </menu> </menubar> <toolbar name="dasher_tool_bar"> <toolitem action="action_new"/> <toolitem action="action_open"/> <toolitem action="action_save"/> <toolitem action="action_saveas"/> <separator/> <toolitem action="action_cut"/> <toolitem action="action_copy"/> <toolitem action="action_paste"/> <separator/> <toolitem action="action_preferences"/> <toolitem action="action_help"/> <separator/> <toolitem action="action_quit"/> </toolbar> </ui> </object> <object class="GtkWindow" id="window"> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="events">GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">Dasher</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_NONE</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">False</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <signal handler="dasher_main_cb_window_close" name="delete_event"/> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkMenuBar" constructor="uimanager1" id="dasher_menu_bar"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Quit</property> <property name="pack_direction">GTK_PACK_DIRECTION_LTR</property> <property name="child_pack_direction">GTK_PACK_DIRECTION_LTR</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkToolbar" constructor="uimanager1" id="dasher_tool_bar"> <property name="toolbar_style">GTK_TOOLBAR_ICONS</property> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkVPaned" id="main_divider"> <property name="visible">True</property> <property name="position">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="DasherEditorInternal" id="DasherEditor"> <property name="visible">True</property> <property name="can_focus">True</property> <signal handler="dasher_main_cb_filename_changed" name="filename_changed"/> <signal handler="dasher_main_cb_buffer_changed" name="buffer_changed"/> <signal handler="dasher_main_cb_context_changed" name="context_changed"/> </object> <packing> <property name="shrink">True</property> <property name="resize">False</property> </packing> </child> <child> <object class = "GtkTable" id = "BottomTable"> <property name = "n-columns">1</property> <property name = "n-rows">2</property> <property name = "row-spacing">0</property> <property name = "column-spacing">0</property> <property name = "visible">True</property> <child> - <object class = "GtkTable" id = "GameDisplay"> + <object class = "GtkHBox" id = "GameDisplay"> - <property name = "n-columns">2</property> - <property name = "n-rows">1</property> - <property name = "row-spacing">0</property> - <property name = "column-spacing">0</property> - <property name = "visible">True</property> - - <child> - - <object class = "GtkLabel" id = "GameChunkDisplay"> - <property name = "visible">True</property> - <property name = "label">This is a test</property> - <property name = "xalign">0</property> - <property name="use_markup">True</property> - </object> - - <packing> - <property name = "left-attach">1</property> - </packing> - - </child> - <child> - <placeholder/> - <!-- Add more table cells to implement new Game Mode display elements" --> - </child> + <property name = "visible">False</property> + <property name = "height_request">30</property> </object> <packing> <property name = "y-options">GTK_FILL</property> <property name = "x-padding">10</property> <property name = "y-padding">10</property> </packing> </child> <child> <object class="GtkDasherControl" id="DasherControl"> <property name="width_request">200</property> <property name="height_request">200</property> <property name="visible">True</property> <signal handler="parameter_notification" name="dasher_changed"/> <signal handler="handle_start_event" name="dasher_start"/> <signal handler="handle_stop_event" name="dasher_stop"/> <signal handler="handle_control_event" name="dasher_control"/> <signal handler="gtk2_edit_output_callback" name="dasher_edit_insert"/> <signal handler="gtk2_edit_delete_callback" name="dasher_edit_delete"/> <signal handler="handle_context_request" name="dasher_context_request"/> <signal handler="handle_request_settings" name="dasher_request_settings"/> <signal handler="focus_in_event" name="focus_in_event"/> <signal handler="on_lock_info" name="dasher_lock_info"/> <signal handler="on_message" name="dasher_message"/> <signal handler="convert_cb" name="dasher_edit_convert"/> <signal handler="protect_cb" name="dasher_edit_protect"/> <signal handler="on_command" name="dasher_command"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name = "top-attach">1</property> <property name = "bottom-attach">2</property> </packing> </child> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkHBox" id="hbox8"> <property name="border_width">2</property> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">2</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkLabel" id="label109"> <property name="visible">True</property> <property name="label" translatable="yes">Speed:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbutton1"> <property name="width_request">64</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="climb_rate">0.10000000149</property> <property name="digits">1</property> <property name="numeric">True</property> <property name="update_policy">GTK_UPDATE_IF_VALID</property> <property name="snap_to_ticks">False</property> <property name="wrap">False</property> <property name="adjustment">adjustment1</property> <signal handler="speed_changed" name="value-changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label110"> <property name="visible">True</property> <property name="label" translatable="yes">Alphabet:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkComboBox" id="combobox1"> <property name="width_request">32</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="add_tearoffs">False</property> <property name="focus_on_click">True</property> <signal handler="alphabet_combo_changed" name="changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">True</property> </packing> </child> </object> </child> </object> <object class="GtkWindow" id="lock_window"> <property name="visible">True</property> <property name="title" translatable="yes">Please Wait…</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">True</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <child> <object class="GtkVBox" id="vbox43"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkLabel" id="lock_message"> <property name="visible">True</property> <property name="label"/> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">0</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> </object> <packing> <property name="padding">8</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkAlignment" id="alignment38"> <property name="border_width">8</property> <property name="visible">True</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xscale">1</property> <property name="yscale">1</property> <property name="top_padding">0</property> <property name="bottom_padding">0</property> <property name="left_padding">0</property> <property name="right_padding">0</property> <child> <object class="GtkProgressBar" id="lock_progress"> <property name="visible">True</property> <property name="orientation">GTK_PROGRESS_LEFT_TO_RIGHT</property> <property name="fraction">0</property> <property name="pulse_step">0.10000000149</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> </object> </child> </object> </interface> diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index ba11c64..e050421 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1190 +1,1189 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <tr1/memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; + m_pGameDisplay = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); + + if(GetBoolParameter(BP_GAME_MODE)) + InitGameModule(); + + CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); + // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); case BP_GAME_MODE: if(GetBoolParameter(BP_GAME_MODE)) { InitGameModule(); } else if(m_pGameModule){ ResetGameModule(); } default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } /** * Reset the dasher model, fetch the game module from the module manager, * set its word generator, and make it available via m_pGameModule. */ void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { CreateModel(0); m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); m_pGameModule->SetWordGenerator(new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE))); + m_pGameModule->SetGameDisplay(m_pGameDisplay); } } /** * Reset the game module, reset the dasher model, and set m_pGameModule to NULL. */ void CDasherInterfaceBase::ResetGameModule() { m_pGameModule->reset(); CreateModel(0); m_pGameModule = NULL; } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager - // TODO should this be wrapped in an "if game mode enabled" - // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value - // TODO: Put "Game Mode" in enumeration in Parameter.h - - // We use a shared ptr here for the word generator to avoid issues regarding - // object ownership. Now this class /could/ own a word generator if it wanted - // whereas before its ownership was ambiguous to the only class that - // could delete it. (The game module) Therefore, newing directly to - // the constructor leaked memory. RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherInterfaceBase.h b/Src/DasherCore/DasherInterfaceBase.h index 8dff81b..ec099cc 100644 --- a/Src/DasherCore/DasherInterfaceBase.h +++ b/Src/DasherCore/DasherInterfaceBase.h @@ -1,596 +1,607 @@ // DasherInterfaceBase.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherInterfaceBase_h__ #define __DasherInterfaceBase_h__ /// /// \mainpage /// /// This is the Dasher source code documentation. Please try to keep /// it up to date! /// // TODO - there is a list of things to be configurable in my notes // Check that everything that is not self-contained within the GUI is covered. #include "../Common/NoClones.h" #include "../Common/ModuleSettings.h" #include "ActionButton.h" #include "Alphabet/Alphabet.h" #include "Alphabet/AlphIO.h" #include "AutoSpeedControl.h" #include "ColourIO.h" #include "InputFilter.h" #include "ModuleManager.h" #include "GameModule.h" +#include "GameDisplay.h" #include <map> #include <algorithm> namespace Dasher { class CDasherScreen; class CDasherView; class CDasherInput; class CDasherModel; class CEventHandler; class CEvent; class CGameModule; class CDasherInterfaceBase; } class CSettingsStore; class CUserLogBase; class CNodeCreationManager; /// \defgroup Core Core Dasher classes /// @{ struct Dasher::SLockData { std::string strDisplay; int iPercent; }; /// The central class in the core of Dasher. Ties together the rest of /// the platform independent stuff and provides a single interface for /// the UI to use. class Dasher::CDasherInterfaceBase:private NoClones { public: CDasherInterfaceBase(); virtual ~CDasherInterfaceBase(); /// @name Access to internal member classes /// Access various classes contained within the interface. These /// should be considered dangerous and use minimised. Eventually to /// be replaced by properly encapsulated equivalents. /// @{ /// /// Return a pointer to the current EventHandler (the one /// which the CSettingsStore is using to notify parameter /// changes) /// virtual CEventHandler *GetEventHandler() { return m_pEventHandler; }; /// /// \deprecated In situ alphabet editing is no longer supported /// \todo Document this /// const CAlphIO::AlphInfo & GetInfo(const std::string & AlphID); /// \todo Document this void SetInfo(const CAlphIO::AlphInfo & NewInfo); /// \todo Document this void DeleteAlphabet(const std::string & AlphID); /// Get a pointer to the current alphabet object CAlphabet *GetAlphabet() { return m_Alphabet; } /// Gets a pointer to the object doing user logging CUserLogBase* GetUserLogPtr(); // @} /// /// @name Parameter manipulation /// Members for manipulating the parameters of the core Dasher object. /// //@{ /// /// Set a boolean parameter. /// \param iParameter The parameter to set. /// \param bValue The new value. /// void SetBoolParameter(int iParameter, bool bValue); /// /// Set a long integer parameter. /// \param iParameter The parameter to set. /// \param lValue The new value. /// void SetLongParameter(int iParameter, long lValue); /// /// Set a string parameter. /// \param iParameter The parameter to set. /// \param sValue The new value. /// void SetStringParameter(int iParameter, const std::string & sValue); /// Get a boolean parameter /// \param iParameter The parameter to get. /// \retval The current value. bool GetBoolParameter(int iParameter); /// Get a long integer parameter /// \param iParameter The parameter to get. /// \retval The current value. long GetLongParameter(int iParameter); /// Get a string parameter /// \param iParameter The parameter to get. /// \retval The current value. std::string GetStringParameter(int iParameter); /// /// Reset a parameter to the default value /// void ResetParameter(int iParmater); /// /// Obtain the permitted values for a string parameter - used to /// geneate preferences dialogues etc. /// void GetPermittedValues(int iParameter, std::vector<std::string> &vList); /// /// Get a list of settings which apply to a particular module /// bool GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount); //@} /// Forward events to listeners in the SettingsUI and Editbox. /// \param pEvent The event to forward. /// \todo Should be protected. virtual void ExternalEventHandler(Dasher::CEvent * pEvent) {}; /// Interface level event handler. For example, responsible for /// restarting the Dasher model whenever parameter changes make it /// invalid. /// \param pEvent The event. /// \todo Should be protected. void InterfaceEventHandler(Dasher::CEvent * pEvent); void PreSetNotify(int iParameter, const std::string &sValue); /// @name Starting and stopping /// Methods used to instruct dynamic motion of Dasher to start or stop /// @{ /// Resets the Dasher model. Doesn't actually unpause Dasher. /// \deprecated Use InvalidateContext() instead // void Start(); /// Pause Dasher. Sets BP_DASHER_PAUSED and broadcasts a StopEvent. /// (But does nothing if BP_DASHER_PAUSED is not set) void Pause(); // are required to make /// Unpause Dasher. Clears BP_DASHER_PAUSED, broadcasts a StartEvent. /// (But does nothing if BP_DASHER_PAUSED is currently set). /// \param Time Time in ms, used to keep a constant frame rate void Unpause(unsigned long Time); // Dasher run at the /// @} // App Interface // ----------------------------------------------------- // std::map<int, std::string>& GetAlphabets(); // map<key, value> int is a UID string can change. Store UID in preferences. Display string to user. // std::vector<std::string>& GetAlphabets(); // std::vector<std::string>& GetLangModels(); // std::vector<std::string>& GetViews(); /// Supply a new CDasherScreen object to do the rendering. /// \param NewScreen Pointer to the new CDasherScreen. void ChangeScreen(CDasherScreen * NewScreen); // We may change the widgets Dasher uses /// Train Dasher from a file /// All traing data must be in UTF-8 /// \param Filename File to load. /// \param iTotalBytes documentme /// \param iOffset Document me // int TrainFile(std::string Filename, int iTotalBytes, int iOffset); /// Set the context in which Dasher makes predictions /// \param strNewContext The new context (UTF-8) void SetContext(std::string strNewContext); /// New control mechanisms: void SetBuffer(int iOffset); void UnsetBuffer(); void SetOffset(int iOffset); /// @name Status reporting /// Get information about the runtime status of Dasher which might /// be of interest for debugging purposes etc. /// @{ /// Get the current rate of text entry. /// \retval The rate in characters per minute. /// TODO: Check that this is still used double GetCurCPM(); /// Get current refresh rate. /// \retval The rate in frames per second /// TODO: Check that this is still used double GetCurFPS(); /// Get the total number of nats (base-e bits) entered. /// \retval The current total /// \todo Obsolete since new logging code? double GetNats() const; /// Reset the count of nats entered. /// \todo Obsolete since new logging code? void ResetNats(); double GetFramerate(); /// @} /// @name Control hierarchy and action buttons /// Manipulate the hierarchy of commands presented in control mode etc /// @{ void RegisterNode( int iID, const std::string &strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); void ExecuteCommand(const std::string &strName); void AddActionButton(const std::string &strName); /// @} /// @name User input /// Deals with forwarding user input to the core /// @{ void KeyDown(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void KeyUp(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void HandleClickUp(int iTime, int iX, int iY); void HandleClickDown(int iTime, int iX, int iY); /// @} // Module management functions CDasherModule *RegisterModule(CDasherModule *pModule); CDasherModule *GetModule(ModuleID_t iID); CDasherModule *GetModuleByName(const std::string &strName); CDasherModule *GetDefaultInputDevice(); CDasherModule *GetDefaultInputMethod(); void SetDefaultInputDevice(CDasherModule *); void SetDefaultInputMethod(CDasherModule *); void StartShutdown(); void AddGameModeString(const std::string &strText) { m_deGameModeStrings.push_back(strText); Pause(); // CreateDasherModel(); CreateNCManager(); // Start(); }; void GameMessageIn(int message, void* messagedata); virtual void GameMessageOut(int message, const void* messagedata) {} void ScheduleRedraw() { m_bRedrawScheduled = true; }; std::string GetContext(int iStart, int iLength); void SetControlOffset(int iOffset); /// Set a key value pair by name - designed to allow operation from /// the command line. Returns 0 on success, an error string on failure. /// const char* ClSet(const std::string &strKey, const std::string &strValue); void ImportTrainingText(const std::string &strPath); protected: /// @name Startup /// Interaction with the derived class during core startup /// @{ /// /// Allocate resources, create alphabets etc. This is a separate /// routine to the constructor to give us a chance to set up /// parameters before things are created. /// void Realize(); /// /// Notify the core that the UI has been realised. At this point drawing etc. is expected to work /// void OnUIRealised(); /// /// Creates a default set of modules. Override in subclasses to create any /// extra/different modules specific to the platform (eg input device drivers) /// virtual void CreateModules(); /// @} /// Draw a new Dasher frame, regardless of whether we're paused etc. /// \param iTime Current time in ms. /// \param bForceRedraw /// \todo See comments in cpp file for some functionality which needs to be re-implemented void NewFrame(unsigned long iTime, bool bForceRedraw); enum ETransition { TR_MODEL_INIT = 0, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN, TR_NUM }; enum EState { ST_START = 0, ST_MODEL, ST_UI, ST_NORMAL, ST_LOCKED, ST_SHUTDOWN, ST_NUM, ST_FORBIDDEN, ST_DELAY }; /// @name State machine functions /// ... /// @{ void ChangeState(ETransition iTransition); /// @} CEventHandler *m_pEventHandler; CSettingsStore *m_pSettingsStore; + + /** + * The display widget used by GameModule to display a helpful UI. + * Insantiated by platform specific implementations of DasherIntefaceBase. + */ + CGameDisplay *m_pGameDisplay; + private: //The default expansion policy to use - an amortized policy depending on the LP_NODE_BUDGET parameter. CExpansionPolicy *m_defaultPolicy; /// @name Platform dependent utility functions /// These functions provide various platform dependent functions /// required by the core. A derived class is created for each /// supported platform which implements these. // @{ /// /// Initialise the SP_SYSTEM_LOC and SP_USER_LOC paths - the exact /// method of doing this will be OS dependent /// virtual void SetupPaths() = 0; /// /// Produce a list of filenames for alphabet files /// virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList) = 0; /// /// Produce a list of filenames for colour files /// virtual void ScanColourFiles(std::vector<std::string> &vFileList) = 0; /// /// Set up the platform dependent UI for the widget (not the wider /// app). Note that the constructor of the derived class will /// probably want to return details of what was created - this will /// have to happen separately, but we'll need to be careful with the /// semantics. /// virtual void SetupUI() = 0; /// /// Create settings store object, which will be platform dependent /// TODO: Can this not be done just by selecting which settings /// store implementation to instantiate? /// virtual void CreateSettingsStore() = 0; /// /// Obtain the size in bytes of a file - the way to do this is /// dependent on the OS (TODO: Check this - any posix on Windows?) /// virtual int GetFileSize(const std::string &strFileName) = 0; /// /// Start the callback timer /// virtual void StartTimer() = 0; /// /// Shutdown the callback timer (permenantly - this is called once /// Dasher is committed to closing). /// virtual void ShutdownTimer() = 0; /// /// Append text to the training file - used to store state between /// sessions /// @todo Pass file path to the function rather than having implementations work it out themselves /// virtual void WriteTrainFile(const std::string &strNewText) { }; /// @} /// Provide a new CDasherInput input device object. void CreateInput(); /** * Initialize m_pGameModule by fetching the * constructed module from the module manager. */ void InitGameModule(); /** * Reset m_pGameModule - called when game mode is disabled. */ void ResetGameModule(); void CreateInputFilter(); void CreateModel(int iOffset); void CreateNCManager(); void ChangeAlphabet(); void ChangeColours(); void ChangeView(); void Redraw(bool bRedrawNodes, CExpansionPolicy &policy); void SetupActionButtons(); void DestroyActionButtons(); void PositionActionButtons(); bool DrawActionButtons(); void WriteTrainFileFull(); void WriteTrainFilePartial(); std::deque<std::string> m_deGameModeStrings; std::vector<CActionButton *> m_vLeftButtons; std::vector<CActionButton *> m_vRightButtons; /// @name Child components /// Various objects which are 'owned' by the core. /// @{ CAlphabet *m_Alphabet; CDasherModel *m_pDasherModel; CDasherScreen *m_DasherScreen; CDasherView *m_pDasherView; CDasherInput *m_pInput; CInputFilter* m_pInputFilter; CModuleManager m_oModuleManager; CAlphIO *m_AlphIO; CColourIO *m_ColourIO; CNodeCreationManager *m_pNCManager; CUserLogBase *m_pUserLog; - // the game mode module - only - // initialized if game mode is enabled + /** + * The game mode module - only + * initialized if game mode is enabled + */ CGameModule *m_pGameModule; + /// @} std::string strTrainfileBuffer; std::string strCurrentContext; std::string m_strContext; /// @name State variables /// Represent the current overall state of the core /// @{ // bool m_bGlobalLock; // The big lock bool m_bRedrawScheduled; EState m_iCurrentState; bool m_bOldVisible; /// @} bool m_bLastChanged; }; /// @} #endif /* #ifndef __DasherInterfaceBase_h__ */ diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index d8bf7a5..778851c 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,173 +1,209 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { //std::stringstream ss; //ss << m_iCurrentStringPos; //g_pLogger->Log(ss.str()); //if(!m_bIsActive) // return; switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); std::stringstream log_stream; log_stream << "First: " << evt->m_pNodes.first << "Second: " << evt->m_pNodes.first << endl; g_pLogger->Log(log_stream.str()); } case EV_EDIT: { - CEditEvent* evt = static_cast<CEditEvent*>(pEvent); + DecorateDisplay(); + + CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { + + DecorateDisplay(); + // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); g_pLogger->Log(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); } void CGameModule::reset() { delete m_pWordGenerator; m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } + + bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); - pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); - pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); + //pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); + //pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); + + DecorateDisplay(); + g_pLogger->Log(m_sTargetString); +} + +void CGameModule::DecorateDisplay() { + + if(m_pGameDisplay == NULL) return; + + std::vector<std::string> *colors = new std::vector<std::string>(); + + for(int pos = 0; pos < m_sTargetString.length(); pos++) { + + if(pos < m_iCurrentStringPos + 1) { + colors->push_back("blue"); + } + else if(pos == m_iCurrentStringPos + 1) { + colors->push_back("red"); + } + else { + colors->push_back("black"); + } + } + + m_pGameDisplay->DisplayChunkText(m_sTargetString, colors); +} + +void CGameModule::SetGameDisplay(CGameDisplay *pGameDisplay) { + m_pGameDisplay = pGameDisplay; } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 2797bd8..816374e 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,232 +1,244 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" -#include <tr1/memory> +#include "GameDisplay.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, Dasher::CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pInterface(pInterface), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) - {} + { + } ~CGameModule() { m_pSettingsStore->SetBoolParameter(BP_GAME_MODE, false); } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); /** * Set the word generator for this instance to draw words from. * @param pWordGenerator the word generator to be used */ void SetWordGenerator(CWordGeneratorBase *pWordGenerator); /** * Reset the game module. This makes the game module invalid until it is provided * with a new WordGenerator. */ void reset(); + void SetGameDisplay(CGameDisplay *pGameDisplay); + private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); - + /** + * Update the game display. + */ + void DecorateDisplay(); + /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ + /** + * The display widget that this module is using to draw its UI. + */ + CGameDisplay *m_pGameDisplay; + /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase *m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ Dasher::CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /** * Flag that denotes whether we are approximating the target position * or not. */ bool m_bApproximating; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ static const int vEvents[3]; }; } #endif diff --git a/Src/Gtk2/DasherControl.cpp b/Src/Gtk2/DasherControl.cpp index a8f96f3..40de89b 100644 --- a/Src/Gtk2/DasherControl.cpp +++ b/Src/Gtk2/DasherControl.cpp @@ -1,626 +1,631 @@ #include "../Common/Common.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <iostream> #include "DasherControl.h" #include "Timer.h" #include "../DasherCore/Event.h" #include "../DasherCore/ModuleManager.h" +#include "GtkGameDisplay.h" #include <fcntl.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <sys/stat.h> #include <unistd.h> using namespace std; // 'Private' methods (only used in this file) extern "C" gint key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data); extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data); extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data); extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData); extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data); static bool g_iTimeoutID = 0; // CDasherControl class definitions CDasherControl::CDasherControl(GtkVBox *pVBox, GtkDasherControl *pDasherControl) { m_pPangoCache = NULL; m_pScreen = NULL; m_pDasherControl = pDasherControl; m_pVBox = GTK_WIDGET(pVBox); Realize(); // m_pKeyboardHelper = new CKeyboardHelper(this); // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); } void CDasherControl::CreateModules() { CDasherInterfaceBase::CreateModules(); //create default set first // Create locally cached copies of the mouse input objects, as we // need to pass coordinates to them from the timer callback m_pMouseInput = (CDasherMouseInput *) RegisterModule(new CDasherMouseInput(m_pEventHandler, m_pSettingsStore)); SetDefaultInputDevice(m_pMouseInput); m_p1DMouseInput = (CDasher1DMouseInput *)RegisterModule(new CDasher1DMouseInput(m_pEventHandler, m_pSettingsStore)); RegisterModule(new CSocketInput(m_pEventHandler, m_pSettingsStore)); #ifdef JOYSTICK RegisterModule(new CDasherJoystickInput(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CDasherJoystickInputDiscrete(m_pEventHandler, m_pSettingsStore, this)); #endif #ifdef TILT RegisterModule(new CDasherTiltInput(m_pEventHandler, m_pSettingsStore, this)); #endif } void CDasherControl::SetupUI() { m_pCanvas = gtk_drawing_area_new(); #if GTK_CHECK_VERSION (2,18,0) gtk_widget_set_can_focus(m_pCanvas, TRUE); #else GTK_WIDGET_SET_FLAGS(m_pCanvas, GTK_CAN_FOCUS); #endif gtk_widget_set_double_buffered(m_pCanvas, FALSE); GtkWidget *pFrame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(pFrame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(pFrame), m_pCanvas); gtk_box_pack_start(GTK_BOX(m_pVBox), pFrame, TRUE, TRUE, 0); gtk_widget_show_all(GTK_WIDGET(m_pVBox)); // Connect callbacks - note that we need to implement the callbacks // as "C" style functions and pass this as user data so they can // call the object g_signal_connect(m_pCanvas, "button_press_event", G_CALLBACK(button_press_event), this); g_signal_connect(m_pCanvas, "button_release_event", G_CALLBACK(button_press_event), this); g_signal_connect_after(m_pCanvas, "realize", G_CALLBACK(realize_canvas), this); g_signal_connect(m_pCanvas, "configure_event", G_CALLBACK(canvas_configure_event), this); g_signal_connect(m_pCanvas, "destroy", G_CALLBACK(canvas_destroy_event), this); g_signal_connect(m_pCanvas, "key-release-event", G_CALLBACK(key_release_event), this); g_signal_connect(m_pCanvas, "key_press_event", G_CALLBACK(key_press_event), this); g_signal_connect(m_pCanvas, "focus_in_event", G_CALLBACK(canvas_focus_event), this); g_signal_connect(m_pCanvas, "expose_event", G_CALLBACK(canvas_expose_event), this); //g_signal_connect(m_pDasher) // Create the Pango cache // TODO: Use system defaults? if(GetStringParameter(SP_DASHER_FONT) == "") SetStringParameter(SP_DASHER_FONT, "Sans 10"); m_pPangoCache = new CPangoCache(GetStringParameter(SP_DASHER_FONT)); } void CDasherControl::SetupPaths() { char *home_dir; char *user_data_dir; const char *system_data_dir; home_dir = getenv("HOME"); user_data_dir = new char[strlen(home_dir) + 10]; sprintf(user_data_dir, "%s/.dasher/", home_dir); mkdir(user_data_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // PROGDATA is provided by the makefile system_data_dir = PROGDATA "/"; SetStringParameter(SP_SYSTEM_LOC, system_data_dir); SetStringParameter(SP_USER_LOC, user_data_dir); delete[] user_data_dir; } +void CDasherControl::CreateGameDisplay(void* pGameDisplay) { + m_pGameDisplay = new GtkGameDisplay(GTK_WIDGET(pGameDisplay)); +} + void CDasherControl::CreateSettingsStore() { m_pSettingsStore = new CGnomeSettingsStore(m_pEventHandler); } void CDasherControl::ScanAlphabetFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *alphabetglob; alphabetglob = g_pattern_spec_new("alphabet*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(alphabetglob); } void CDasherControl::ScanColourFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *colourglob; colourglob = g_pattern_spec_new("colour*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(colourglob); } CDasherControl::~CDasherControl() { if(m_pMouseInput) { m_pMouseInput = NULL; } if(m_p1DMouseInput) { m_p1DMouseInput = NULL; } if(m_pPangoCache) { delete m_pPangoCache; m_pPangoCache = NULL; } // if(m_pKeyboardHelper) { // delete m_pKeyboardHelper; // m_pKeyboardHelper = 0; // } } bool CDasherControl::FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent) { if((pEvent->type == GDK_FOCUS_CHANGE) && (pEvent->in)) { GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); gboolean *returnType; focusEvent->type = GDK_FOCUS_CHANGE; focusEvent->window = (GdkWindow *) m_pDasherControl; focusEvent->send_event = FALSE; focusEvent->in = TRUE; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "focus_in_event", GTK_WIDGET(m_pDasherControl), focusEvent, NULL, &returnType); } return true; } void CDasherControl::SetFocus() { gtk_widget_grab_focus(m_pCanvas); } void CDasherControl::GameMessageOut(int message, const void* messagedata) { gtk_dasher_control_game_messageout(m_pDasherControl, message, messagedata); } GArray *CDasherControl::GetAllowedValues(int iParameter) { // Glib version of the STL based core function GArray *pRetVal(g_array_new(false, false, sizeof(gchar *))); std::vector < std::string > vList; GetPermittedValues(iParameter, vList); for(std::vector < std::string >::iterator it(vList.begin()); it != vList.end(); ++it) { // For internal glib reasons we need to make a variable and then // pass - we can't use the iterator directly const char *pTemp(it->c_str()); char *pTempNew = new char[strlen(pTemp) + 1]; strcpy(pTempNew, pTemp); g_array_append_val(pRetVal, pTempNew); } return pRetVal; } void CDasherControl::RealizeCanvas(GtkWidget *pWidget) { // TODO: Pointless function - call directly from C callback. #ifdef DEBUG std::cout << "RealizeCanvas()" << std::endl; #endif OnUIRealised(); } void CDasherControl::StartTimer() { // Start the timer loops as everything is set up. // Aim for 40 frames per second, computers are getting faster. if(g_iTimeoutID == 0) { g_iTimeoutID = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 25, timer_callback, this, NULL); // TODO: Reimplement this (or at least reimplement some kind of status reporting) //g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 5000, long_timer_callback, this, NULL); } } void CDasherControl::ShutdownTimer() { // TODO: Figure out how to implement this - at the moment it's done // through a return value from the timer callback, but it would be // nicer to prevent any further calls as soon as the shutdown signal // has been receieved. } int CDasherControl::CanvasConfigureEvent() { GtkAllocation a; #if GTK_CHECK_VERSION (2,18,0) gtk_widget_get_allocation(m_pCanvas, &a); #else a.width = m_pCanvas->allocation.width; a.height = m_pCanvas->allocation.height; #endif if(m_pScreen != NULL) delete m_pScreen; m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache, a.width, a.height); ChangeScreen(m_pScreen); return 0; } void CDasherControl::ExternalEventHandler(Dasher::CEvent *pEvent) { // Convert events coming from the core to Glib signals. if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); HandleParameterNotification(pEvt->m_iParameter); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_changed", pEvt->m_iParameter); } else if(pEvent->m_iEventType == EV_EDIT) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { // Insert event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_insert", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 2) { // Delete event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 10) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_convert"); } else if(pEditEvent->m_iEditType == 11) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_protect"); } } else if(pEvent->m_iEventType == EV_EDIT_CONTEXT) { CEditContextEvent *pEditContextEvent(static_cast < CEditContextEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_context_request", pEditContextEvent->m_iOffset, pEditContextEvent->m_iLength); } else if(pEvent->m_iEventType == EV_START) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_start"); } else if(pEvent->m_iEventType == EV_STOP) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_stop"); } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast < CControlEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_control", pControlEvent->m_iID); } else if(pEvent->m_iEventType == EV_LOCK) { CLockEvent *pLockEvent(static_cast<CLockEvent *>(pEvent)); DasherLockInfo sInfo; sInfo.szMessage = pLockEvent->m_strMessage.c_str(); sInfo.bLock = pLockEvent->m_bLock; sInfo.iPercent = pLockEvent->m_iPercent; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_lock_info", &sInfo); } else if(pEvent->m_iEventType == EV_MESSAGE) { CMessageEvent *pMessageEvent(static_cast<CMessageEvent *>(pEvent)); DasherMessageInfo sInfo; sInfo.szMessage = pMessageEvent->m_strMessage.c_str(); sInfo.iID = pMessageEvent->m_iID; sInfo.iType = pMessageEvent->m_iType; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_message", &sInfo); } else if(pEvent->m_iEventType == EV_COMMAND) { CCommandEvent *pCommandEvent(static_cast<CCommandEvent *>(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_command", pCommandEvent->m_strCommand.c_str()); } }; void CDasherControl::WriteTrainFile(const std::string &strNewText) { if(strNewText.length() == 0) return; std::string strFilename(GetStringParameter(SP_USER_LOC) + GetStringParameter(SP_TRAIN_FILE)); int fd=open(strFilename.c_str(),O_CREAT|O_WRONLY|O_APPEND,S_IRUSR|S_IWUSR); write(fd,strNewText.c_str(),strNewText.length()); close(fd); } // TODO: Sort these methods out void CDasherControl::ExternalKeyDown(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyDown(get_time(), iButtonID); // } KeyDown(get_time(), iKeyVal); } void CDasherControl::ExternalKeyUp(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyUp(get_time(), iButtonID); // } KeyUp(get_time(), iKeyVal); } void CDasherControl::HandleParameterNotification(int iParameter) { switch(iParameter) { case SP_DASHER_FONT: if(m_pPangoCache) { m_pPangoCache->ChangeFont(GetStringParameter(SP_DASHER_FONT)); ScheduleRedraw(); } break; case BP_GLOBAL_KEYBOARD: // TODO: reimplement // if(m_pKeyboardHelper) // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); break; } } int CDasherControl::TimerEvent() { int x, y; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_pointer(gtk_widget_get_window(m_pCanvas), &x, &y, NULL); #else gdk_window_get_pointer(m_pCanvas->window, &x, &y, NULL); #endif m_pMouseInput->SetCoordinates(x, y); gdk_window_get_pointer(gdk_get_default_root_window(), &x, &y, NULL); int iRootWidth; int iRootHeight; gdk_drawable_get_size(gdk_get_default_root_window(), &iRootWidth, &iRootHeight); if(GetLongParameter(LP_YSCALE) < 10) SetLongParameter(LP_YSCALE, 10); y = (y - iRootHeight / 2); m_p1DMouseInput->SetCoordinates(y, GetLongParameter(LP_YSCALE)); NewFrame(get_time(), false); // Update our UserLog object about the current mouse position CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { // We want current canvas and window coordinates so normalization // is done properly with respect to the canvas. GdkRectangle sWindowRect; GdkRectangle sCanvasRect; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_frame_extents(gtk_widget_get_window(m_pCanvas), &sWindowRect); #else gdk_window_get_frame_extents(m_pCanvas->window, &sWindowRect); #endif pUserLog->AddWindowSize(sWindowRect.y, sWindowRect.x, sWindowRect.y + sWindowRect.height, sWindowRect.x + sWindowRect.width); if (m_pScreen != NULL) { if (m_pScreen->GetCanvasSize(&sCanvasRect)) pUserLog->AddCanvasSize(sCanvasRect.y, sCanvasRect.x, sCanvasRect.y + sCanvasRect.height, sCanvasRect.x + sCanvasRect.width); } int iMouseX = 0; int iMouseY = 0; gdk_window_get_pointer(NULL, &iMouseX, &iMouseY, NULL); // TODO: This sort of thing shouldn't be in specialised methods, move into base class somewhere pUserLog->AddMouseLocationNormalized(iMouseX, iMouseY, true, GetNats()); } return 1; // See CVS for code which used to be here } int CDasherControl::LongTimerEvent() { // std::cout << "Framerate: " << GetFramerate() << std::endl; // std::cout << "Render count: " << GetRenderCount() << std::endl; return 1; } gboolean CDasherControl::ExposeEvent() { NewFrame(get_time(), true); return 0; } gboolean CDasherControl::ButtonPressEvent(GdkEventButton *event) { // Take the focus if we click on the canvas // GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); // gboolean *returnType; // focusEvent->type = GDK_FOCUS_CHANGE; // focusEvent->window = (GdkWindow *) m_pCanvas; // focusEvent->send_event = FALSE; // focusEvent->in = TRUE; // gtk_widget_grab_focus(GTK_WIDGET(m_pCanvas)); // g_signal_emit_by_name(GTK_OBJECT(m_pCanvas), "focus_in_event", GTK_WIDGET(m_pCanvas), focusEvent, NULL, &returnType); // No - don't take the focus - give it to the text area instead if(event->type == GDK_BUTTON_PRESS) HandleClickDown(get_time(), (int)event->x, (int)event->y); else if(event->type == GDK_BUTTON_RELEASE) HandleClickUp(get_time(), (int)event->x, (int)event->y); return false; } gint CDasherControl::KeyReleaseEvent(GdkEventKey *event) { // TODO: This is seriously flawed - the semantics of of X11 Keyboard // events mean the there's no guarantee that key up/down events will // be received in pairs. if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) { // if(event->state & GDK_CONTROL_MASK) // SetLongParameter(LP_BOOSTFACTOR, 25); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) { // if(event->state & GDK_SHIFT_MASK) // SetLongParameter(LP_BOOSTFACTOR, 175); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyUp(get_time(), iKeyVal); // } } return 0; } gint CDasherControl::KeyPressEvent(GdkEventKey *event) { // if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) // SetLongParameter(LP_BOOSTFACTOR, 175); // else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) // SetLongParameter(LP_BOOSTFACTOR, 25); // else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyDown(get_time(), iKeyVal); // } // } return 0; } void CDasherControl::CanvasDestroyEvent() { // Delete the screen if(m_pScreen != NULL) { delete m_pScreen; m_pScreen = NULL; } } // Tell the logging object that a new user trial is starting. void CDasherControl::UserLogNewTrial() { CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { pUserLog->NewTrial(); } } int CDasherControl::GetFileSize(const std::string &strFileName) { struct stat sStatInfo; if(!stat(strFileName.c_str(), &sStatInfo)) return sStatInfo.st_size; else return 0; } // "C" style callbacks - these are here just because it's not possible // (or at least not easy) to connect a callback directly to a C++ // method, so we pass a pointer to th object in the user_data field // and use a wrapper function. Please do not put any functional code // here. extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data) { static_cast < CDasherControl * >(user_data)->RealizeCanvas(widget); } extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) { return static_cast < CDasherControl * >(data)->ButtonPressEvent(event); } extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { return static_cast < CDasherControl * >(data)->KeyPressEvent(event); } extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { return static_cast < CDasherControl * >(data)->CanvasConfigureEvent(); } extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData) { static_cast<CDasherControl*>(pUserData)->CanvasDestroyEvent(); } extern "C" gint key_release_event(GtkWidget *pWidget, GdkEventKey *event, gpointer pUserData) { return static_cast<CDasherControl*>(pUserData)->KeyReleaseEvent(event); } extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return static_cast < CDasherControl * >(data)->FocusEvent(widget, event); } extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data) { return ((CDasherControl*)data)->ExposeEvent(); } diff --git a/Src/Gtk2/DasherControl.h b/Src/Gtk2/DasherControl.h index 78f66a4..0a82963 100644 --- a/Src/Gtk2/DasherControl.h +++ b/Src/Gtk2/DasherControl.h @@ -1,202 +1,207 @@ #ifndef __dashercontrol_h__ #define __dashercontrol_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "PangoCache.h" #include "Canvas.h" #include "../DasherCore/SocketInput.h" #ifdef JOYSTICK #include "joystick_input.h" #endif #ifdef TILT #include "tilt_input.h" #endif #include "mouse_input.h" #include "GtkDasherControl.h" //#include "KeyboardHelper.h" //#include "../DasherCore/DasherSettingsInterface.h" #include "../DasherCore/DasherInterfaceBase.h" #include "../DasherCore/GnomeSettingsStore.h" #include "../DasherCore/UserLog.h" /// /// \brief C++ core of the Dasher GTK UI component. /// /// Class representing the Dasher UI component (ie the canvas and speed slider) /// \todo It would really be more sensible for CDasherControl to inheret from CDasherInterface rather than contain a pointer to it /// class CDasherControl : public CDasherInterfaceBase { public: /// /// \param pVBox GTK VBox to populate with the DasherControl /// component widgets. This needs to be created externally by the /// GObject wrapper and passed to the C++ class rather than being /// created internally. /// \param pDasherControl Pointer to the GObject wrapper. This is /// needed so that we can emit signals from the GObject. /// CDasherControl(GtkVBox * pVbox, GtkDasherControl * pDasherControl); ~CDasherControl(); // Event handlers // FIXME - we should probably pass all parameters to these from the "C" callbacks void SetFocus(); /// /// GTK Signal handler for the canvas getting the focus (which it gives away to the edit box) /// bool FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent); /// /// Called when the canvas gets realized (ie when internal resources have been allocated), so we can finalise setup. /// void RealizeCanvas(GtkWidget *pWidget); /// /// Called periodically by a timer. Used to prompt the interface to perform a redraw /// \todo There's rather a lot which happens in this /// function. Ideally it should just be a simple call to the core /// which then figures out whether we're paused or not etc. /// int TimerEvent(); int LongTimerEvent(); /// /// Mouse button pressed on the canvas /// gboolean ButtonPressEvent(GdkEventButton * event); /// /// Called when the canvas has been resized, prompts the (re)creation of the CCanvas object. /// int CanvasConfigureEvent(); /// /// Speed slider has been moved. /// void SliderEvent(); /// /// Called when the canvas GTK widget is destroyed, so we can free any references to it. /// void CanvasDestroyEvent(); /// /// Key press event on the canvas /// gint KeyReleaseEvent(GdkEventKey * event); gint KeyPressEvent(GdkEventKey * event); /// /// Return an array of allowed values for a string parameter. /// \param iParameter The parameter to query. /// \return A GArray of gchar* pointers to strings containing permitted values /// GArray *GetAllowedValues(int iParameter); /// /// Called by UI needs to signal a new user trial is starting. /// void UserLogNewTrial(); void ExternalKeyDown(int iKeyVal); void ExternalKeyUp(int iKeyVal); /** - * Give GameDisplay a reference to the GtkWidget - * so it can start drawing text. + * Instantiate the Game Display object with a reference to the Gtk + * table it will be populating. * * @param pGameDisplay the reference */ - void SetGameDisplay(void* pGameDisplay); + void CreateGameDisplay(void* pGameDisplay); gboolean ExposeEvent(); private: // virtual void CreateSettingsStore(); virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList); virtual void ScanColourFiles(std::vector<std::string> &vFileList); virtual void SetupPaths(); virtual void CreateModules(); virtual void SetupUI(); virtual void CreateSettingsStore(); virtual int GetFileSize(const std::string &strFileName); virtual void WriteTrainFile(const std::string &strNewText); virtual void StartTimer(); virtual void ShutdownTimer(); /// /// Pass events coming from the core to the appropriate handler. /// void ExternalEventHandler(Dasher::CEvent *pEvent); void GameMessageOut(int message, const void* messagedata); /// /// Notification from CDasherInterface that a parameter has changed /// \param iParameter The parameter which has changed /// void HandleParameterNotification(int iParameter); + /** + * The GTK implementation of the game display widget. Need to keep a + * reference so that we can initialize it, then pass it into Game + */ + GtkWidget *m_pVBox; GtkWidget *m_pCanvas; /// /// Abstracted input device object for mouse input. /// CDasherMouseInput *m_pMouseInput; CDasher1DMouseInput *m_p1DMouseInput; /// /// Cache of Pango layouts /// CPangoCache *m_pPangoCache; /// /// The CCanvas object /// CCanvas *m_pScreen; /// /// The GObject which is wrapping this class /// GtkDasherControl *m_pDasherControl; /// /// Keyboard helper class /// // CKeyboardHelper *m_pKeyboardHelper; }; #endif diff --git a/Src/Gtk2/GtkDasherControl.cpp b/Src/Gtk2/GtkDasherControl.cpp index 2bd64cc..128f8de 100644 --- a/Src/Gtk2/GtkDasherControl.cpp +++ b/Src/Gtk2/GtkDasherControl.cpp @@ -1,348 +1,348 @@ // GtkDasherControl.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherControl.h" #include "GtkDasherControl.h" #include "custom_marshal.h" #include "game_mode_helper.h" #include <gtk/gtkmarshal.h> struct _GtkDasherControlPrivate { CDasherControl *pControl; void* pGameHelper; }; typedef struct _GtkDasherControlPrivate GtkDasherControlPrivate; // Signals that this control can emit enum { DASHER_CHANGED, DASHER_START, DASHER_STOP, DASHER_EDIT_INSERT, DASHER_EDIT_DELETE, DASHER_EDIT_CONVERT, DASHER_EDIT_PROTECT, DASHER_CONTROL, DASHER_CONTEXT_REQUEST, DASHER_REQUEST_SETTINGS, DASHER_LOCK_INFO, DASHER_MESSAGE, DASHER_COMMAND, SIGNAL_NUM }; #define GTK_DASHER_CONTROL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), GTK_DASHER_TYPE_CONTROL, GtkDasherControlPrivate)); /* TODO: is it still sensible to derive from VBox, given that its just a cnavas now*/ G_DEFINE_TYPE(GtkDasherControl, gtk_dasher_control, GTK_TYPE_VBOX); static void gtk_dasher_control_finalize(GObject * pObject); static guint gtk_dasher_control_signals[SIGNAL_NUM]; /* TODO: initialise this? */ static void gtk_dasher_control_class_init(GtkDasherControlClass *pClass) { g_type_class_add_private(pClass, sizeof(GtkDasherControlPrivate)); GObjectClass *pObjectClass = (GObjectClass *) pClass; pObjectClass->finalize = gtk_dasher_control_finalize; gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_changed", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_changed), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_START] = g_signal_new("dasher_start", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_start), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_STOP] = g_signal_new("dasher_stop", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_INSERT] = g_signal_new("dasher_edit_insert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_insert), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_DELETE] = g_signal_new("dasher_edit_delete", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_delete), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_CONVERT] = g_signal_new("dasher_edit_convert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_convert), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_PROTECT] = g_signal_new("dasher_edit_protect", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_protect), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("dasher_control", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_control), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_context_request", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_context_request), NULL, NULL, g_cclosure_user_marshal_VOID__INT_INT, G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_INT); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_press_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_press_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_release_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_release_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); gtk_dasher_control_signals[DASHER_REQUEST_SETTINGS] = g_signal_new("dasher_request_settings", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_request_settings), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_LOCK_INFO] = g_signal_new("dasher_lock_info", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_lock), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_MESSAGE] = g_signal_new("dasher_message", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_message), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_COMMAND] = g_signal_new("dasher_command", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_command), NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); pClass->dasher_changed = NULL; pClass->dasher_start = NULL; pClass->dasher_stop = NULL; pClass->dasher_edit_insert = NULL; pClass->dasher_edit_delete = NULL; pClass->dasher_edit_convert = NULL; pClass->dasher_edit_protect = NULL; pClass->dasher_control = NULL; pClass->dasher_context_request = NULL; pClass->dasher_request_settings = NULL; pClass->dasher_lock = NULL; pClass->dasher_message = NULL; pClass->dasher_command = NULL; // pClass->key_press_event = gtk_dasher_control_default_key_press_handler; // pClass->key_release_event = gtk_dasher_control_default_key_release_handler; } static void gtk_dasher_control_init(GtkDasherControl *pDasherControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); pPrivate->pControl = new CDasherControl(&(pDasherControl->box), pDasherControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-press-event", G_CALLBACK(gtk_dasher_control_default_key_press_handler), pPrivate->pControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-release-event", G_CALLBACK(gtk_dasher_control_default_key_release_handler), pPrivate->pControl); } static void gtk_dasher_control_finalize(GObject *pObject) { GtkDasherControl *pDasherControl = GTK_DASHER_CONTROL(pObject); GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); /* TODO: Check that this actually gets called correctly */ /* TODO: Should just call constructor - this should just be a lightweight wrapper class */ pPrivate->pControl->StartShutdown(); delete pPrivate->pControl; // g_free(pDasherControl->private_data); } GtkWidget * gtk_dasher_control_new() { return GTK_WIDGET(g_object_new(GTK_DASHER_TYPE_CONTROL, NULL)); } void gtk_dasher_control_set_parameter_bool(GtkDasherControl *pControl, int iParameter, bool bValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBoolParameter(iParameter, bValue); } void gtk_dasher_control_set_parameter_long(GtkDasherControl *pControl, int iParameter, long lValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetLongParameter(iParameter, lValue); } void gtk_dasher_control_set_parameter_string(GtkDasherControl *pControl, int iParameter, const char *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetStringParameter(iParameter, szValue); } bool gtk_dasher_control_get_parameter_bool(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetBoolParameter(iParameter); } long gtk_dasher_control_get_parameter_long(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetLongParameter(iParameter); } void gtk_dasher_control_reset_parameter(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ResetParameter(iParameter); } const char * gtk_dasher_control_get_parameter_string(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetStringParameter(iParameter).c_str(); } GArray * gtk_dasher_control_get_allowed_values(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetAllowedValues(iParameter); }; void gtk_dasher_control_train(GtkDasherControl *pControl, const gchar *szFilename) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ImportTrainingText(szFilename); }; void gtk_dasher_control_set_context(GtkDasherControl *pControl, const gchar *szContext) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetContext(szContext); } void gtk_dasher_control_set_buffer(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBuffer(iOffset); } void gtk_dasher_control_unset_buffer(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UnsetBuffer(); } void gtk_dasher_control_set_offset(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetOffset(iOffset); } void gtk_dasher_control_register_node(GtkDasherControl *pControl, int iID, const gchar *szLabel, int iColour) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->RegisterNode(iID, szLabel, iColour); } void gtk_dasher_control_connect_node(GtkDasherControl *pControl, int iChild, int iParent, int iAfter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ConnectNode(iChild, iParent, iAfter); } void gtk_dasher_control_disconnect_node(GtkDasherControl *pControl, int iChild, int iParent) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->DisconnectNode(iChild, iParent); } void gtk_dasher_control_external_key_down(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyDown(iKeyVal); } void gtk_dasher_control_external_key_up(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyUp(iKeyVal); } void gtk_dasher_user_log_new_trial(GtkDasherControl * pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UserLogNewTrial(); } void gtk_dasher_control_set_focus(GtkDasherControl * pControl){ GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetFocus(); } // gboolean // gtk_dasher_control_default_key_press_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data){ // static_cast<CDasherControl *>(data)->KeyPressEvent(pEvent); // return FALSE; // } // gboolean // gtk_dasher_control_default_key_release_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data) { // static_cast<CDasherControl *>(data)->KeyReleaseEvent(pEvent); // return FALSE; // } gboolean gtk_dasher_control_get_module_settings(GtkDasherControl * pControl, const gchar *szModule, SModuleSettings **pSettings, gint *iCount) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetModuleSettings(szModule, pSettings, iCount); } void -gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameHelper) { +gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameDisplay) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); - pPrivate->pControl->SetGameDisplay(gameHelper); + pPrivate->pControl->CreateGameDisplay(gameDisplay); } void gtk_dasher_control_add_game_mode_string(GtkDasherControl *pControl, const gchar *szString) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddGameModeString(szString); } void gtk_dasher_control_game_messagein(GtkDasherControl *pControl, int message, void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->GameMessageIn(message, messagedata); } void gtk_dasher_control_game_helperreg(GtkDasherControl *pControl, void* gameHelper) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pGameHelper = gameHelper; } void gtk_dasher_control_game_messageout(GtkDasherControl *pControl, int message, const void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); GameModeHelper* pHelper = GAME_MODE_HELPER(pPrivate->pGameHelper); if(pHelper) game_mode_helper_message(pHelper, message, messagedata); } void gtk_dasher_control_force_pause(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->Pause(); } double gtk_dasher_control_get_framerate(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetFramerate(); } void gtk_dasher_control_add_action_button(GtkDasherControl *pControl, const gchar *szCommand) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddActionButton(szCommand); } void gtk_dasher_control_set_control_offset(GtkDasherControl *pControl, gint iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetControlOffset(iOffset); } const char * gtk_dasher_control_cl_set(GtkDasherControl *pControl, const gchar *szKey, const gchar *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->ClSet(szKey, szValue); } diff --git a/Src/Gtk2/GtkDasherControl.h b/Src/Gtk2/GtkDasherControl.h index ff8f8b1..07940b8 100644 --- a/Src/Gtk2/GtkDasherControl.h +++ b/Src/Gtk2/GtkDasherControl.h @@ -1,115 +1,114 @@ #ifndef __gtkdashercontrol_h__ #define __gtkdashercontrol_h__ #include <gtk/gtk.h> #include "../Common/ModuleSettings.h" #include "Parameters.h" #include "ControlManager.h" typedef struct _DasherLockInfo DasherLockInfo; struct _DasherLockInfo { const gchar *szMessage; gboolean bLock; gint iPercent; }; typedef struct _DasherMessageInfo DasherMessageInfo; struct _DasherMessageInfo { const gchar *szMessage; gint iID; gint iType; }; G_BEGIN_DECLS -#define GTK_DASHER_CONTROL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), GTK_DASHER_TYPE_CONTROL, GtkDasherControlPrivate)); - #define GTK_DASHER_TYPE_CONTROL (gtk_dasher_control_get_type()) #define GTK_DASHER_CONTROL(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_DASHER_TYPE_CONTROL, GtkDasherControl )) #define GTK_DASHER_CONTROL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_DASHER_TYPE_CONTROL, GtkDasherControlClass )) #define GTK_DASHER_IS_CONTROL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_DASHER_TYPE_CONTROL)) #define GTK_DASHER_IS_CONTROL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_DASHER_TYPE_CONTROL)) typedef struct _GtkDasherControl GtkDasherControl; typedef struct _GtkDasherControlClass GtkDasherControlClass; struct _GtkDasherControl { GtkVBox box; // gpointer private_data; }; struct _GtkDasherControlClass { GtkVBoxClass parent_class; // Signal handlers void (*dasher_changed) (GtkDasherControl * pDasherControl, gint iParameter, gpointer data); void (*dasher_start) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_stop) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_edit_insert) (GtkDasherControl * pDasherControl, const gchar * szText, int iOffset, gpointer data); void (*dasher_edit_delete) (GtkDasherControl * pDasherControl, const gchar * szText, int iOffset, gpointer data); void (*dasher_edit_convert) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_edit_protect) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_control) (GtkDasherControl * pDasherControl, gint iEvent, gpointer data); gboolean (*key_press_event) (GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); gboolean (*key_release_event) (GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); void (*dasher_context_request) (GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); void (*dasher_request_settings) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_lock) (GtkDasherControl * pDasherControl, gpointer pLockInfo, gpointer data); void (*dasher_message) (GtkDasherControl * pDasherControl, gpointer pLockInfo, gpointer data); void (*dasher_command) (GtkDasherControl * pDasherControl, const gchar * szText, gpointer data); }; GtkWidget *gtk_dasher_control_new(); GType gtk_dasher_control_get_type(); gboolean gtk_dasher_control_default_key_press_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); gboolean gtk_dasher_control_default_key_release_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); void gtk_dasher_control_set_parameter_bool(GtkDasherControl * pControl, int iParameter, bool bValue); void gtk_dasher_control_set_parameter_long(GtkDasherControl * pControl, int iParameter, long lValue); void gtk_dasher_control_set_parameter_string(GtkDasherControl * pControl, int iParameter, const char *szValue); bool gtk_dasher_control_get_parameter_bool(GtkDasherControl * pControl, int iParameter); long gtk_dasher_control_get_parameter_long(GtkDasherControl * pControl, int iParameter); void gtk_dasher_control_reset_parameter(GtkDasherControl * pControl, int iParameter); const char *gtk_dasher_control_get_parameter_string(GtkDasherControl * pControl, int iParameter); GArray *gtk_dasher_control_get_allowed_values(GtkDasherControl * pControl, int iParameter); void gtk_dasher_control_train(GtkDasherControl * pControl, const gchar * szFilename); void gtk_dasher_control_set_context(GtkDasherControl *pControl, const gchar *szContext); //void gtk_dasher_control_invalidate_context(GtkDasherControl *pControl, bool bForceStart); void gtk_dasher_control_set_buffer(GtkDasherControl *pControl, int iOffset); void gtk_dasher_control_set_offset(GtkDasherControl *pControl, int iOffset); void gtk_dasher_control_unset_buffer(GtkDasherControl *pControl); void gtk_dasher_control_register_node(GtkDasherControl *pControl, int iID, const gchar *szLabel, int iColour); void gtk_dasher_control_connect_node(GtkDasherControl *pControl, int iChild, int iParent, int iAfter); void gtk_dasher_control_disconnect_node(GtkDasherControl *pControl, int iChild, int iParent); void gtk_dasher_control_external_key_down(GtkDasherControl *pControl, int iKeyVal); void gtk_dasher_control_external_key_up(GtkDasherControl *pControl, int iKeyVal); gboolean gtk_dasher_control_get_module_settings(GtkDasherControl * pControl, const gchar *szModule, SModuleSettings **pSettings, gint *iCount); void gtk_dasher_control_add_game_mode_string(GtkDasherControl *pControl, const gchar *szString); void gtk_dasher_control_game_messagein(GtkDasherControl *pControl, int message, void* messagedata); /** - * Pass a reference to the GTK widget containing the game mode display down to DasherControl. + * Pass a reference to the GTK widget containing the game mode display down to DasherControl + * so that it can construct the game display UI. * @param pControl reference to GtkDasherControl instance - * @gameDisplay reference to the GTK widget containing the game display + * @gameDisplay reference to the GTK table containing the game display */ void gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameDisplay); void gtk_dasher_control_game_helperreg(GtkDasherControl *pControl, void* gameHelper); void gtk_dasher_control_game_messageout(GtkDasherControl *pControl, int message, const void* messagedata); void gtk_dasher_control_force_pause(GtkDasherControl *pControl); double gtk_dasher_control_get_framerate(GtkDasherControl *pControl); void gtk_dasher_control_add_action_button(GtkDasherControl *pControl, const gchar *szCommand); void gtk_dasher_control_set_control_offset(GtkDasherControl *pControl, gint iOffset); void gtk_dasher_user_log_new_trial(GtkDasherControl * pControl); void gtk_dasher_control_set_focus(GtkDasherControl * pControl); const gchar* gtk_dasher_control_cl_set(GtkDasherControl *pControl, const gchar *szKey, const gchar *szValue); G_END_DECLS #endif diff --git a/Src/Gtk2/Makefile.am b/Src/Gtk2/Makefile.am index bdeecd6..dd14aa5 100644 --- a/Src/Gtk2/Makefile.am +++ b/Src/Gtk2/Makefile.am @@ -1,93 +1,95 @@ LIBS = @INTLLIBS@ @LIBS@ noinst_LTLIBRARIES = libdashergtk.la libdashercontrol.la if GCONF_SCHEMAS_INSTALL noinst_PROGRAMS = generate-schema generate_schema_SOURCES = GenerateSchema.cpp endif #bin_PROGRAMS = dasher-config if WITH_GPE settings_store = gpesettings_store.cc gpesettings_store.h else settings_store = endif #dasher_config_SOURCES = \ # DasherAppSettings.cpp \ # DasherAppSettings.h \ # Preferences.cpp \ # Preferences.h \ # dasher_config.cpp \ # module_settings_window.cpp \ # module_settings_window.h# # #dasher_config_LDADD = \ # $(GTK2BUILD_LIBS) libdashercontrol_la_SOURCES = \ Canvas.cpp \ Canvas.h \ + GtkGameDisplay.cpp \ + GtkGameDisplay.h \ DasherControl.cpp \ DasherControl.h \ GtkDasherControl.cpp \ GtkDasherControl.h \ KeyboardHelper.cpp \ KeyboardHelper.h \ PangoCache.cpp \ PangoCache.h \ Timer.cpp \ Timer.h \ custom_marshal.cpp \ custom_marshal.h \ game_mode_helper.cpp \ game_mode_helper.h \ joystick_input.h \ mouse_input.h \ $(settings_store) libdashergtk_la_SOURCES = \ DasherAppSettings.cpp \ DasherAppSettings.h \ GtkDasherControl.h \ Preferences.cpp \ Preferences.h \ dasher.h \ dasher_action.cpp \ dasher_action.h \ dasher_action_keyboard.cpp \ dasher_action_keyboard.h \ dasher_action_keyboard_maemo.cpp \ dasher_action_keyboard_maemo.h \ dasher_action_script.cpp \ dasher_action_script.h \ dasher_action_speech.cpp \ dasher_action_speech.h \ dasher_buffer_set.cpp \ dasher_buffer_set.h \ dasher_editor.cpp \ dasher_editor.h \ dasher_editor_external.cpp \ dasher_editor_external.h \ dasher_editor_internal.cpp \ dasher_editor_internal.h \ dasher_external_buffer.cpp \ dasher_external_buffer.h \ dasher_internal_buffer.cpp \ dasher_internal_buffer.h \ dasher_lock_dialogue.cpp \ dasher_lock_dialogue.h \ dasher_maemo_helper.cpp \ dasher_maemo_helper.h \ dasher_main.cpp \ dasher_main.h \ module_settings_window.cpp \ module_settings_window.h libdashergtk_la_LIBADD = @SPEECH_SOURCES@ libdashergtk_la_DEPENDENCIES = @SPEECH_SOURCES@ AM_CXXFLAGS = -I$(srcdir)/../DasherCore -DPROGDATA=\"$(pkgdatadir)\" -I../../intl -I$(top_srcdir)/intl $(GTK2BUILD_CFLAGS) AM_CFLAGS = $(GTK2_CFLAGS) diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 2ff2812..37d30b8 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -75,1030 +75,1033 @@ static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); pPrivate->pGameDisplay = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "GameDisplay")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // /** * Clear all text out of the dasher editor. * @param pSelf a reference to an instance of DasherMain */ void clear_dasher_editor_text(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } /** * Start game mode, specify the text to play with, and clear out any text in the dasher editor. * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. * * @param pGameTextFilePath - the absolute path to the text file to play with * @param pSelf - a reference to an instance of DasherMain */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkDasherControl *pControl = GTK_DASHER_CONTROL(pPrivate->pDasherWidget); + gtk_dasher_control_set_game_display(pControl, pPrivate->pGameDisplay); + gtk_widget_set_visible(GTK_WIDGET(pPrivate->pGameDisplay), true); + dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); - + dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); clear_dasher_editor_text(pSelf); } /** * Event handler which displays a standard GTK file dialog. The dialog allows the user * to specify a text file to play game mode with. * * @param pButton the button that fired the event * @param pWidget reference needed by GTK for callback signature * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references * to the dialog's parent window and an instance of DasherMain */ void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } /** * Toggle game mode on and off. Toggling on causes a dialog box to be displayed * welcoming the user to game mode and prompting them to specify a file to play with. * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core * to respond appropriately. * * @param pSelf a reference to an instance of DasherMain */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); GtkWidget *pCancelButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); //g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); clear_dasher_editor_text(pSelf); } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; }
rgee/HFOSS-Dasher
cfd1ab09e9a5db5b38eb59353bebe59c7bdc0d91
One step away from instantiating CGameDisplay. Lots of digging through GTK code.
diff --git a/Data/GUI/dasher.traditional.ui b/Data/GUI/dasher.traditional.ui index 1c4c3b4..d7e1f86 100644 --- a/Data/GUI/dasher.traditional.ui +++ b/Data/GUI/dasher.traditional.ui @@ -1,461 +1,523 @@ <?xml version="1.0"?> <!--*- mode: xml -*--> <interface> <object class="GtkAdjustment" id="adjustment1"> <property name="upper">8</property> <property name="lower">0.1</property> <property name="page_increment">1</property> <property name="step_increment">0.1</property> <property name="page_size">0</property> <property name="value">1</property> </object> <object class="GtkUIManager" id="uimanager1"> <child> <object class="GtkActionGroup" id="actiongroup1"> <child> <object class="GtkAction" id="file_menu"> <property name="label" translatable="yes">_File</property> </object> </child> <child> <object class="GtkAction" id="action_new"> <property name="stock_id">gtk-new</property> <property name="tooltip" translatable="yes">New file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_open"> <property name="stock_id">gtk-open</property> <property name="tooltip" translatable="yes">Open file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_save"> <property name="stock_id">gtk-save</property> <property name="tooltip" translatable="yes">Save file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_saveas"> <property name="stock_id">gtk-save-as</property> <property name="tooltip" translatable="yes">Save file as</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_append"> <property name="name">action_append</property> <property name="label" translatable="yes">A_ppend to file…</property> </object> </child> <child> <object class="GtkAction" id="action_import"> <property name="label" translatable="yes">_Import Training Text…</property> <signal name="activate" handler="dasher_main_cb_import"/> </object> </child> <child> <object class="GtkAction" id="action_quit"> <property name="stock_id">gtk-quit</property> <property name="tooltip" translatable="yes">Quit</property> <signal name="activate" handler="dasher_main_cb_quit"/> </object> </child> <child> <object class="GtkAction" id="edit_menu"> <property name="label" translatable="yes">_Edit</property> </object> </child> <child> <object class="GtkAction" id="action_cut"> <property name="stock_id">gtk-cut</property> <property name="tooltip" translatable="yes">Cut</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copy"> <property name="stock_id">gtk-copy</property> <property name="tooltip" translatable="yes">Copy</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copyall"> <property name="label" translatable="yes">Copy _All</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_paste"> <property name="stock_id">gtk-paste</property> <property name="tooltip" translatable="yes">Paste</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_preferences"> <property name="stock_id">gtk-preferences</property> <property name="label" translatable="yes">Pr_eferences…</property> <property name="tooltip" translatable="yes">Preferences</property> <signal name="activate" handler="dasher_main_cb_preferences"/> </object> <accelerator key="S" modifiers="GDK_CONTROL_MASK | GDK_SHIFT_MASK"/> </child> <child> <object class="GtkAction" id="help_menu"> <property name="label" translatable="yes">_Help</property> </object> </child> <child> <object class="GtkAction" id="action_help"> <property name="stock_id">gtk-help</property> <property name="label" translatable="yes">_Contents…</property> <property name="tooltip" translatable="yes">Help</property> <signal name="activate" handler="dasher_main_cb_help"/> </object> <accelerator key="F1" modifiers="0"/> </child> <child> <object class="GtkAction" id="action_about"> <property name="stock_id">gtk-about</property> <property name="label" translatable="yes">_About…</property> <signal name="activate" handler="dasher_main_cb_about"/> </object> </child> <child> <object class="GtkAction" id="action_toggle_game_mode"> <property name="stock_id">action_toggle_game_mode</property> <property name="tooltip" translatable="yes">_Game Mode</property> <property name = "label" translatable="yes">_Game Mode</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> </object> </child> <ui> <menubar name="dasher_menu_bar"> <menu action="file_menu"> <menuitem action="action_new"/> <menuitem action="action_open"/> <menuitem action="action_save"/> <menuitem action="action_saveas"/> <menuitem action="action_append"/> <menuitem action="action_toggle_game_mode"/> <separator/> <menuitem action="action_import"/> <menuitem action="action_quit"/> </menu> <menu action="edit_menu"> <menuitem action="action_cut"/> <menuitem action="action_copy"/> <menuitem action="action_copyall"/> <menuitem action="action_paste"/> <separator/> <menuitem action="action_preferences"/> </menu> <menu action="help_menu"> <menuitem action="action_help"/> <menuitem action="action_about"/> </menu> </menubar> <toolbar name="dasher_tool_bar"> <toolitem action="action_new"/> <toolitem action="action_open"/> <toolitem action="action_save"/> <toolitem action="action_saveas"/> <separator/> <toolitem action="action_cut"/> <toolitem action="action_copy"/> <toolitem action="action_paste"/> <separator/> <toolitem action="action_preferences"/> <toolitem action="action_help"/> <separator/> <toolitem action="action_quit"/> </toolbar> </ui> </object> <object class="GtkWindow" id="window"> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="events">GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">Dasher</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_NONE</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">False</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <signal handler="dasher_main_cb_window_close" name="delete_event"/> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkMenuBar" constructor="uimanager1" id="dasher_menu_bar"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Quit</property> <property name="pack_direction">GTK_PACK_DIRECTION_LTR</property> <property name="child_pack_direction">GTK_PACK_DIRECTION_LTR</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkToolbar" constructor="uimanager1" id="dasher_tool_bar"> <property name="toolbar_style">GTK_TOOLBAR_ICONS</property> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkVPaned" id="main_divider"> <property name="visible">True</property> <property name="position">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="DasherEditorInternal" id="DasherEditor"> <property name="visible">True</property> <property name="can_focus">True</property> <signal handler="dasher_main_cb_filename_changed" name="filename_changed"/> <signal handler="dasher_main_cb_buffer_changed" name="buffer_changed"/> <signal handler="dasher_main_cb_context_changed" name="context_changed"/> </object> <packing> <property name="shrink">True</property> <property name="resize">False</property> </packing> </child> <child> - <object class="GtkDasherControl" id="DasherControl"> - <property name="width_request">200</property> - <property name="height_request">200</property> - <property name="visible">True</property> - <signal handler="parameter_notification" name="dasher_changed"/> - <signal handler="handle_start_event" name="dasher_start"/> - <signal handler="handle_stop_event" name="dasher_stop"/> - <signal handler="handle_control_event" name="dasher_control"/> - <signal handler="gtk2_edit_output_callback" name="dasher_edit_insert"/> - <signal handler="gtk2_edit_delete_callback" name="dasher_edit_delete"/> - <signal handler="handle_context_request" name="dasher_context_request"/> - <signal handler="handle_request_settings" name="dasher_request_settings"/> - <signal handler="focus_in_event" name="focus_in_event"/> - <signal handler="on_lock_info" name="dasher_lock_info"/> - <signal handler="on_message" name="dasher_message"/> - <signal handler="convert_cb" name="dasher_edit_convert"/> - <signal handler="protect_cb" name="dasher_edit_protect"/> - <signal handler="on_command" name="dasher_command"/> - <signal handler="test_focus_handler" name="focus-in-event"/> + + + + <object class = "GtkTable" id = "BottomTable"> + + <property name = "n-columns">1</property> + <property name = "n-rows">2</property> + <property name = "row-spacing">0</property> + <property name = "column-spacing">0</property> + <property name = "visible">True</property> + + <child> + + <object class = "GtkTable" id = "GameDisplay"> + + <property name = "n-columns">2</property> + <property name = "n-rows">1</property> + <property name = "row-spacing">0</property> + <property name = "column-spacing">0</property> + <property name = "visible">True</property> + + <child> + + <object class = "GtkLabel" id = "GameChunkDisplay"> + <property name = "visible">True</property> + <property name = "label">This is a test</property> + <property name = "xalign">0</property> + <property name="use_markup">True</property> + </object> + + <packing> + <property name = "left-attach">1</property> + </packing> + + </child> + <child> + <placeholder/> + <!-- Add more table cells to implement new Game Mode display elements" --> + </child> + + </object> + + <packing> + <property name = "y-options">GTK_FILL</property> + <property name = "x-padding">10</property> + <property name = "y-padding">10</property> + </packing> + + </child> + + <child> + + <object class="GtkDasherControl" id="DasherControl"> + <property name="width_request">200</property> + <property name="height_request">200</property> + <property name="visible">True</property> + <signal handler="parameter_notification" name="dasher_changed"/> + <signal handler="handle_start_event" name="dasher_start"/> + <signal handler="handle_stop_event" name="dasher_stop"/> + <signal handler="handle_control_event" name="dasher_control"/> + <signal handler="gtk2_edit_output_callback" name="dasher_edit_insert"/> + <signal handler="gtk2_edit_delete_callback" name="dasher_edit_delete"/> + <signal handler="handle_context_request" name="dasher_context_request"/> + <signal handler="handle_request_settings" name="dasher_request_settings"/> + <signal handler="focus_in_event" name="focus_in_event"/> + <signal handler="on_lock_info" name="dasher_lock_info"/> + <signal handler="on_message" name="dasher_message"/> + <signal handler="convert_cb" name="dasher_edit_convert"/> + <signal handler="protect_cb" name="dasher_edit_protect"/> + <signal handler="on_command" name="dasher_command"/> + <signal handler="test_focus_handler" name="focus-in-event"/> + </object> + + <packing> + <property name = "top-attach">1</property> + <property name = "bottom-attach">2</property> + </packing> + + + </child> + + </object> - <packing> - <property name="shrink">True</property> - <property name="resize">True</property> - </packing> + + + </child> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkHBox" id="hbox8"> <property name="border_width">2</property> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">2</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkLabel" id="label109"> <property name="visible">True</property> <property name="label" translatable="yes">Speed:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbutton1"> <property name="width_request">64</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="climb_rate">0.10000000149</property> <property name="digits">1</property> <property name="numeric">True</property> <property name="update_policy">GTK_UPDATE_IF_VALID</property> <property name="snap_to_ticks">False</property> <property name="wrap">False</property> <property name="adjustment">adjustment1</property> <signal handler="speed_changed" name="value-changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label110"> <property name="visible">True</property> <property name="label" translatable="yes">Alphabet:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkComboBox" id="combobox1"> <property name="width_request">32</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="add_tearoffs">False</property> <property name="focus_on_click">True</property> <signal handler="alphabet_combo_changed" name="changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">True</property> </packing> </child> </object> </child> </object> <object class="GtkWindow" id="lock_window"> <property name="visible">True</property> <property name="title" translatable="yes">Please Wait…</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">True</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <child> <object class="GtkVBox" id="vbox43"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkLabel" id="lock_message"> <property name="visible">True</property> <property name="label"/> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">0</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> </object> <packing> <property name="padding">8</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkAlignment" id="alignment38"> <property name="border_width">8</property> <property name="visible">True</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xscale">1</property> <property name="yscale">1</property> <property name="top_padding">0</property> <property name="bottom_padding">0</property> <property name="left_padding">0</property> <property name="right_padding">0</property> <child> <object class="GtkProgressBar" id="lock_progress"> <property name="visible">True</property> <property name="orientation">GTK_PROGRESS_LEFT_TO_RIGHT</property> <property name="fraction">0</property> <property name="pulse_step">0.10000000149</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> </object> </child> </object> </interface> diff --git a/Src/Gtk2/DasherControl.h b/Src/Gtk2/DasherControl.h index 7a3ab37..78f66a4 100644 --- a/Src/Gtk2/DasherControl.h +++ b/Src/Gtk2/DasherControl.h @@ -1,194 +1,202 @@ #ifndef __dashercontrol_h__ #define __dashercontrol_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "PangoCache.h" #include "Canvas.h" #include "../DasherCore/SocketInput.h" #ifdef JOYSTICK #include "joystick_input.h" #endif #ifdef TILT #include "tilt_input.h" #endif #include "mouse_input.h" #include "GtkDasherControl.h" //#include "KeyboardHelper.h" //#include "../DasherCore/DasherSettingsInterface.h" #include "../DasherCore/DasherInterfaceBase.h" #include "../DasherCore/GnomeSettingsStore.h" #include "../DasherCore/UserLog.h" /// /// \brief C++ core of the Dasher GTK UI component. /// /// Class representing the Dasher UI component (ie the canvas and speed slider) /// \todo It would really be more sensible for CDasherControl to inheret from CDasherInterface rather than contain a pointer to it /// class CDasherControl : public CDasherInterfaceBase { public: /// /// \param pVBox GTK VBox to populate with the DasherControl /// component widgets. This needs to be created externally by the /// GObject wrapper and passed to the C++ class rather than being /// created internally. /// \param pDasherControl Pointer to the GObject wrapper. This is /// needed so that we can emit signals from the GObject. /// CDasherControl(GtkVBox * pVbox, GtkDasherControl * pDasherControl); ~CDasherControl(); // Event handlers // FIXME - we should probably pass all parameters to these from the "C" callbacks void SetFocus(); /// /// GTK Signal handler for the canvas getting the focus (which it gives away to the edit box) /// bool FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent); /// /// Called when the canvas gets realized (ie when internal resources have been allocated), so we can finalise setup. /// void RealizeCanvas(GtkWidget *pWidget); /// /// Called periodically by a timer. Used to prompt the interface to perform a redraw /// \todo There's rather a lot which happens in this /// function. Ideally it should just be a simple call to the core /// which then figures out whether we're paused or not etc. /// int TimerEvent(); int LongTimerEvent(); /// /// Mouse button pressed on the canvas /// gboolean ButtonPressEvent(GdkEventButton * event); /// /// Called when the canvas has been resized, prompts the (re)creation of the CCanvas object. /// int CanvasConfigureEvent(); /// /// Speed slider has been moved. /// void SliderEvent(); /// /// Called when the canvas GTK widget is destroyed, so we can free any references to it. /// void CanvasDestroyEvent(); /// /// Key press event on the canvas /// gint KeyReleaseEvent(GdkEventKey * event); gint KeyPressEvent(GdkEventKey * event); /// /// Return an array of allowed values for a string parameter. /// \param iParameter The parameter to query. /// \return A GArray of gchar* pointers to strings containing permitted values /// GArray *GetAllowedValues(int iParameter); /// /// Called by UI needs to signal a new user trial is starting. /// void UserLogNewTrial(); void ExternalKeyDown(int iKeyVal); void ExternalKeyUp(int iKeyVal); + + /** + * Give GameDisplay a reference to the GtkWidget + * so it can start drawing text. + * + * @param pGameDisplay the reference + */ + void SetGameDisplay(void* pGameDisplay); gboolean ExposeEvent(); private: // virtual void CreateSettingsStore(); virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList); virtual void ScanColourFiles(std::vector<std::string> &vFileList); virtual void SetupPaths(); virtual void CreateModules(); virtual void SetupUI(); virtual void CreateSettingsStore(); virtual int GetFileSize(const std::string &strFileName); virtual void WriteTrainFile(const std::string &strNewText); virtual void StartTimer(); virtual void ShutdownTimer(); /// /// Pass events coming from the core to the appropriate handler. /// void ExternalEventHandler(Dasher::CEvent *pEvent); void GameMessageOut(int message, const void* messagedata); /// /// Notification from CDasherInterface that a parameter has changed /// \param iParameter The parameter which has changed /// void HandleParameterNotification(int iParameter); GtkWidget *m_pVBox; GtkWidget *m_pCanvas; /// /// Abstracted input device object for mouse input. /// CDasherMouseInput *m_pMouseInput; CDasher1DMouseInput *m_p1DMouseInput; /// /// Cache of Pango layouts /// CPangoCache *m_pPangoCache; /// /// The CCanvas object /// CCanvas *m_pScreen; /// /// The GObject which is wrapping this class /// GtkDasherControl *m_pDasherControl; /// /// Keyboard helper class /// // CKeyboardHelper *m_pKeyboardHelper; }; #endif diff --git a/Src/Gtk2/GtkDasherControl.cpp b/Src/Gtk2/GtkDasherControl.cpp index 230bd7f..2bd64cc 100644 --- a/Src/Gtk2/GtkDasherControl.cpp +++ b/Src/Gtk2/GtkDasherControl.cpp @@ -1,342 +1,348 @@ // GtkDasherControl.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherControl.h" #include "GtkDasherControl.h" #include "custom_marshal.h" #include "game_mode_helper.h" #include <gtk/gtkmarshal.h> struct _GtkDasherControlPrivate { CDasherControl *pControl; void* pGameHelper; }; typedef struct _GtkDasherControlPrivate GtkDasherControlPrivate; // Signals that this control can emit enum { DASHER_CHANGED, DASHER_START, DASHER_STOP, DASHER_EDIT_INSERT, DASHER_EDIT_DELETE, DASHER_EDIT_CONVERT, DASHER_EDIT_PROTECT, DASHER_CONTROL, DASHER_CONTEXT_REQUEST, DASHER_REQUEST_SETTINGS, DASHER_LOCK_INFO, DASHER_MESSAGE, DASHER_COMMAND, SIGNAL_NUM }; #define GTK_DASHER_CONTROL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), GTK_DASHER_TYPE_CONTROL, GtkDasherControlPrivate)); /* TODO: is it still sensible to derive from VBox, given that its just a cnavas now*/ G_DEFINE_TYPE(GtkDasherControl, gtk_dasher_control, GTK_TYPE_VBOX); static void gtk_dasher_control_finalize(GObject * pObject); static guint gtk_dasher_control_signals[SIGNAL_NUM]; /* TODO: initialise this? */ static void gtk_dasher_control_class_init(GtkDasherControlClass *pClass) { g_type_class_add_private(pClass, sizeof(GtkDasherControlPrivate)); GObjectClass *pObjectClass = (GObjectClass *) pClass; pObjectClass->finalize = gtk_dasher_control_finalize; gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_changed", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_changed), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_START] = g_signal_new("dasher_start", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_start), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_STOP] = g_signal_new("dasher_stop", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_INSERT] = g_signal_new("dasher_edit_insert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_insert), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_DELETE] = g_signal_new("dasher_edit_delete", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_delete), NULL, NULL, g_cclosure_user_marshal_VOID__STRING_INT, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_INT); gtk_dasher_control_signals[DASHER_EDIT_CONVERT] = g_signal_new("dasher_edit_convert", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_convert), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_EDIT_PROTECT] = g_signal_new("dasher_edit_protect", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_edit_protect), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("dasher_control", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_control), NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); gtk_dasher_control_signals[DASHER_CHANGED] = g_signal_new("dasher_context_request", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_context_request), NULL, NULL, g_cclosure_user_marshal_VOID__INT_INT, G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_INT); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_press_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_press_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); // gtk_dasher_control_signals[DASHER_CONTROL] = g_signal_new("key_release_event", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, key_release_event), NULL, NULL, gtk_marshal_BOOLEAN__POINTER, G_TYPE_BOOLEAN, 1, GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE); gtk_dasher_control_signals[DASHER_REQUEST_SETTINGS] = g_signal_new("dasher_request_settings", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_request_settings), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); gtk_dasher_control_signals[DASHER_LOCK_INFO] = g_signal_new("dasher_lock_info", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_lock), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_MESSAGE] = g_signal_new("dasher_message", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_message), NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); gtk_dasher_control_signals[DASHER_COMMAND] = g_signal_new("dasher_command", G_TYPE_FROM_CLASS(pClass), static_cast < GSignalFlags > (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(GtkDasherControlClass, dasher_command), NULL, NULL, g_cclosure_marshal_VOID__STRING, G_TYPE_NONE, 1, G_TYPE_STRING); pClass->dasher_changed = NULL; pClass->dasher_start = NULL; pClass->dasher_stop = NULL; pClass->dasher_edit_insert = NULL; pClass->dasher_edit_delete = NULL; pClass->dasher_edit_convert = NULL; pClass->dasher_edit_protect = NULL; pClass->dasher_control = NULL; pClass->dasher_context_request = NULL; pClass->dasher_request_settings = NULL; pClass->dasher_lock = NULL; pClass->dasher_message = NULL; pClass->dasher_command = NULL; // pClass->key_press_event = gtk_dasher_control_default_key_press_handler; // pClass->key_release_event = gtk_dasher_control_default_key_release_handler; } static void gtk_dasher_control_init(GtkDasherControl *pDasherControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); pPrivate->pControl = new CDasherControl(&(pDasherControl->box), pDasherControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-press-event", G_CALLBACK(gtk_dasher_control_default_key_press_handler), pPrivate->pControl); // g_signal_connect(G_OBJECT(pDasherControl), "key-release-event", G_CALLBACK(gtk_dasher_control_default_key_release_handler), pPrivate->pControl); } static void gtk_dasher_control_finalize(GObject *pObject) { GtkDasherControl *pDasherControl = GTK_DASHER_CONTROL(pObject); GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pDasherControl); /* TODO: Check that this actually gets called correctly */ /* TODO: Should just call constructor - this should just be a lightweight wrapper class */ pPrivate->pControl->StartShutdown(); delete pPrivate->pControl; // g_free(pDasherControl->private_data); } GtkWidget * gtk_dasher_control_new() { return GTK_WIDGET(g_object_new(GTK_DASHER_TYPE_CONTROL, NULL)); } void gtk_dasher_control_set_parameter_bool(GtkDasherControl *pControl, int iParameter, bool bValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBoolParameter(iParameter, bValue); } void gtk_dasher_control_set_parameter_long(GtkDasherControl *pControl, int iParameter, long lValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetLongParameter(iParameter, lValue); } void gtk_dasher_control_set_parameter_string(GtkDasherControl *pControl, int iParameter, const char *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetStringParameter(iParameter, szValue); } bool gtk_dasher_control_get_parameter_bool(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetBoolParameter(iParameter); } long gtk_dasher_control_get_parameter_long(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetLongParameter(iParameter); } void gtk_dasher_control_reset_parameter(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ResetParameter(iParameter); } const char * gtk_dasher_control_get_parameter_string(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetStringParameter(iParameter).c_str(); } GArray * gtk_dasher_control_get_allowed_values(GtkDasherControl *pControl, int iParameter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetAllowedValues(iParameter); }; void gtk_dasher_control_train(GtkDasherControl *pControl, const gchar *szFilename) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ImportTrainingText(szFilename); }; void gtk_dasher_control_set_context(GtkDasherControl *pControl, const gchar *szContext) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetContext(szContext); } void gtk_dasher_control_set_buffer(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetBuffer(iOffset); } void gtk_dasher_control_unset_buffer(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UnsetBuffer(); } void gtk_dasher_control_set_offset(GtkDasherControl *pControl, int iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetOffset(iOffset); } void gtk_dasher_control_register_node(GtkDasherControl *pControl, int iID, const gchar *szLabel, int iColour) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->RegisterNode(iID, szLabel, iColour); } void gtk_dasher_control_connect_node(GtkDasherControl *pControl, int iChild, int iParent, int iAfter) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ConnectNode(iChild, iParent, iAfter); } void gtk_dasher_control_disconnect_node(GtkDasherControl *pControl, int iChild, int iParent) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->DisconnectNode(iChild, iParent); } void gtk_dasher_control_external_key_down(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyDown(iKeyVal); } void gtk_dasher_control_external_key_up(GtkDasherControl *pControl, int iKeyVal) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->ExternalKeyUp(iKeyVal); } void gtk_dasher_user_log_new_trial(GtkDasherControl * pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->UserLogNewTrial(); } void gtk_dasher_control_set_focus(GtkDasherControl * pControl){ GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetFocus(); } // gboolean // gtk_dasher_control_default_key_press_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data){ // static_cast<CDasherControl *>(data)->KeyPressEvent(pEvent); // return FALSE; // } // gboolean // gtk_dasher_control_default_key_release_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data) { // static_cast<CDasherControl *>(data)->KeyReleaseEvent(pEvent); // return FALSE; // } gboolean gtk_dasher_control_get_module_settings(GtkDasherControl * pControl, const gchar *szModule, SModuleSettings **pSettings, gint *iCount) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetModuleSettings(szModule, pSettings, iCount); } +void +gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameHelper) { + GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); + pPrivate->pControl->SetGameDisplay(gameHelper); +} + void gtk_dasher_control_add_game_mode_string(GtkDasherControl *pControl, const gchar *szString) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddGameModeString(szString); } void gtk_dasher_control_game_messagein(GtkDasherControl *pControl, int message, void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->GameMessageIn(message, messagedata); } void gtk_dasher_control_game_helperreg(GtkDasherControl *pControl, void* gameHelper) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pGameHelper = gameHelper; } void gtk_dasher_control_game_messageout(GtkDasherControl *pControl, int message, const void* messagedata) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); GameModeHelper* pHelper = GAME_MODE_HELPER(pPrivate->pGameHelper); if(pHelper) game_mode_helper_message(pHelper, message, messagedata); } void gtk_dasher_control_force_pause(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->Pause(); } double gtk_dasher_control_get_framerate(GtkDasherControl *pControl) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->GetFramerate(); } void gtk_dasher_control_add_action_button(GtkDasherControl *pControl, const gchar *szCommand) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->AddActionButton(szCommand); } void gtk_dasher_control_set_control_offset(GtkDasherControl *pControl, gint iOffset) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); pPrivate->pControl->SetControlOffset(iOffset); } const char * gtk_dasher_control_cl_set(GtkDasherControl *pControl, const gchar *szKey, const gchar *szValue) { GtkDasherControlPrivate *pPrivate = GTK_DASHER_CONTROL_GET_PRIVATE(pControl); return pPrivate->pControl->ClSet(szKey, szValue); } diff --git a/Src/Gtk2/GtkDasherControl.h b/Src/Gtk2/GtkDasherControl.h index 0a22c87..ff8f8b1 100644 --- a/Src/Gtk2/GtkDasherControl.h +++ b/Src/Gtk2/GtkDasherControl.h @@ -1,103 +1,115 @@ #ifndef __gtkdashercontrol_h__ #define __gtkdashercontrol_h__ #include <gtk/gtk.h> #include "../Common/ModuleSettings.h" #include "Parameters.h" #include "ControlManager.h" typedef struct _DasherLockInfo DasherLockInfo; struct _DasherLockInfo { const gchar *szMessage; gboolean bLock; gint iPercent; }; typedef struct _DasherMessageInfo DasherMessageInfo; struct _DasherMessageInfo { const gchar *szMessage; gint iID; gint iType; }; G_BEGIN_DECLS + +#define GTK_DASHER_CONTROL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), GTK_DASHER_TYPE_CONTROL, GtkDasherControlPrivate)); + #define GTK_DASHER_TYPE_CONTROL (gtk_dasher_control_get_type()) #define GTK_DASHER_CONTROL(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_DASHER_TYPE_CONTROL, GtkDasherControl )) #define GTK_DASHER_CONTROL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_DASHER_TYPE_CONTROL, GtkDasherControlClass )) #define GTK_DASHER_IS_CONTROL(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_DASHER_TYPE_CONTROL)) #define GTK_DASHER_IS_CONTROL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_DASHER_TYPE_CONTROL)) typedef struct _GtkDasherControl GtkDasherControl; typedef struct _GtkDasherControlClass GtkDasherControlClass; struct _GtkDasherControl { GtkVBox box; // gpointer private_data; }; struct _GtkDasherControlClass { GtkVBoxClass parent_class; // Signal handlers void (*dasher_changed) (GtkDasherControl * pDasherControl, gint iParameter, gpointer data); void (*dasher_start) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_stop) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_edit_insert) (GtkDasherControl * pDasherControl, const gchar * szText, int iOffset, gpointer data); void (*dasher_edit_delete) (GtkDasherControl * pDasherControl, const gchar * szText, int iOffset, gpointer data); void (*dasher_edit_convert) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_edit_protect) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_control) (GtkDasherControl * pDasherControl, gint iEvent, gpointer data); gboolean (*key_press_event) (GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); gboolean (*key_release_event) (GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); void (*dasher_context_request) (GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); void (*dasher_request_settings) (GtkDasherControl * pDasherControl, gpointer data); void (*dasher_lock) (GtkDasherControl * pDasherControl, gpointer pLockInfo, gpointer data); void (*dasher_message) (GtkDasherControl * pDasherControl, gpointer pLockInfo, gpointer data); void (*dasher_command) (GtkDasherControl * pDasherControl, const gchar * szText, gpointer data); }; GtkWidget *gtk_dasher_control_new(); GType gtk_dasher_control_get_type(); gboolean gtk_dasher_control_default_key_press_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); gboolean gtk_dasher_control_default_key_release_handler(GtkDasherControl *pDasherControl, GdkEventKey *pEvent, gpointer data); void gtk_dasher_control_set_parameter_bool(GtkDasherControl * pControl, int iParameter, bool bValue); void gtk_dasher_control_set_parameter_long(GtkDasherControl * pControl, int iParameter, long lValue); void gtk_dasher_control_set_parameter_string(GtkDasherControl * pControl, int iParameter, const char *szValue); bool gtk_dasher_control_get_parameter_bool(GtkDasherControl * pControl, int iParameter); long gtk_dasher_control_get_parameter_long(GtkDasherControl * pControl, int iParameter); void gtk_dasher_control_reset_parameter(GtkDasherControl * pControl, int iParameter); const char *gtk_dasher_control_get_parameter_string(GtkDasherControl * pControl, int iParameter); GArray *gtk_dasher_control_get_allowed_values(GtkDasherControl * pControl, int iParameter); void gtk_dasher_control_train(GtkDasherControl * pControl, const gchar * szFilename); void gtk_dasher_control_set_context(GtkDasherControl *pControl, const gchar *szContext); //void gtk_dasher_control_invalidate_context(GtkDasherControl *pControl, bool bForceStart); void gtk_dasher_control_set_buffer(GtkDasherControl *pControl, int iOffset); void gtk_dasher_control_set_offset(GtkDasherControl *pControl, int iOffset); void gtk_dasher_control_unset_buffer(GtkDasherControl *pControl); void gtk_dasher_control_register_node(GtkDasherControl *pControl, int iID, const gchar *szLabel, int iColour); void gtk_dasher_control_connect_node(GtkDasherControl *pControl, int iChild, int iParent, int iAfter); void gtk_dasher_control_disconnect_node(GtkDasherControl *pControl, int iChild, int iParent); void gtk_dasher_control_external_key_down(GtkDasherControl *pControl, int iKeyVal); void gtk_dasher_control_external_key_up(GtkDasherControl *pControl, int iKeyVal); gboolean gtk_dasher_control_get_module_settings(GtkDasherControl * pControl, const gchar *szModule, SModuleSettings **pSettings, gint *iCount); void gtk_dasher_control_add_game_mode_string(GtkDasherControl *pControl, const gchar *szString); void gtk_dasher_control_game_messagein(GtkDasherControl *pControl, int message, void* messagedata); + +/** + * Pass a reference to the GTK widget containing the game mode display down to DasherControl. + * @param pControl reference to GtkDasherControl instance + * @gameDisplay reference to the GTK widget containing the game display + */ +void gtk_dasher_control_set_game_display(GtkDasherControl *pControl, void* gameDisplay); + + void gtk_dasher_control_game_helperreg(GtkDasherControl *pControl, void* gameHelper); void gtk_dasher_control_game_messageout(GtkDasherControl *pControl, int message, const void* messagedata); void gtk_dasher_control_force_pause(GtkDasherControl *pControl); double gtk_dasher_control_get_framerate(GtkDasherControl *pControl); void gtk_dasher_control_add_action_button(GtkDasherControl *pControl, const gchar *szCommand); void gtk_dasher_control_set_control_offset(GtkDasherControl *pControl, gint iOffset); void gtk_dasher_user_log_new_trial(GtkDasherControl * pControl); void gtk_dasher_control_set_focus(GtkDasherControl * pControl); const gchar* gtk_dasher_control_cl_set(GtkDasherControl *pControl, const gchar *szKey, const gchar *szValue); G_END_DECLS #endif diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 408b70c..2ff2812 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -1,1096 +1,1100 @@ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <utility> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #ifdef WITH_MAEMOFULLSCREEN #include <hildon-widgets/hildon-program.h> #endif #include <unistd.h> #include "GtkDasherControl.h" #include "dasher_lock_dialogue.h" #ifdef WITH_MAEMO #include "dasher_maemo_helper.h" #endif #include "dasher_main.h" #include "dasher_editor.h" #include "dasher_editor_internal.h" #include "dasher_editor_external.h" /* Static instance of singleton, USE SPARINGLY */ static DasherMain *g_pDasherMain = NULL; // TODO: The following global variable makes control mode editing work // - this needs to be sorted out properly. static gboolean g_bSend = true; enum { REALIZED, SIGNAL_NUM }; static guint dasher_main_signals[SIGNAL_NUM] = { 0 }; G_DEFINE_TYPE(DasherMain, dasher_main, G_TYPE_OBJECT); static void dasher_main_finalize(GObject *pObject); /* Private member functions */ static void dasher_main_setup_window_state(DasherMain *pSelf); static void dasher_main_setup_window_style(DasherMain *pSelf); static void dasher_main_setup_internal_layout(DasherMain *pSelf); static void dasher_main_set_window_title(DasherMain *pSelf); /* ... Table based menu/toolbar commands */ static void dasher_main_command_import(DasherMain *pSelf); static void dasher_main_command_quit(DasherMain *pSelf); static void dasher_main_command_preferences(DasherMain *pSelf); static void dasher_main_command_preferences_alphabet(DasherMain *pSelf); static void dasher_main_command_tutorial(DasherMain *pSelf); static void dasher_main_command_help(DasherMain *pSelf); static void dasher_main_command_about(DasherMain *pSelf); /* c.f. WRAP_CPP_CB below */ extern "C" void dasher_main_cb_import(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_quit(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_preferences(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_help(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_about(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_editor(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_toggle_game_mode(GtkAction*, DasherMain*); static gboolean dasher_main_speed_changed(DasherMain *pSelf); static void dasher_main_alphabet_combo_changed(DasherMain *pSelf); // TODO: populate speed slider static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); /* TODO: order these in file */ static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); + pPrivate->pGameDisplay = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "GameDisplay")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // /** * Clear all text out of the dasher editor. * @param pSelf a reference to an instance of DasherMain */ void clear_dasher_editor_text(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } /** * Start game mode, specify the text to play with, and clear out any text in the dasher editor. * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. * * @param pGameTextFilePath - the absolute path to the text file to play with * @param pSelf - a reference to an instance of DasherMain */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); + GtkDasherControl *pControl = GTK_DASHER_CONTROL(pPrivate->pDasherWidget); + gtk_dasher_control_set_game_display(pControl, pPrivate->pGameDisplay); + dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); clear_dasher_editor_text(pSelf); } /** * Event handler which displays a standard GTK file dialog. The dialog allows the user * to specify a text file to play game mode with. * * @param pButton the button that fired the event * @param pWidget reference needed by GTK for callback signature * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references * to the dialog's parent window and an instance of DasherMain */ void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } /** * Toggle game mode on and off. Toggling on causes a dialog box to be displayed * welcoming the user to game mode and prompting them to specify a file to play with. * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core * to respond appropriately. * * @param pSelf a reference to an instance of DasherMain */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); GtkWidget *pCancelButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); //g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); clear_dasher_editor_text(pSelf); } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: diff --git a/Src/Gtk2/dasher_main.h b/Src/Gtk2/dasher_main.h index 4b29a4a..feed7cd 100644 --- a/Src/Gtk2/dasher_main.h +++ b/Src/Gtk2/dasher_main.h @@ -1,91 +1,92 @@ #ifndef __dasher_main_h__ #define __dasher_main_h__ #include <glib.h> #include <glib-object.h> #include "Preferences.h" #include "KeyboardHelper.h" #include "DasherAppSettings.h" G_BEGIN_DECLS #define DASHER_TYPE_MAIN (dasher_main_get_type()) #define DASHER_MAIN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), DASHER_TYPE_MAIN, DasherMain )) #define DASHER_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), DASHER_TYPE_MAIN, DasherMainClass )) #define DASHER_IS_MAIN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), DASHER_TYPE_MAIN)) #define DASHER_IS_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), DASHER_TYPE_MAIN)) #define DASHER_MAIN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), DASHER_TYPE_MAIN, DasherMainClass)) // TODO: Make sure this is actually used #define DASHER_MAIN_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), DASHER_TYPE_MAIN, DasherMainPrivate)) typedef struct _DasherMain DasherMain; typedef struct _DasherMainClass DasherMainClass; struct _DasherMain { GObject parent; }; struct _DasherMainClass { GObjectClass parent_class; void (*realized)(DasherMain *pDasherMain); }; struct _DasherMainPrivate { GtkBuilder *pXML; GtkBuilder *pPrefXML; // Child objects owned here DasherAppSettings *pAppSettings; DasherPreferencesDialogue *pPreferencesDialogue; DasherEditor *pEditor; CKeyboardHelper *pKeyboardHelper; // Various widgets which need to be cached: // GtkWidget *pBufferView; GtkPaned *pDivider; GtkWindow *pMainWindow; + GtkWidget *pGameDisplay; GtkWidget *pToolbar; GtkSpinButton *pSpeedBox; GtkWidget *pAlphabetCombo; GtkWidget *pStatusControl; GtkWidget *pDasherWidget; GtkListStore *pAlphabetList; GtkAccelGroup *pAccel; gulong iAlphabetComboHandler; // Widgets used for maemo #ifdef WITH_MAEMO DasherMaemoHelper *pMaemoHelper; #ifdef WITH_MAEMOFULLSCREEN HildonProgram *pProgram; HildonWindow *pHWindow; #endif #endif // Properties of the main window int iWidth; int iHeight; bool bWidgetsInitialised; }; typedef struct _DasherMainPrivate DasherMainPrivate; typedef struct _SCommandLine SCommandLine; struct _SCommandLine { gchar *szFilename; gchar *szAppStyle; gchar *szOptions; }; DasherMain *dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine); GType dasher_main_get_type(); //DasherEditorInternal *dasher_main_get_editor(DasherMain *pSelf); void dasher_main_show(DasherMain *pSelf); void dasher_main_toggle_game_mode(DasherMain *pSelf); G_END_DECLS #endif
rgee/HFOSS-Dasher
12c8907f7d7597e8901ec6d38028bced8d7a554c
Added confirmation box when quitting game mode.
diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 408b70c..cc156f0 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -116,1064 +116,1087 @@ extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // /** * Clear all text out of the dasher editor. * @param pSelf a reference to an instance of DasherMain */ void clear_dasher_editor_text(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } /** * Start game mode, specify the text to play with, and clear out any text in the dasher editor. * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. * * @param pGameTextFilePath - the absolute path to the text file to play with * @param pSelf - a reference to an instance of DasherMain */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); clear_dasher_editor_text(pSelf); } /** * Event handler which displays a standard GTK file dialog. The dialog allows the user * to specify a text file to play game mode with. * * @param pButton the button that fired the event * @param pWidget reference needed by GTK for callback signature * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references * to the dialog's parent window and an instance of DasherMain */ void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } +void quit_game_mode(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { + DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE((DasherMain*)pData); +} + /** * Toggle game mode on and off. Toggling on causes a dialog box to be displayed * welcoming the user to game mode and prompting them to specify a file to play with. * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core * to respond appropriately. * * @param pSelf a reference to an instance of DasherMain */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); - GtkWidget *pCancelButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); + gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); //g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { - dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); - clear_dasher_editor_text(pSelf); + GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, + GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, + _("Are you sure you wish to turn off game mode? All unsaved changes will be lost.")); + + GtkWidget *pNoButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_NO, GTK_RESPONSE_REJECT); + GtkWidget *pYesButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), GTK_STOCK_YES, GTK_RESPONSE_ACCEPT); + + //g_signal_connect(pYesButton, "button-press-event", G_CALLBACK(quit_game_mode), (gpointer)pSelf); + + switch(gtk_dialog_run(GTK_DIALOG(pDialog))) { + case GTK_RESPONSE_REJECT: + gtk_widget_destroy(GTK_WIDGET(pDialog)); + break; + case GTK_RESPONSE_ACCEPT: + dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); + clear_dasher_editor_text(pSelf); + } + + if(GTK_IS_WIDGET(pDialog)) { + gtk_widget_destroy(GTK_WIDGET(pDialog)); + } } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; } } else { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Are you sure you wish to quit?")); gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't quit"), GTK_RESPONSE_REJECT, _("Quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: gtk_main_quit(); } } } static void dasher_main_command_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 0); } static void dasher_main_command_preferences_alphabet(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 1); } static void dasher_main_command_tutorial(DasherMain *pSelf) { // TODO: Implement this } static void dasher_main_command_help(DasherMain *pSelf) { #ifdef HAVE_GTK_SHOW_URI DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GdkScreen *scr; GError *err = NULL; scr = gtk_widget_get_screen(GTK_WIDGET(pPrivate->pMainWindow)); if (!gtk_show_uri(scr, "ghelp:dasher", gtk_get_current_event_time(), &err)) { GtkWidget *d; d = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", _("Unable to open help file")); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d), "%s", err->message); g_signal_connect(d, "response", G_CALLBACK(gtk_widget_destroy), NULL); gtk_window_present(GTK_WINDOW(d)); g_error_free (err); } #endif } static void dasher_main_command_about(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // In alphabetical order - please keep this in sync with the AUTHORS // file at root of the package tree const gchar *authors[] = { "Chris Ball", "Ignas Budvytis", "Peter Conlon", "Phil Cowans", "Frederik Eaton", "Behdad Esfahbod", "Matthew Garrett", "Chris Hack", "Takashi Kaburagi", "Sega Kazue",
rgee/HFOSS-Dasher
ab53af85ee65a41913b65d23146f44218cf30be1
Added more high-level documentation of the model.
diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 85dbf02..8db139b 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,379 +1,396 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// +/// The structure of this tree is the following (English used as an example. +/// Specifics may change for other languages, but this is a high-level overview) : +/// - Non-Group node has six group nodes for children: +/// 1) A non-visible group node that has, 26 children. One for every lower-case +/// character. +/// 2) A yellow group node with 26 children. One for every upper-case character. +/// 3) A green group node who's parent to punctuation nodes. +/// 4) The space character/symbol. +/// 5) The paragraph/newline symbol. +/// 6) A control node, if control mode is turned on. +/// +/// - Therefore, each level of the tree alternates between 6 group nodes +/// and n other nodes where n is defined by the current alphabet. +/// +/// (rgee: This is my current understanding of the Model. Please correct +/// or rephrase any incorrect information.) +/// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; /** * The string a user must type if game mode is active. */ std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */
rgee/HFOSS-Dasher
48dcdd7460313fe9da94faa576d36e5d9b02edc4
Added documentation to game mode related methods in dasher_main.cpp. Still have a 1 off error when starting game mode.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index ec34c80..ba11c64 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -372,812 +372,819 @@ void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } +/** + * Reset the dasher model, fetch the game module from the module manager, + * set its word generator, and make it available via m_pGameModule. + */ void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { - m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); CreateModel(0); + m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); m_pGameModule->SetWordGenerator(new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE))); } } +/** + * Reset the game module, reset the dasher model, and set m_pGameModule to NULL. + */ void CDasherInterfaceBase::ResetGameModule() { m_pGameModule->reset(); CreateModel(0); m_pGameModule = NULL; } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h // We use a shared ptr here for the word generator to avoid issues regarding // object ownership. Now this class /could/ own a word generator if it wanted // whereas before its ownership was ambiguous to the only class that // could delete it. (The game module) Therefore, newing directly to // the constructor leaked memory. RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 4531cb1..5351e1b 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,728 +1,727 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <sstream> #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); - m_pEventHandler->InsertEvent(new CModelReadyEvent()); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::GetSymbolList(CDasherNode* pNode, std::deque<CAlphabetManager::CSymbolNode*>& result) { for(std::deque<CDasherNode*>::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if((*it)->GetType() == NT_SYMBOL) { result.push_back(static_cast<CAlphabetManager::CSymbolNode*>(*it)); } else if((*it)->GetType() == NT_GROUP) { std::deque<CAlphabetManager::CSymbolNode*> group_results; GetSymbolList(*it, group_results); result.insert(result.end(), group_results.begin(), group_results.end()); } } } void CDasherModel::GameApproximate() { // Get a list of the symbol IDs of all the currently drawn children. std::deque<CAlphabetManager::CSymbolNode*> vNodes; GetSymbolList(Get_node_under_crosshair(), vNodes); std::vector<int> iTargetSymbols; m_pNodeCreationManager->GetAlphabet()->GetSymbols(iTargetSymbols, m_strGameTarget); int iTargetSymbol = iTargetSymbols.front(); // Check if the target is off to the high end if( iTargetSymbol > vNodes.front()->iSymbol ) { m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), vNodes.front())) ); } // Check if the target is off to the low end if( iTargetSymbol < vNodes.back()->iSymbol) { m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair(vNodes.back(), static_cast<CDasherNode*>(NULL))) ); } for(std::deque<CAlphabetManager::CSymbolNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it) { if( iTargetSymbol < (*it)->iSymbol ) { CAlphabetManager::CSymbolNode* prev = *(--it); m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair( static_cast<CDasherNode*>(NULL), static_cast<CDasherNode*>(NULL)))); } } } void CDasherModel::GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode) { std::vector<int> iTargetSymbols; m_pNodeCreationManager->GetAlphabet()->GetSymbols(iTargetSymbols, m_strGameTarget); int iTargetSymbol = iTargetSymbols.front(); g_pLogger->Log("Begin search for approximate game nodes..."); // If the first symbol is greater than the target, we know the target // must be off the child list to the left if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().begin()))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), (*pNode->GetChildren().begin())))); return; } // If the last symbol is less than the target, we know the target must // be off the child list to the right if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().end()))->iSymbol < iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair( (*pNode->GetChildren().end()), static_cast<CDasherNode*>(NULL) ))); return; } // Otherwise, it's between two elements of the child list. Find those // elements and send them out. for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( static_cast<CAlphabetManager::CSymbolNode*>((*it))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent( std::make_pair( (*--it), (*it) ) )); return; } } } bool CDasherModel::GameSearchChildren(CDasherNode* pNode) { for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( GameSearchIndividual((*it)) ) return true; } // If we cannot find the target string, it must not be drawn. We know this because every subtree // in the dasher model has one instance of each node in the alphabet. It must be there // somewhere or it's not drawn OR it's not in the alphabet at all. In the last case, we have // larger problems... if(m_strGameTarget != "") { /* std::stringstream ss; ss << Get_node_under_crosshair()->GetChildren().size(); g_pLogger->Log(ss.str()); */ - GameApproximate(); + //GameApproximate(); } return false; } bool CDasherModel::GameSearchIndividual(CDasherNode* pNode) { int iType = pNode->GetType(); if(iType == NT_GROUP) { if(GameSearchChildren(pNode)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } else if(iType == NT_SYMBOL) { if(pNode->IsTarget(m_strGameTarget)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. GameSearchChildren(Get_node_under_crosshair()); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index afcaf97..79e6907 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,220 +1,214 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; -<<<<<<< HEAD - class CModelReadyEvent; -======= class CNoGameNodeEvent; ->>>>>>> 727c5c67d470403739cc4dc357ef25f85ae4c294 } /* * The enumeration of event types. Whenever you add a new event type, * you must add its enum representation here. You must also make sure * to change the constant in EventHandler that refers to the number of events * or you will likely get errors. */ enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, - EV_NO_GAME_NODE + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; -} +}; /* An event that represents when the game target node cannot be found * among the current last-typed node's children. Since the set of child * nodes is a set consisting of all possible characters in the current * alphabet, the only way for it not to exist at all is if it was not * drawn yet. */ class Dasher::CNoGameNodeEvent : public Dasher::CEvent { public: CNoGameNodeEvent(std::pair<CDasherNode*, CDasherNode*> pNodes) : m_pNodes(pNodes) { m_iEventType = EV_NO_GAME_NODE; - }; + } /** * The pair of nodes that represent the closest drawn nodes to the top * and bottom of where the target node /should/ be. * * If the left of this pair is null, the target node is at the top-most * node in the current subtree of the model (in Dasher space). * * Conversely, if the right of this pair is null, the target node exists * at the bottom of the current subtree of the model. */ std::pair<CDasherNode*, CDasherNode*> m_pNodes; }; /** * An event that notifies listeners that a node previously flagged for * game mode has been drawn. */ ->>>>>>> 727c5c67d470403739cc4dc357ef25f85ae4c294 class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; /** * The node itself. */ CDasherNode* m_pNode; /** * the coordinates at which m_pNode was drawn. */ screenint m_iX, m_iY; /** * View object for manipulating the screen. */ CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 40588b5..d8bf7a5 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,178 +1,173 @@ #include "GameModule.h" #include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { //std::stringstream ss; //ss << m_iCurrentStringPos; //g_pLogger->Log(ss.str()); //if(!m_bIsActive) // return; switch(pEvent->m_iEventType) { case EV_NO_GAME_NODE: { CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); std::stringstream log_stream; log_stream << "First: " << evt->m_pNodes.first << "Second: " << evt->m_pNodes.first << endl; g_pLogger->Log(log_stream.str()); } case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); g_pLogger->Log(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); - m_bIsActive = true; - //++m_iCurrentStringPos; - //m_pEventHandler->InsertEvent( - //new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); } void CGameModule::reset() { delete m_pWordGenerator; m_sTargetString = ""; m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; - m_bIsActive = false; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 395771a..2797bd8 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,238 +1,232 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" #include <tr1/memory> namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, Dasher::CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pInterface(pInterface), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) {} ~CGameModule() { m_pSettingsStore->SetBoolParameter(BP_GAME_MODE, false); } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); /** * Set the word generator for this instance to draw words from. * @param pWordGenerator the word generator to be used */ void SetWordGenerator(CWordGeneratorBase *pWordGenerator); /** * Reset the game module. This makes the game module invalid until it is provided * with a new WordGenerator. */ void reset(); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ - - - /** - * Whether or not this instance is actually playing right now. - */ - bool m_bIsActive; /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase *m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ Dasher::CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /** * Flag that denotes whether we are approximating the target position * or not. */ bool m_bApproximating; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ static const int vEvents[3]; }; } #endif diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 43d8fa0..408b70c 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -51,1069 +51,1097 @@ static void dasher_main_set_window_title(DasherMain *pSelf); /* ... Table based menu/toolbar commands */ static void dasher_main_command_import(DasherMain *pSelf); static void dasher_main_command_quit(DasherMain *pSelf); static void dasher_main_command_preferences(DasherMain *pSelf); static void dasher_main_command_preferences_alphabet(DasherMain *pSelf); static void dasher_main_command_tutorial(DasherMain *pSelf); static void dasher_main_command_help(DasherMain *pSelf); static void dasher_main_command_about(DasherMain *pSelf); /* c.f. WRAP_CPP_CB below */ extern "C" void dasher_main_cb_import(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_quit(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_preferences(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_help(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_about(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_editor(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_toggle_game_mode(GtkAction*, DasherMain*); static gboolean dasher_main_speed_changed(DasherMain *pSelf); static void dasher_main_alphabet_combo_changed(DasherMain *pSelf); // TODO: populate speed slider static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); /* TODO: order these in file */ static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // +/** + * Clear all text out of the dasher editor. + * @param pSelf a reference to an instance of DasherMain + */ void clear_dasher_editor_text(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } +/** + * Start game mode, specify the text to play with, and clear out any text in the dasher editor. + * Sets BP_GAME_MODE to true, and SP_GAME_TEXT_FILE to the value of pGameTextFilePath. + * + * @param pGameTextFilePath - the absolute path to the text file to play with + * @param pSelf - a reference to an instance of DasherMain + */ void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_app_settings_set_string(pPrivate->pAppSettings, SP_GAME_TEXT_FILE, pGameTextFilePath); dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); clear_dasher_editor_text(pSelf); } -void show_game_file_dialog(GtkWidget *widget, GtkWidget *pButton, gpointer pData) { +/** + * Event handler which displays a standard GTK file dialog. The dialog allows the user + * to specify a text file to play game mode with. + * + * @param pButton the button that fired the event + * @param pWidget reference needed by GTK for callback signature + * @param pData pointer to a an std::pair<GtkWindow*, DasherMain*> containing references + * to the dialog's parent window and an instance of DasherMain + */ +void show_game_file_dialog(GtkWidget *pButton, GtkWidget *pWidget, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; DasherMain *pSelf = objRefs->second; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); init_game_mode(filename, pSelf); gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } +/** + * Toggle game mode on and off. Toggling on causes a dialog box to be displayed + * welcoming the user to game mode and prompting them to specify a file to play with. + * Toggling off just sets BP_GAME_MODE to false, which then causes the dasher core + * to respond appropriately. + * + * @param pSelf a reference to an instance of DasherMain + */ void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); GtkWidget *pCancelButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); //g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); clear_dasher_editor_text(pSelf); } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; } } else { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Are you sure you wish to quit?")); gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't quit"), GTK_RESPONSE_REJECT, _("Quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: gtk_main_quit(); } } } static void dasher_main_command_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 0); } static void dasher_main_command_preferences_alphabet(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 1); } static void dasher_main_command_tutorial(DasherMain *pSelf) { // TODO: Implement this } static void dasher_main_command_help(DasherMain *pSelf) { #ifdef HAVE_GTK_SHOW_URI DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GdkScreen *scr; GError *err = NULL; scr = gtk_widget_get_screen(GTK_WIDGET(pPrivate->pMainWindow)); if (!gtk_show_uri(scr, "ghelp:dasher", gtk_get_current_event_time(), &err)) {
rgee/HFOSS-Dasher
b0f887b5eaa52353321deff1b1b80a5ada70f42d
Removed all old game mode code from the model.
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 4bef83f..a7ac6b6 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,823 +1,780 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" -#include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. Get_node_under_crosshair()->GameSearchChildren(m_strGameTarget); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); - ///GAME MODE TEMP///Pass new frame events onto our teacher - GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); - if(m_bGameMode && pTeacher) - pTeacher->NewFrame(Time); + } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); - - // If the node we are outputting is the last one in a game target sentence, then - // notify the game mode teacher. - if(m_bGameMode) - if(pNode->GetFlag(NF_END_GAME)) - GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); - // We get here if all our children (groups) and grandchildren (symbols) are created. - // So lets find the correct letters. - ///GAME MODE TEMP/////////// - // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create - // new children. - - //GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); - //if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) - if(pNode->GetFlag(NF_GAME)) - { - /*std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); - - // Check if this is the last node in the sentence... - if(strTargetUtf8Char == "GameEnd") - pNode->SetFlag(NF_END_GAME, true); - else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { - // Target character not found - not in our current alphabet?!?! - // Let's give up! - pNode->SetFlag(NF_END_GAME, true); - }*/ + if(pNode->GetFlag(NF_GAME)) { Get_node_under_crosshair()->GameSearchChildren(m_strGameTarget); } - //////////////////////////// - - } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); - /////////GAME MODE TEMP////////////// - if(m_bGameMode) - if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { - //ACL 27/10/09 I note the following vector: - std::vector<std::pair<myint,bool> > vGameTargetY; - //was declared earlier and passed to pView->Render, above; but pView->Render - //would never do _anything_ to it. Hence the below seems a bit redundant too, - //but leaving around for now as a reminder that Game Mode generally is a TODO. - pTeacher->SetTargetY(vGameTargetY); - } - ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); }
rgee/HFOSS-Dasher
727c5c67d470403739cc4dc357ef25f85ae4c294
Fixed more logic errors and other bugs in node approximation. Still does NOT work. Most likely segfaults on startup.
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 50aee8a..18e6eb5 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,710 +1,727 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" +#include <sstream> + #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::GetSymbolList(CDasherNode* pNode, std::deque<CAlphabetManager::CSymbolNode*>& result) { - for(std::deque<CDasherNode*>::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if((*it)->GetType() == NT_SYMBOL) { result.push_back(static_cast<CAlphabetManager::CSymbolNode*>(*it)); } else if((*it)->GetType() == NT_GROUP) { std::deque<CAlphabetManager::CSymbolNode*> group_results; GetSymbolList(*it, group_results); - result.insert(result.end(), group_results.begin(), group_results.end()); + result.insert(result.end(), group_results.begin(), group_results.end()); } } } void CDasherModel::GameApproximate() { + // Get a list of the symbol IDs of all the currently drawn children. std::deque<CAlphabetManager::CSymbolNode*> vNodes; GetSymbolList(Get_node_under_crosshair(), vNodes); - int iTargetSymbol = m_pNodeCreationManager->GetAlphabet()->GetSymbol(m_strGameTarget); - - if( iTargetSymbol > vNodes.front()->iSymbol) { + std::vector<int> iTargetSymbols; + m_pNodeCreationManager->GetAlphabet()->GetSymbols(iTargetSymbols, m_strGameTarget); + + + int iTargetSymbol = iTargetSymbols.front(); + // Check if the target is off to the high end + if( iTargetSymbol > vNodes.front()->iSymbol ) { m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), vNodes.front())) ); } + // Check if the target is off to the low end if( iTargetSymbol < vNodes.back()->iSymbol) { m_pEventHandler->InsertEvent( new CNoGameNodeEvent(std::make_pair(vNodes.back(), static_cast<CDasherNode*>(NULL))) ); } + for(std::deque<CAlphabetManager::CSymbolNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it) { if( iTargetSymbol < (*it)->iSymbol ) { CAlphabetManager::CSymbolNode* prev = *(--it); m_pEventHandler->InsertEvent( - new CNoGameNodeEvent(std::make_pair( prev, *(it) ))); + new CNoGameNodeEvent(std::make_pair( static_cast<CDasherNode*>(NULL), static_cast<CDasherNode*>(NULL)))); } } } void CDasherModel::GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode) { - int iTargetSymbol = m_pNodeCreationManager->GetAlphabet()->GetSymbol(m_strGameTarget); + std::vector<int> iTargetSymbols; + m_pNodeCreationManager->GetAlphabet()->GetSymbols(iTargetSymbols, m_strGameTarget); + + int iTargetSymbol = iTargetSymbols.front(); + g_pLogger->Log("Begin search for approximate game nodes..."); // If the first symbol is greater than the target, we know the target // must be off the child list to the left if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().begin()))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), (*pNode->GetChildren().begin())))); return; } // If the last symbol is less than the target, we know the target must // be off the child list to the right if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().end()))->iSymbol < iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair( (*pNode->GetChildren().end()), static_cast<CDasherNode*>(NULL) ))); return; } // Otherwise, it's between two elements of the child list. Find those // elements and send them out. for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( static_cast<CAlphabetManager::CSymbolNode*>((*it))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent( std::make_pair( (*--it), (*it) ) )); return; } } } bool CDasherModel::GameSearchChildren(CDasherNode* pNode) { - if(pNode->GetChildren().size() == 0) g_pLogger->Log("NO CHILDREN"); for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( GameSearchIndividual((*it)) ) return true; } // If we cannot find the target string, it must not be drawn. We know this because every subtree // in the dasher model has one instance of each node in the alphabet. It must be there // somewhere or it's not drawn OR it's not in the alphabet at all. In the last case, we have // larger problems... - if(m_strGameTarget != "") + if(m_strGameTarget != "") { +/* + std::stringstream ss; + ss << Get_node_under_crosshair()->GetChildren().size(); + g_pLogger->Log(ss.str()); +*/ GameApproximate(); + } return false; } bool CDasherModel::GameSearchIndividual(CDasherNode* pNode) { int iType = pNode->GetType(); if(iType == NT_GROUP) { if(GameSearchChildren(pNode)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } else if(iType == NT_SYMBOL) { if(pNode->IsTarget(m_strGameTarget)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. GameSearchChildren(Get_node_under_crosshair()); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true);
rgee/HFOSS-Dasher
d99e86ceab204738ddfe746543521dc001aac235
Documented Game Node Drawn event
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 65d52a1..4b74e78 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,201 +1,216 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; class CNoGameNodeEvent; } /* * The enumeration of event types. Whenever you add a new event type, * you must add its enum representation here. You must also make sure * to change the constant in EventHandler that refers to the number of events * or you will likely get errors. */ enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; /** * An event that represents when the game target node cannot be found * among the current last-typed node's children. Since the set of child * nodes is a set consisting of all possible characters in the current * alphabet, the only way for it not to exist at all is if it was not * drawn yet. */ class Dasher::CNoGameNodeEvent : public Dasher::CEvent { public: CNoGameNodeEvent(std::pair<CDasherNode*, CDasherNode*> pNodes) : m_pNodes(pNodes) { m_iEventType = EV_NO_GAME_NODE; }; - /* + /** * The pair of nodes that represent the closest drawn nodes to the top * and bottom of where the target node /should/ be. * * If the left of this pair is null, the target node is at the top-most * node in the current subtree of the model (in Dasher space). * * Conversely, if the right of this pair is null, the target node exists * at the bottom of the current subtree of the model. */ std::pair<CDasherNode*, CDasherNode*> m_pNodes; }; +/** + * An event that notifies listeners that a node previously flagged for + * game mode has been drawn. + */ class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; + /** + * The node itself. + */ CDasherNode* m_pNode; + + /** + * the coordinates at which m_pNode was drawn. + */ screenint m_iX, m_iY; + + /** + * View object for manipulating the screen. + */ CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif
rgee/HFOSS-Dasher
d847aa8c4f4b3d3d9132267c1030e8b98f26a048
Got rid of redundant reverse lookup function. Already exists in GetSymbols. oops.
diff --git a/Src/DasherCore/Alphabet/Alphabet.h b/Src/DasherCore/Alphabet/Alphabet.h index 91cc89d..04ed2a3 100644 --- a/Src/DasherCore/Alphabet/Alphabet.h +++ b/Src/DasherCore/Alphabet/Alphabet.h @@ -1,233 +1,224 @@ // Alphabet.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DASHER_ALPHABET_H__ #define __DASHER_ALPHABET_H__ #include "AlphIO.h" #include "AlphabetMap.h" #include "../DasherTypes.h" #include "GroupInfo.h" #include <cstdlib> #include <iostream> #include <algorithm> #include <vector> namespace Dasher { /// /// \defgroup Alphabet Alphabet information /// @{ class CAlphabet { public: CAlphabet(); CAlphabet(const CAlphIO::AlphInfo & AlphInfo); // Return size of alphabet, including control symbols int GetNumberSymbols() const { return m_Characters.size(); } // return size of alphabet /// Return number of text symbols /// Text symbols are everything which doesn't generate a new root, /// i.e. control mode and conversion mode int GetNumberTextSymbols() const { // TODO: This really does need to be fixed, as this will sometimes be 2 return m_Characters.size() - 1; } Opts::ScreenOrientations GetOrientation() { return m_Orientation; } Opts::AlphabetTypes GetType() { return m_DefaultEncoding; } const std::string & GetTrainingFile() const { return m_TrainingFile; } std::string GetGameModeFile() { return m_GameModeFile; } std::string & GetPalette() { return m_DefaultPalette; } symbol GetParagraphSymbol() const; symbol GetSpaceSymbol() const; symbol GetControlSymbol() const; symbol GetStartConversionSymbol() const; symbol GetEndConversionSymbol() const; const std::string & GetDisplayText(symbol i) const { return m_Display[i]; } // return display string for i'th symbol const std::string & GetText(symbol i) const { return m_Characters[i]; } - // return string for i'th symbol - - /** - * Return the symbol id of the character with the specified text. - * Essentially a reverse lookup of GetText. - */ - const int GetSymbol(std::string & str) const { - return std::distance(m_Characters.begin(), std::find(m_Characters.begin(), m_Characters.end(), str)) - 1; - } int GetColour(symbol i, int iPhase) const; int GetTextColour(symbol i); // return the foreground colour for i'th symbol const std::string & GetForeground(symbol i) const { return m_Foreground[i]; } // return the foreground colour for i'th symbol /* int GetGroupCount() const { */ /* return m_iGroups; */ /* } int GetGroupStart(int i) const { */ /* return m_GroupStart[i]; */ /* } int GetGroupEnd(int i) const { */ /* return m_GroupEnd[i]; */ /* } */ //int get_group(symbol i) const {return m_Group[i];} // return group membership of i'th symbol class SymbolStream { public: SymbolStream(const CAlphabet *pAlph, std::istream &_in); symbol next(); private: void readMore(); const alphabet_map &map; char buf[1024]; int pos, len; std::istream &in; }; // Fills Symbols with the symbols corresponding to Input. {{{ Note that this // is not necessarily reversible by repeated use of GetText. Some text // may not be recognised and so discarded. }}} void GetSymbols(std::vector<symbol> &Symbols, const std::string &Input) const; //SymbolStream *GetSymbols(std::istream &in) const; void Trace() const; // diagnostic void SetOrientation(Opts::ScreenOrientations Orientation) { m_Orientation = Orientation; } void SetLanguage(Opts::AlphabetTypes Group) { m_DefaultEncoding = Group; } void SetTrainingFile(std::string TrainingFile) { m_TrainingFile = TrainingFile; } void SetGameModeFile(std::string GameModeFile) { m_GameModeFile = GameModeFile; } void SetPalette(std::string Palette) { m_DefaultPalette = Palette; } const std::string &GetDefaultContext() const { return m_strDefaultContext; } SGroupInfo *m_pBaseGroup; int iNumChildNodes; private: // Add the characters that can appear in Nodes void AddChar(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); // add single char to the alphabet // Alphabet language parameters void AddParagraphSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddSpaceSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddControlSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddStartConversionSymbol(std::string NewCharacter, std::string Display , int Colour, std::string Foreground); void AddEndConversionSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); Opts::AlphabetTypes m_DefaultEncoding; Opts::ScreenOrientations m_Orientation; symbol m_ParagraphSymbol; symbol m_SpaceSymbol; symbol m_ControlSymbol; symbol m_StartConversionSymbol; symbol m_EndConversionSymbol; std::string m_TrainingFile; std::string m_GameModeFile; std::string m_DefaultPalette; class utf8_length { public: utf8_length(); int operator[](const unsigned char) const; int max_length; private: int utf8_count_array[0x100]; }; static utf8_length m_utf8_count_array; // TODO: This is inane std::vector < std::string > m_Characters; // stores the characters std::vector < std::string > m_Display; // stores how the characters are visually represented in the Dasher nodes std::vector < int >m_Colours; // stores the colour of the characters std::vector < std::string > m_Foreground; // stores the colour of the character foreground // ---- alphabet_map TextMap; std::string m_strDefaultContext; }; /// @} inline symbol CAlphabet::GetParagraphSymbol() const { return m_ParagraphSymbol; } inline symbol CAlphabet::GetSpaceSymbol() const { return m_SpaceSymbol; } inline symbol CAlphabet::GetControlSymbol() const { return m_ControlSymbol; } inline symbol CAlphabet::GetStartConversionSymbol() const { return m_StartConversionSymbol; } inline symbol CAlphabet::GetEndConversionSymbol() const { return m_EndConversionSymbol; } } // end namespace dasher #endif // ifndef __DASHER_ALPHABET_H__
rgee/HFOSS-Dasher
51dfbb6c232e835f3a0d41e28f06f13a3315fcf8
In the middle of Game mode UI development. Now, Dasher resets the model and text box every time the user toggles game mode. Have some logging statements lying around.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index ddbf4bd..ec34c80 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -376,806 +376,808 @@ void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); - m_pGameModule->SetWordGenerator(std::tr1::shared_ptr<CWordGeneratorBase> - (new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE)))); + CreateModel(0); + m_pGameModule->SetWordGenerator(new CFileWordGenerator(GetStringParameter(SP_GAME_TEXT_FILE))); + } } void CDasherInterfaceBase::ResetGameModule() { m_pGameModule->reset(); + CreateModel(0); m_pGameModule = NULL; } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h // We use a shared ptr here for the word generator to avoid issues regarding // object ownership. Now this class /could/ own a word generator if it wanted // whereas before its ownership was ambiguous to the only class that // could delete it. (The game module) Therefore, newing directly to // the constructor leaked memory. RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 4bef83f..698c1de 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,602 +1,604 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); + + m_pEventHandler->InsertEvent(new CModelReadyEvent()); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. Get_node_under_crosshair()->GameSearchChildren(m_strGameTarget); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 2e5a2ee..a9d09e9 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,166 +1,176 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; + class CModelReadyEvent; } enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_MODEL_READY }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; +/** + * Signal that the Dasher model is fully constructed and + * ready to receieve events. + */ +class Dasher::CModelReadyEvent : public Dasher::CEvent { +public: + CModelReadyEvent() { m_iEventType = EV_MODEL_READY; } +}; + class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; CDasherNode* m_pNode; screenint m_iX, m_iY; CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index b7f2a75..ad8b039 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,165 +1,177 @@ #include "GameModule.h" #include <sstream> #include <iostream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ -const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN}; +const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_MODEL_READY}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { - std::stringstream ss; - ss << m_iCurrentStringPos; - g_pLogger->Log(ss.str()); + //std::stringstream ss; + //ss << m_iCurrentStringPos; + //g_pLogger->Log(ss.str()); - if(!m_bIsActive) - return; + //if(!m_bIsActive) + // return; switch(pEvent->m_iEventType) { + case EV_MODEL_READY: + { + m_pEventHandler->InsertEvent(new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); + g_pLogger->Log("Dasher Model ready"); + + } case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); + + g_pLogger->Log(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); + } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } -void CGameModule::SetWordGenerator(std::tr1::shared_ptr<CWordGeneratorBase> pWordGenerator) { +void CGameModule::SetWordGenerator(CWordGeneratorBase *pWordGenerator) { m_pWordGenerator = pWordGenerator; GenerateChunk(); m_bIsActive = true; + //++m_iCurrentStringPos; + //m_pEventHandler->InsertEvent( + //new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); } void CGameModule::reset() { - m_pWordGenerator.reset(); + delete m_pWordGenerator; m_sTargetString = ""; - m_iCurrentStringPos = 0; + m_iCurrentStringPos = -1; m_iTargetX = 0; m_iTargetY = 0; m_bIsActive = false; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index bc8e180..3e0adcb 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,232 +1,232 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" #include <tr1/memory> namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, Dasher::CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pInterface(pInterface), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) {} ~CGameModule() { m_pSettingsStore->SetBoolParameter(BP_GAME_MODE, false); } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); /** * Set the word generator for this instance to draw words from. * @param pWordGenerator the word generator to be used */ - void SetWordGenerator(std::tr1::shared_ptr<CWordGeneratorBase> pWordGenerator); + void SetWordGenerator(CWordGeneratorBase *pWordGenerator); /** * Reset the game module. This makes the game module invalid until it is provided * with a new WordGenerator. */ void reset(); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Whether or not this instance is actually playing right now. */ bool m_bIsActive; /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ - std::tr1::shared_ptr<CWordGeneratorBase> m_pWordGenerator; + CWordGeneratorBase *m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ Dasher::CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ static const int vEvents[3]; }; } #endif diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index fde14a0..43d8fa0 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -1,1137 +1,1151 @@ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <utility> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #ifdef WITH_MAEMOFULLSCREEN #include <hildon-widgets/hildon-program.h> #endif #include <unistd.h> #include "GtkDasherControl.h" #include "dasher_lock_dialogue.h" #ifdef WITH_MAEMO #include "dasher_maemo_helper.h" #endif #include "dasher_main.h" +#include "dasher_editor.h" #include "dasher_editor_internal.h" #include "dasher_editor_external.h" /* Static instance of singleton, USE SPARINGLY */ static DasherMain *g_pDasherMain = NULL; // TODO: The following global variable makes control mode editing work // - this needs to be sorted out properly. static gboolean g_bSend = true; enum { REALIZED, SIGNAL_NUM }; static guint dasher_main_signals[SIGNAL_NUM] = { 0 }; G_DEFINE_TYPE(DasherMain, dasher_main, G_TYPE_OBJECT); static void dasher_main_finalize(GObject *pObject); /* Private member functions */ static void dasher_main_setup_window_state(DasherMain *pSelf); static void dasher_main_setup_window_style(DasherMain *pSelf); static void dasher_main_setup_internal_layout(DasherMain *pSelf); static void dasher_main_set_window_title(DasherMain *pSelf); /* ... Table based menu/toolbar commands */ static void dasher_main_command_import(DasherMain *pSelf); static void dasher_main_command_quit(DasherMain *pSelf); static void dasher_main_command_preferences(DasherMain *pSelf); static void dasher_main_command_preferences_alphabet(DasherMain *pSelf); static void dasher_main_command_tutorial(DasherMain *pSelf); static void dasher_main_command_help(DasherMain *pSelf); static void dasher_main_command_about(DasherMain *pSelf); /* c.f. WRAP_CPP_CB below */ extern "C" void dasher_main_cb_import(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_quit(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_preferences(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_help(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_about(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_editor(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_toggle_game_mode(GtkAction*, DasherMain*); static gboolean dasher_main_speed_changed(DasherMain *pSelf); static void dasher_main_alphabet_combo_changed(DasherMain *pSelf); // TODO: populate speed slider static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); /* TODO: order these in file */ static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // -void initialize_game_mode(char *trainingText) { - +void clear_dasher_editor_text(DasherMain *pSelf) { + + DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); + int editorTextLen = strlen(dasher_editor_get_all_text(pPrivate->pEditor)); + dasher_editor_delete(pPrivate->pEditor, editorTextLen, 0); } +void init_game_mode(char *pGameTextFilePath, DasherMain *pSelf) { + + DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); + + dasher_app_settings_set_string(pPrivate->pAppSettings, + SP_GAME_TEXT_FILE, + pGameTextFilePath); + + dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); + clear_dasher_editor_text(pSelf); +} void show_game_file_dialog(GtkWidget *widget, GtkWidget *pButton, gpointer pData) { std::pair<GtkWindow*, DasherMain*> *objRefs = (std::pair<GtkWindow*, DasherMain*>*)pData; - DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(objRefs->second); + DasherMain *pSelf = objRefs->second; + DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", GTK_WINDOW(objRefs->first), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); gtk_window_set_destroy_with_parent(GTK_WINDOW(pFileDialog), true); if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); - dasher_app_settings_set_string(pPrivate->pAppSettings, - SP_GAME_TEXT_FILE, - filename); - - dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); + init_game_mode(filename, pSelf); + gtk_widget_destroy(GTK_WIDGET(objRefs->first)); } } void dasher_main_toggle_game_mode(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GAME_MODE)) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, - GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, - _("Welcome to Game Mode! Please select a training text:")); + GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, + _("Welcome to Dasher Game Mode! Game Mode is a fun way to practice entering text in Dasher. Please select a training text to play with:")); GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); GtkWidget *pCancelButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); //make a pair with references to the the DasherMain and parent window instances that //handler will need - kind of disgusting, but looks like only way to pass multiple //parameters in g_signal_connect std::pair<GtkWindow*, DasherMain*> objRefs = std::make_pair(GTK_WINDOW(pDialog), pSelf); //g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), (gpointer)&objRefs); gtk_dialog_run(GTK_DIALOG(pDialog)); //have to do this check because we might have destroyed the dialog already in show_game_file_dialog if(GTK_IS_WIDGET(pDialog)) gtk_widget_destroy(pDialog); } else { dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, false); + clear_dasher_editor_text(pSelf); } } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; } } else { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Are you sure you wish to quit?")); gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't quit"), GTK_RESPONSE_REJECT, _("Quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: gtk_main_quit(); } } } static void dasher_main_command_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 0); } static void dasher_main_command_preferences_alphabet(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 1); } static void dasher_main_command_tutorial(DasherMain *pSelf) { // TODO: Implement this } static void dasher_main_command_help(DasherMain *pSelf) { #ifdef HAVE_GTK_SHOW_URI DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GdkScreen *scr; GError *err = NULL; scr = gtk_widget_get_screen(GTK_WIDGET(pPrivate->pMainWindow)); if (!gtk_show_uri(scr, "ghelp:dasher", gtk_get_current_event_time(), &err)) { GtkWidget *d; d = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", _("Unable to open help file")); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d), "%s", err->message); g_signal_connect(d, "response", G_CALLBACK(gtk_widget_destroy), NULL); gtk_window_present(GTK_WINDOW(d)); g_error_free (err); } #endif } static void dasher_main_command_about(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // In alphabetical order - please keep this in sync with the AUTHORS // file at root of the package tree const gchar *authors[] = { "Chris Ball", "Ignas Budvytis", "Peter Conlon", "Phil Cowans", "Frederik Eaton", "Behdad Esfahbod", "Matthew Garrett", "Chris Hack", "Takashi Kaburagi", "Sega Kazue",
rgee/HFOSS-Dasher
655561ce3c776839420a17e7c41506f37ee0c951
Improved search approximation. Still not working. Currently segfaults on startup.
diff --git a/Src/DasherCore/Alphabet/Alphabet.h b/Src/DasherCore/Alphabet/Alphabet.h index 5a44efb..91cc89d 100644 --- a/Src/DasherCore/Alphabet/Alphabet.h +++ b/Src/DasherCore/Alphabet/Alphabet.h @@ -1,233 +1,233 @@ // Alphabet.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DASHER_ALPHABET_H__ #define __DASHER_ALPHABET_H__ #include "AlphIO.h" #include "AlphabetMap.h" #include "../DasherTypes.h" #include "GroupInfo.h" #include <cstdlib> #include <iostream> #include <algorithm> #include <vector> namespace Dasher { /// /// \defgroup Alphabet Alphabet information /// @{ class CAlphabet { public: CAlphabet(); CAlphabet(const CAlphIO::AlphInfo & AlphInfo); // Return size of alphabet, including control symbols int GetNumberSymbols() const { return m_Characters.size(); } // return size of alphabet /// Return number of text symbols /// Text symbols are everything which doesn't generate a new root, /// i.e. control mode and conversion mode int GetNumberTextSymbols() const { // TODO: This really does need to be fixed, as this will sometimes be 2 return m_Characters.size() - 1; } Opts::ScreenOrientations GetOrientation() { return m_Orientation; } Opts::AlphabetTypes GetType() { return m_DefaultEncoding; } const std::string & GetTrainingFile() const { return m_TrainingFile; } std::string GetGameModeFile() { return m_GameModeFile; } std::string & GetPalette() { return m_DefaultPalette; } symbol GetParagraphSymbol() const; symbol GetSpaceSymbol() const; symbol GetControlSymbol() const; symbol GetStartConversionSymbol() const; symbol GetEndConversionSymbol() const; const std::string & GetDisplayText(symbol i) const { return m_Display[i]; } // return display string for i'th symbol const std::string & GetText(symbol i) const { return m_Characters[i]; } // return string for i'th symbol /** * Return the symbol id of the character with the specified text. * Essentially a reverse lookup of GetText. */ const int GetSymbol(std::string & str) const { - return std::distance( std::find(m_Characters.begin(), m_Characters.end(), str), m_Characters.begin() ) - 1; + return std::distance(m_Characters.begin(), std::find(m_Characters.begin(), m_Characters.end(), str)) - 1; } int GetColour(symbol i, int iPhase) const; int GetTextColour(symbol i); // return the foreground colour for i'th symbol const std::string & GetForeground(symbol i) const { return m_Foreground[i]; } // return the foreground colour for i'th symbol /* int GetGroupCount() const { */ /* return m_iGroups; */ /* } int GetGroupStart(int i) const { */ /* return m_GroupStart[i]; */ /* } int GetGroupEnd(int i) const { */ /* return m_GroupEnd[i]; */ /* } */ //int get_group(symbol i) const {return m_Group[i];} // return group membership of i'th symbol class SymbolStream { public: SymbolStream(const CAlphabet *pAlph, std::istream &_in); symbol next(); private: void readMore(); const alphabet_map &map; char buf[1024]; int pos, len; std::istream &in; }; // Fills Symbols with the symbols corresponding to Input. {{{ Note that this // is not necessarily reversible by repeated use of GetText. Some text // may not be recognised and so discarded. }}} void GetSymbols(std::vector<symbol> &Symbols, const std::string &Input) const; //SymbolStream *GetSymbols(std::istream &in) const; void Trace() const; // diagnostic void SetOrientation(Opts::ScreenOrientations Orientation) { m_Orientation = Orientation; } void SetLanguage(Opts::AlphabetTypes Group) { m_DefaultEncoding = Group; } void SetTrainingFile(std::string TrainingFile) { m_TrainingFile = TrainingFile; } void SetGameModeFile(std::string GameModeFile) { m_GameModeFile = GameModeFile; } void SetPalette(std::string Palette) { m_DefaultPalette = Palette; } const std::string &GetDefaultContext() const { return m_strDefaultContext; } SGroupInfo *m_pBaseGroup; int iNumChildNodes; private: // Add the characters that can appear in Nodes void AddChar(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); // add single char to the alphabet // Alphabet language parameters void AddParagraphSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddSpaceSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddControlSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddStartConversionSymbol(std::string NewCharacter, std::string Display , int Colour, std::string Foreground); void AddEndConversionSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); Opts::AlphabetTypes m_DefaultEncoding; Opts::ScreenOrientations m_Orientation; symbol m_ParagraphSymbol; symbol m_SpaceSymbol; symbol m_ControlSymbol; symbol m_StartConversionSymbol; symbol m_EndConversionSymbol; std::string m_TrainingFile; std::string m_GameModeFile; std::string m_DefaultPalette; class utf8_length { public: utf8_length(); int operator[](const unsigned char) const; int max_length; private: int utf8_count_array[0x100]; }; static utf8_length m_utf8_count_array; // TODO: This is inane std::vector < std::string > m_Characters; // stores the characters std::vector < std::string > m_Display; // stores how the characters are visually represented in the Dasher nodes std::vector < int >m_Colours; // stores the colour of the characters std::vector < std::string > m_Foreground; // stores the colour of the character foreground // ---- alphabet_map TextMap; std::string m_strDefaultContext; }; /// @} inline symbol CAlphabet::GetParagraphSymbol() const { return m_ParagraphSymbol; } inline symbol CAlphabet::GetSpaceSymbol() const { return m_SpaceSymbol; } inline symbol CAlphabet::GetControlSymbol() const { return m_ControlSymbol; } inline symbol CAlphabet::GetStartConversionSymbol() const { return m_StartConversionSymbol; } inline symbol CAlphabet::GetEndConversionSymbol() const { return m_EndConversionSymbol; } } // end namespace dasher #endif // ifndef __DASHER_ALPHABET_H__ diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 414c457..50aee8a 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,718 +1,710 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } -std::vector<CDasherNode*> CDasherModel::GetSymbolList(CDasherNode* pNode) { - std::vector<CDasherNode*> result; +void CDasherModel::GetSymbolList(CDasherNode* pNode, std::deque<CAlphabetManager::CSymbolNode*>& result) { - for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); + + for(std::deque<CDasherNode*>::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { - if(pNode->GetType() == NT_SYMBOL) { - result.push_back(pNode); + if((*it)->GetType() == NT_SYMBOL) { + result.push_back(static_cast<CAlphabetManager::CSymbolNode*>(*it)); } - else if(pNode->GetType() == NT_GROUP) { - std::vector<CDasherNode*> group_results; + else if((*it)->GetType() == NT_GROUP) { + + std::deque<CAlphabetManager::CSymbolNode*> group_results; + GetSymbolList(*it, group_results); + result.insert(result.end(), group_results.begin(), group_results.end()); } - } - - return result; + } } void CDasherModel::GameApproximate() { - std::vector<CDasherNode*> vNodes = GetSymbolList(Get_node_under_crosshair()); + std::deque<CAlphabetManager::CSymbolNode*> vNodes; + GetSymbolList(Get_node_under_crosshair(), vNodes); int iTargetSymbol = m_pNodeCreationManager->GetAlphabet()->GetSymbol(m_strGameTarget); - if( iTargetSymbol < vNodes.begin()->iSymbol) { + if( iTargetSymbol > vNodes.front()->iSymbol) { m_pEventHandler->InsertEvent( - new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), vNodes.begin())) + new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), vNodes.front())) ); } - if( iTargetSymbol > vNodes.eng()->iSymbol) { + if( iTargetSymbol < vNodes.back()->iSymbol) { m_pEventHandler->InsertEvent( - new CNoGameNodeEvent(std::make_pair(vNodes.end(), static_cast<CDasherNode*>(NULL))) + new CNoGameNodeEvent(std::make_pair(vNodes.back(), static_cast<CDasherNode*>(NULL))) ); } - for(std::vector<CDasherNode*>::const_iterator it = vNodes.begin(); - it != vNodes.end(); it++) { - if( iTargetSymbol < (*it).iSymbol ) { + for(std::deque<CAlphabetManager::CSymbolNode*>::iterator it = vNodes.begin(); + it != vNodes.end(); ++it) { + if( iTargetSymbol < (*it)->iSymbol ) { + CAlphabetManager::CSymbolNode* prev = *(--it); m_pEventHandler->InsertEvent( - new CNoGameNodeEvent(std::make_pair( (*--it), (*it) )) - ); + new CNoGameNodeEvent(std::make_pair( prev, *(it) ))); } } } void CDasherModel::GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode) { int iTargetSymbol = m_pNodeCreationManager->GetAlphabet()->GetSymbol(m_strGameTarget); g_pLogger->Log("Begin search for approximate game nodes..."); // If the first symbol is greater than the target, we know the target // must be off the child list to the left if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().begin()))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), (*pNode->GetChildren().begin())))); return; } // If the last symbol is less than the target, we know the target must // be off the child list to the right if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().end()))->iSymbol < iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair( (*pNode->GetChildren().end()), static_cast<CDasherNode*>(NULL) ))); return; } // Otherwise, it's between two elements of the child list. Find those // elements and send them out. for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( static_cast<CAlphabetManager::CSymbolNode*>((*it))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent( std::make_pair( (*--it), (*it) ) )); return; } } } bool CDasherModel::GameSearchChildren(CDasherNode* pNode) { if(pNode->GetChildren().size() == 0) g_pLogger->Log("NO CHILDREN"); for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( GameSearchIndividual((*it)) ) return true; } + + // If we cannot find the target string, it must not be drawn. We know this because every subtree // in the dasher model has one instance of each node in the alphabet. It must be there // somewhere or it's not drawn OR it's not in the alphabet at all. In the last case, we have // larger problems... - int iType = pNode->GetType(); - if((iType == NT_GROUP) || (iType == NT_SYMBOL)) { - if(iType == NT_SYMBOL) { - CAlphabetManager::CSymbolNode* newNode = static_cast<CAlphabetManager::CSymbolNode*>(pNode); - GameSearchApproximate(newNode); - } -/* - if(iType == NT_GROUP) { - CAlphabetManager::CGroupNode* newNode = static_cast<CAlphabetManager::CGroupNode*>(pNode); - GameSearchApproximate(newNode); - } -*/ - } - + if(m_strGameTarget != "") + GameApproximate(); return false; } bool CDasherModel::GameSearchIndividual(CDasherNode* pNode) { int iType = pNode->GetType(); if(iType == NT_GROUP) { if(GameSearchChildren(pNode)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } else if(iType == NT_SYMBOL) { if(pNode->IsTarget(m_strGameTarget)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. GameSearchChildren(Get_node_under_crosshair()); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 725e3b1..98f5c08 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,409 +1,409 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; /** * The string a user must type if game mode is active. */ std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); void GameApproximate(); - std::vector<CDasherNode*> GetSymbolList(CDasherNode* pNode); + void GetSymbolList(CDasherNode* pNode, std::deque<CAlphabetManager::CSymbolNode*>& result); /// /// Search the model for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchChildren(CDasherNode* pNode); /// /// Search the model (recursively) for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchIndividual(CDasherNode* pNode); /// /// Approximate the position of the target node, if it was not /// explicitly found. /// /// \param pNode The node to begin the search from /// \warning Currently only works for symbol or group nodes. This /// needs to be improved. void GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */
rgee/HFOSS-Dasher
bcb09f05bb0a0b9701c97ba87aed565fa2c98174
Added new node approximation functions. Committing and leaving early due to possible HAIL. oh god....
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index 9795a16..dd27082 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,452 +1,451 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iType, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, iType), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, NT_SYMBOL, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, NT_SYMBOL, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup) : CAlphNode(pParent, NT_GROUP, iOffset, iLbnd, iHbnd, pGroup ? (pGroup->bVisible ? pGroup->iColour : pParent->getColour()) : pMgr->m_pNCManager->GetAlphabet()->GetColour(0, iOffset%2), pGroup ? pGroup->strLabel : "", pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { return new CSymbolNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup) { return new CGroupNode(pParent, iOffset, iLbnd, iHbnd, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pNewNode = makeGroup(pParent, iNewOffset, iLower, iUpper, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pNewNode = makeSymbol(pParent, iNewOffset, iLower, iUpper, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->iContext = iContext; return pNewNode; } bool CAlphabetManager::CSymbolNode::IsTarget(string strTargetUtf8Char) { - g_pLogger->Log("Comparing to: " + m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol)); return (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char); } CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->offset() == offset()); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // When creating a group node... // ...the offset is the same as the parent... CGroupNode *pNewNode = makeGroup(pParent, pParent->offset(), iLbnd, iHbnd, pInfo); //...as is the context! pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (offset() == pParent->offset()); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); } else { // TODO: Exceptions / error handling in general CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, pParent->offset()+1, iLbnd, iHbnd, iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(offset() == pParent->offset() + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); //loop for eliding groups with single children (see below). // Variables store necessary properties of any elided groups: std::string groupPrefix=""; int iOverrideColour=-1; SGroupInfo *pInner=pCurrentNode; while (true) { if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop break; //exit inner (group elision) loop } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); i = pInner->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) // (maybe not of pCurrentNode now, which might be a subgroup filling the original) break; //exit inner (group elision) loop } //were about to create a group node, which would have only one child // (eventually, if the group node were PopulateChildren'd). // Such a child would entirely fill it's parent (the group), and thus, // creation/destruction of the child would cause the node's colour to flash // between that for parent group and child. // Hence, instead we elide the group node and create the child _here_... //1. however we also have to take account of the appearance of the elided group. Hence: groupPrefix += pInner->strLabel; if (pInner->bVisible) iOverrideColour=pInner->iColour; //2. now go into the group... pInner = pInner->pChild; bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok //3. loop round inner loop... } //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); //now adjust the node we've actually created, to take account of any elided group(s)... // tho not if we've reused the existing node, assume that's been adjusted already if (pNewChild && pNewChild!=buildAround) pNewChild->PrependElidedGroup(iOverrideColour, groupPrefix); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(offset()); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(offset()-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index bc87d4e..414c457 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,648 +1,695 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } +std::vector<CDasherNode*> CDasherModel::GetSymbolList(CDasherNode* pNode) { + std::vector<CDasherNode*> result; + + for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); + it != pNode->GetChildren().end(); it++) { + if(pNode->GetType() == NT_SYMBOL) { + result.push_back(pNode); + } + else if(pNode->GetType() == NT_GROUP) { + std::vector<CDasherNode*> group_results; + result.insert(result.end(), group_results.begin(), group_results.end()); + } + } + + return result; +} + +void CDasherModel::GameApproximate() { + std::vector<CDasherNode*> vNodes = GetSymbolList(Get_node_under_crosshair()); + int iTargetSymbol = m_pNodeCreationManager->GetAlphabet()->GetSymbol(m_strGameTarget); + + if( iTargetSymbol < vNodes.begin()->iSymbol) { + m_pEventHandler->InsertEvent( + new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), vNodes.begin())) + ); + } + + if( iTargetSymbol > vNodes.eng()->iSymbol) { + m_pEventHandler->InsertEvent( + new CNoGameNodeEvent(std::make_pair(vNodes.end(), static_cast<CDasherNode*>(NULL))) + ); + } + + for(std::vector<CDasherNode*>::const_iterator it = vNodes.begin(); + it != vNodes.end(); it++) { + if( iTargetSymbol < (*it).iSymbol ) { + m_pEventHandler->InsertEvent( + new CNoGameNodeEvent(std::make_pair( (*--it), (*it) )) + ); + } + } +} + + void CDasherModel::GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode) { int iTargetSymbol = m_pNodeCreationManager->GetAlphabet()->GetSymbol(m_strGameTarget); - + g_pLogger->Log("Begin search for approximate game nodes..."); + + // If the first symbol is greater than the target, we know the target // must be off the child list to the left if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().begin()))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), (*pNode->GetChildren().begin())))); return; } // If the last symbol is less than the target, we know the target must // be off the child list to the right if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().end()))->iSymbol < iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair( (*pNode->GetChildren().end()), static_cast<CDasherNode*>(NULL) ))); return; } // Otherwise, it's between two elements of the child list. Find those // elements and send them out. for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( static_cast<CAlphabetManager::CSymbolNode*>((*it))->iSymbol > iTargetSymbol ) { m_pEventHandler->InsertEvent(new CNoGameNodeEvent( std::make_pair( (*--it), (*it) ) )); return; } } } bool CDasherModel::GameSearchChildren(CDasherNode* pNode) { + if(pNode->GetChildren().size() == 0) g_pLogger->Log("NO CHILDREN"); for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( GameSearchIndividual((*it)) ) return true; } // If we cannot find the target string, it must not be drawn. We know this because every subtree // in the dasher model has one instance of each node in the alphabet. It must be there // somewhere or it's not drawn OR it's not in the alphabet at all. In the last case, we have // larger problems... int iType = pNode->GetType(); if((iType == NT_GROUP) || (iType == NT_SYMBOL)) { if(iType == NT_SYMBOL) { CAlphabetManager::CSymbolNode* newNode = static_cast<CAlphabetManager::CSymbolNode*>(pNode); GameSearchApproximate(newNode); } /* if(iType == NT_GROUP) { CAlphabetManager::CGroupNode* newNode = static_cast<CAlphabetManager::CGroupNode*>(pNode); GameSearchApproximate(newNode); } */ } return false; } bool CDasherModel::GameSearchIndividual(CDasherNode* pNode) { int iType = pNode->GetType(); if(iType == NT_GROUP) { if(GameSearchChildren(pNode)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } else if(iType == NT_SYMBOL) { if(pNode->IsTarget(m_strGameTarget)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. GameSearchChildren(Get_node_under_crosshair()); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 857b614..725e3b1 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,406 +1,409 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; /** * The string a user must type if game mode is active. */ std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); + void GameApproximate(); + std::vector<CDasherNode*> GetSymbolList(CDasherNode* pNode); + /// /// Search the model for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchChildren(CDasherNode* pNode); /// /// Search the model (recursively) for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchIndividual(CDasherNode* pNode); /// /// Approximate the position of the target node, if it was not /// explicitly found. /// /// \param pNode The node to begin the search from /// \warning Currently only works for symbol or group nodes. This /// needs to be improved. void GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */ diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 0c91d79..11cce41 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,141 +1,148 @@ #include "GameModule.h" - +#include <sstream> using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { + case EV_NO_GAME_NODE: + { + CNoGameNodeEvent* evt = static_cast<CNoGameNodeEvent*>(pEvent); + std::stringstream log_stream; + log_stream << "First: " << evt->m_pNodes.first << "Second: " << evt->m_pNodes.first << endl; + g_pLogger->Log(log_stream.str()); + } case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); }
rgee/HFOSS-Dasher
5a5d3038f3d884c510a17271201ee75f25db9549
Not building test for now. When we do, we get a really strange error. To be fixed later.
diff --git a/Makefile.am b/Makefile.am index fa59c4f..84ceda7 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,71 +1,71 @@ -SUBDIRS = Src Data Doc Testing/dasher_tests +SUBDIRS = Src Data Doc if USE_INTLTOOL SUBDIRS += po endif ACLOCAL_AMFLAGS = -I m4 distuninstallcheck_listfiles = \ find . -type f -print | \ grep -v '^\./var/scrollkeeper' | \ grep -v '^\./share/gnome/help' EXTRA_DIST = \ INSTALL.Linux \ INSTALL.WinCE \ INSTALL.Windows \ MAINTAINERS \ m4/pkg.m4 \ m4/glib-gettext.m4 \ m4/dgconf-2.m4 \ m4/gnome-doc-utils.m4 \ m4/intltool.m4 \ m4/nls.m4 \ intltool-merge.in \ intltool-extract.in \ intltool-update.in \ gnome-doc-utils.make \ .tarball-version \ build-aux/mkversion DISTCLEANFILES = \ intltool-merge \ intltool-extract \ intltool-update \ Data/dasher.desktop \ Data/Help/Gnome/Makefile MAINTAINERCLEANFILES = \ $(srcdir)/INSTALL \ $(srcdir)/aclocal.m4 \ $(srcdir)/autoscan.log \ $(srcdir)/compile \ $(srcdir)/config.guess \ $(srcdir)/config.h.in \ $(srcdir)/config.h.in~ \ $(srcdir)/config.sub \ $(srcdir)/configure \ $(srcdir)/configure.scan \ $(srcdir)/depcomp \ $(srcdir)/install-sh \ $(srcdir)/ltmain.sh \ $(srcdir)/missing \ $(srcdir)/mkinstalldirs \ $(srcdir)/intltool-extract.in \ $(srcdir)/intltool-merge.in \ $(srcdir)/intltool-update.in \ $(srcdir)/omf.make \ $(srcdir)/xmldocs.make \ $(srcdir)/po/Makefile.in.in maemo-install: all - mkdir tmp_build cp -a Data/maemo/* tmp_build cp Src/dasher tmp_build/usr/bin/dasher strip tmp_build/usr/bin/dasher cp Data/GUI/dashermaemo.ui Data/GUI/dashermaemofullscreen.ui tmp_build/usr/share/dasher cp Data/training/training_english_GB.txt Data/alphabets/alphabet.english.xml Data/colours/colour.xml tmp_build/usr/share/dasher ln -sf /usr/share/applications/hildon/dasher.desktop tmp_build/etc/others-menu/extra_applications/0301_dasher.desktop - find tmp_build -name .git -exec rm -rf \{\} \; dpkg-deb -b tmp_build dasher_4.11.0.0inferencemaemo1_armel.deb rm -rf tmp_build diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index efa7306..acedf7e 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,157 +1,157 @@ #include "gtest/gtest.h" #include "../../Src/TestPlatform/MockInterfaceBase.h" #include "../../Src/TestPlatform/MockSettingsStore.h" #include "../../Src/DasherCore/EventHandler.h" #include "../../Src/DasherCore/SettingsStore.h" //A Dasher component that allows tests to easily determine whether //or not it was notified of an event which it subscribed to. class DummyComponent : public Dasher::CDasherComponent { public: int evtCount; std::vector<Dasher::CEvent*> receivedEvents; DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : Dasher::CDasherComponent(pEventHandler, pSettingsStore, std::vector<int>()) { evtCount = 0; } virtual void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; receivedEvents.push_back(pEvent); } }; //An extension of DummyComponent that fires a CStartEvent every time its HandleEvent is called class RecursionComponent : public DummyComponent { public: RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : DummyComponent(pEventHandler, pSettingsStore) { } void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); } }; //Test fixture - sets up the EventHandler, SettingsStore, and InterfaceBase instances. class EventTest : public ::testing::Test { public: EventTest() { interfaceBase = new CMockInterfaceBase(); evtHandler = new Dasher::CEventHandler(interfaceBase); settingsStore = new CMockSettingsStore(evtHandler); } protected: Dasher::CEventHandler *evtHandler; CMockInterfaceBase *interfaceBase; CMockSettingsStore *settingsStore; }; //very basic test - subscribe 5 components, fire one event, and assert that they all were notified TEST_F(EventTest, BasicTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 5; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } evtHandler->InsertEvent(new CParameterNotificationEvent(0)); for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { EXPECT_EQ((*iter)->evtCount, 1); } } //stress test - register a lot of listeners, fire a lot of events, and EXPECT that //everything was notified without crashing TEST_F(EventTest, StressTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 1000; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } for(int c = 0; c < 1000; c++) { evtHandler->InsertEvent(new CParameterNotificationEvent(0)); } for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { EXPECT_EQ((*iter)->evtCount, 1000); } } //test for proper behavior when components call InsertEvent in their HandleEvent TEST_F(EventTest, RecursionTest) { RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); evtHandler->RegisterListener(listener, EV_START); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(rec1->evtCount, 1); EXPECT_EQ(rec2->evtCount, 1); EXPECT_EQ(listener->evtCount, 2); } //register listeners for one event, fire a different event, and //check that they DON'T receieve that event TEST_F(EventTest, StaysQuiet) { DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); - evtHandler->RegisterListener(listener1, EV_TEXTDRAW); + evtHandler->RegisterListener(listener1, EV_GAME_NODE_DRAWN); evtHandler->RegisterListener(listener2, EV_COMMAND); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(listener1->evtCount, 0); EXPECT_EQ(listener2->evtCount, 0); } //verify that events are fired in the order we claim them to be TEST_F(EventTest, EventOrdering) { std::vector<CEvent*> events; DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(listener, EV_START); for(int c = 0; c < 5; c++) { Dasher::CStartEvent *curEvt = new Dasher::CStartEvent(); events.push_back(curEvt); evtHandler->InsertEvent(curEvt); } for(int c = 0; c < 5; c++) { EXPECT_EQ(events[c], listener->receivedEvents[c]); } }
rgee/HFOSS-Dasher
3bea8d8be0af41ad2b7089fac2e732cb84449fa6
Fixed compilation problemt in EventTest.cpp
diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index efa7306..acedf7e 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,157 +1,157 @@ #include "gtest/gtest.h" #include "../../Src/TestPlatform/MockInterfaceBase.h" #include "../../Src/TestPlatform/MockSettingsStore.h" #include "../../Src/DasherCore/EventHandler.h" #include "../../Src/DasherCore/SettingsStore.h" //A Dasher component that allows tests to easily determine whether //or not it was notified of an event which it subscribed to. class DummyComponent : public Dasher::CDasherComponent { public: int evtCount; std::vector<Dasher::CEvent*> receivedEvents; DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : Dasher::CDasherComponent(pEventHandler, pSettingsStore, std::vector<int>()) { evtCount = 0; } virtual void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; receivedEvents.push_back(pEvent); } }; //An extension of DummyComponent that fires a CStartEvent every time its HandleEvent is called class RecursionComponent : public DummyComponent { public: RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : DummyComponent(pEventHandler, pSettingsStore) { } void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); } }; //Test fixture - sets up the EventHandler, SettingsStore, and InterfaceBase instances. class EventTest : public ::testing::Test { public: EventTest() { interfaceBase = new CMockInterfaceBase(); evtHandler = new Dasher::CEventHandler(interfaceBase); settingsStore = new CMockSettingsStore(evtHandler); } protected: Dasher::CEventHandler *evtHandler; CMockInterfaceBase *interfaceBase; CMockSettingsStore *settingsStore; }; //very basic test - subscribe 5 components, fire one event, and assert that they all were notified TEST_F(EventTest, BasicTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 5; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } evtHandler->InsertEvent(new CParameterNotificationEvent(0)); for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { EXPECT_EQ((*iter)->evtCount, 1); } } //stress test - register a lot of listeners, fire a lot of events, and EXPECT that //everything was notified without crashing TEST_F(EventTest, StressTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 1000; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } for(int c = 0; c < 1000; c++) { evtHandler->InsertEvent(new CParameterNotificationEvent(0)); } for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { EXPECT_EQ((*iter)->evtCount, 1000); } } //test for proper behavior when components call InsertEvent in their HandleEvent TEST_F(EventTest, RecursionTest) { RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); evtHandler->RegisterListener(listener, EV_START); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(rec1->evtCount, 1); EXPECT_EQ(rec2->evtCount, 1); EXPECT_EQ(listener->evtCount, 2); } //register listeners for one event, fire a different event, and //check that they DON'T receieve that event TEST_F(EventTest, StaysQuiet) { DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); - evtHandler->RegisterListener(listener1, EV_TEXTDRAW); + evtHandler->RegisterListener(listener1, EV_GAME_NODE_DRAWN); evtHandler->RegisterListener(listener2, EV_COMMAND); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(listener1->evtCount, 0); EXPECT_EQ(listener2->evtCount, 0); } //verify that events are fired in the order we claim them to be TEST_F(EventTest, EventOrdering) { std::vector<CEvent*> events; DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(listener, EV_START); for(int c = 0; c < 5; c++) { Dasher::CStartEvent *curEvt = new Dasher::CStartEvent(); events.push_back(curEvt); evtHandler->InsertEvent(curEvt); } for(int c = 0; c < 5; c++) { EXPECT_EQ(events[c], listener->receivedEvents[c]); } }
rgee/HFOSS-Dasher
4b5ef3f7482289955785ddcda94b0df25a7ec6ba
Hard coded version number into configure.ac
diff --git a/configure.ac b/configure.ac index b592424..f734d3e 100644 --- a/configure.ac +++ b/configure.ac @@ -1,421 +1,419 @@ AC_PREREQ(2.59) AC_INIT([dasher], - m4_esyscmd([build-aux/mkversion]), - [http://bugzilla.gnome.org/enter_bug.cgi?product=dasher], - [dasher], + 4.11, [http://www.inference.phy.cam.ac.uk/dasher/]) # This becomes part of AC_INIT in autoconf 2.64 m4_ifndef([AC_PACKAGE_URL], [m4_define([AC_PACKAGE_URL],["http://www.inference.phy.cam.ac.uk/dasher/"]) AC_DEFINE_UNQUOTED([PACKAGE_URL], [AC_PACKAGE_URL], [Define to the home page for this package.]) AC_SUBST([PACKAGE_URL],[AC_PACKAGE_URL])]) AC_CONFIG_SRCDIR([Src/main.cc]) AC_CONFIG_HEADERS(config.h) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([m4]) -AM_INIT_AUTOMAKE([1.8 gnu check-news dist-bzip2]) +AM_INIT_AUTOMAKE AM_MAINTAINER_MODE AC_PROG_MAKE_SET # IT_PROG_INTLTOOL requires AM_NLS but ignores --enable-nls AM_NLS AM_CONDITIONAL(USE_INTLTOOL, test "x$USE_NLS" = "xyes") AS_IF([test "x$USE_NLS" = "xyes"],[ IT_PROG_INTLTOOL([0.40.1]) ], [touch po/Makefile.in.in]) dnl as intltoolize insists LT_INIT([disable-static]) dnl AM_ICONV GETTEXT_PACKAGE=dasher AC_SUBST(GETTEXT_PACKAGE) AC_DEFINE_UNQUOTED(GETTEXT_PACKAGE,"$GETTEXT_PACKAGE", [Gettext package]) AM_GLIB_GNU_GETTEXT AC_PROG_CXX AC_PROG_LD_GNU WITHGTK2=true; PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.6) AC_LANG_PUSH(C++) AC_CHECK_FUNCS(lldiv) AC_CHECK_FUNC(socket,,[AC_CHECK_LIB(socket,socket)]) AC_LANG_POP(C++) AC_ARG_ENABLE(debug, AS_HELP_STRING([--enable-debug], [build with additional debugging checks (default is NO)]), if test "x$enable_debug" = "xno"; then DEBUG=false else DEBUG=true fi, DEBUG=false) AC_ARG_WITH([gnome], AS_HELP_STRING([--with-gnome],[build GNOME documentation (default is YES)]), if test "x$with_gnome" = "xno"; then WITHGNOME=false else WITHGNOME=true # Need to work out how to translate replaced variables before uncommenting # AC_CONFIG_FILES([Data/Help/Gnome/C/dasher.xml]) fi, WITHGNOME=true) dnl Just useful for debugging AC_ARG_WITH([gvfs], AS_HELP_STRING([--with-gvfs], [build with gvfs from gio in glib (default is YES)]), [], with_gvfs="yes") if test "x$with_gvfs" != "xno"; then PKG_CHECK_MODULES(GIO, gio-2.0, [have_gio=true AC_DEFINE(HAVE_GIO, 1, [gio exists so use gvfs])], [have_gio=false]) fi AC_ARG_ENABLE([speech], AS_HELP_STRING([--enable-speech],[build with speech support (default is NO)]), if test "x$enableval" = "xno"; then WITHSPEECH=false; else WITHSPEECH=true; fi, WITHSPEECH=false) AC_ARG_WITH([qte], AS_HELP_STRING([--with-qte],[build with QTE support (default is NO -- currently untested)]), if test "x$withval" = "xno"; then WITHQTE=false; else WITHQTE=true; fi, WITHQTE=false) AC_ARG_WITH([gpe], AS_HELP_STRING([--with-gpe],[build with GPE support (default is NO -- currently untested)]), if test "x$withval" = "xno"; then WITHGPE=false; else WITHGPE=true; fi, WITHGPE=false) AC_ARG_ENABLE([a11y], AS_HELP_STRING([--enable-a11y],[build with support for the GNOME accessibility framework (default is YES)]), if test "x$enableval" = "xno"; then WITHA11Y=false; else WITHA11Y=true; fi, WITHA11Y=true) AC_ARG_ENABLE([japanese], AS_HELP_STRING([--enable-japanese],[build with support for Japanese Kanji entry (experimental -- default is NO)]), if test "x$enableval" = "xno"; then WITHJAPANESE=false; else AC_CHECK_LIB(canna, RkBgnBun,, AC_MSG_ERROR([Canna library not found (required for Japanese).])) WITHJAPANESE=true; fi, WITHJAPANESE=false) AC_ARG_ENABLE([joystick], AS_HELP_STRING([--enable-joystick],[Build with Linux joystick support (note that other UNIX based operating systems aren't supported here)]), if test "x$enableval" = "xno"; then WITHJOYSTICK=false; else WITHJOYSTICK=true; fi, WITHJOYSTICK=false) AC_ARG_ENABLE([tilt], AS_HELP_STRING([--enable-tilt],[Build with experimental support for tilt sensor input (experimental -- default is NO)]), if test "x$enableval" = "xno"; then WITHTILT=false; else WITHTILT=true; fi, WITHTILT=false) AC_ARG_WITH([maemo], AS_HELP_STRING([--with-maemo],[build with Maemo support (default is NO)]), if test "x$withval" = "xyes"; then WITHMAEMO=true; WITHGNOME=false; WITHA11Y=false; else WITHMAEMO=false; fi, WITHMAEMO=false) AC_ARG_WITH([maemo-fullscreen], AS_HELP_STRING([--with-maemo-fullscreen],[build as standalone Maemo fullscreen app (default is NO)]), if test "x$withval" = "xyes"; then WITHMAEMOFULLSCREEN=true; WITHMAEMO=true; WITHGNOME=false; WITHA11Y=false; else WITHMAEMOFULLSCREEN=false; fi, WITHMAEMOFULLSCREEN=false) dnl AC_ARG_WITH([darwin], dnl AS_HELP_STRING([--with-darwin],[build with Darwin (Mac OS X) support (default is NO)]), dnl if test "x$withval" = "xyes"; then dnl WITHDARWIN=true; dnl else dnl WITHDARWIN=false; dnl fi, dnl WITHDARWIN=false) AC_ARG_WITH([cairo], AS_HELP_STRING([--with-cairo],[build with cairo support (default is YES)]), if test "x$withval" = "xno"; then WITHCAIRO=false; else WITHCAIRO=true; fi, WITHCAIRO=true) if test x"$WITHGTK2" = xtrue then PKG_CHECK_MODULES(GTK2, gtk+-2.0 >= 2.6.0,[GTK2HERE=true],[GTK2HERE=false]) fi if test x"$GTK2HERE" = xtrue -a x"$WITHGTK2" = xtrue -a x"$WITHQTE" != xtrue then BUILDGTK2=true elif test x"$GTK2HERE" = xtrue -a x"$WITHQTE" != xtrue then BUILDGTK2=true else BUILDGTK2=false fi DAM_GCONF_SOURCE_2 if test x$BUILDGTK2 = xtrue then PKG_CHECK_MODULES(GCONF, gconf-2.0, [AC_DEFINE([WITH_GCONF], 1, [Use GConf])], [AC_MSG_WARN([GConf was not detected - user preferences will not be stored.])]) save_CFLAGS="$CFLAGS" save_LIBS="$LIBS" CFLAGS="$CFLAGS $GTK2_CFLAGS" LIBS="$LIBS $GTK2_LIBS" AC_CHECK_FUNCS([gtk_builder_new gtk_show_uri], [], [if test "x$ac_cv_func_gtk_builder_new" = "xno"; then AC_MSG_ERROR([A version of GTK+ providing GtkBuilder is necessary.]) fi if test "x$ac_cv_func_gtk_show_uri" = "xno"; then AC_MSG_WARN([This version of GTK+ doesn't provide gtk_show_uri - help will not be displayed from within dasher.]) fi] ) CFLAGS="$save_CFLAGS" LIBS="$save_LIBS" # GtkBuilder's autoconnect feature requires dasher to be linked with # the --export-dynamic flag. pkg-config does not provide it, and libtool # knows what to do with -export-dynamic. # (We need this e.g., for <object class="DasherEditor">) GTK2_LIBS="$GTK2_LIBS -export-dynamic" else AC_MSG_ERROR("Unable to find GTK2 or another necessary library.") fi if test x"$DEBUG" = xtrue; then AC_DEFINE([DEBUG], 1, [Additional debug checks enabled]) fi if test x"$WITHSPEECH" = xtrue; then PKG_CHECK_MODULES(gnome_speech, gnome-speech-1.0 bonobo-activation-2.0 libbonobo-2.0 ORBit-2.0) AC_DEFINE([GNOME_SPEECH], 1, [gnome_speech-1 libraries are present]) # SPEECH_SOURCES='speech.$(OBJEXT)' fi if test x"$WITHA11Y" = xtrue; then PKG_CHECK_MODULES(gnome_a11y, bonobo-activation-2.0 libbonobo-2.0 ORBit-2.0 libgnomeui-2.0 cspi-1.0 atk) AC_DEFINE([GNOME_A11Y], 1, [gnome_a11y libraries are present]) fi AC_PATH_XTRA AC_CHECK_LIB(expat, XML_Parse,,[ if test x$no_x = xyes ; then AC_MSG_ERROR([Expat library not found.]) else CPPFLAGS="$CPPFLAGS $X_CFLAGS" LDFLAGS="$LDFLAGS $X_LIBS" dnl Check for different function to avoid cached "no" result. AC_CHECK_LIB(expat, XML_SetElementHandler,, [AC_MSG_ERROR([Expat library not found.])]) fi ]) if test x"$WITHQTE" != xtrue -a x"$WITHA11Y" != xtrue; then if test x$no_x = xyes ; then AC_MSG_ERROR([X development libraries not found]) else X_LIBS="$X_LIBS $X_PRE_LIBS -lX11 $X_EXTRA_LIBS" fi save_LIBS="$LIBS" AC_CHECK_LIB([Xtst], [XTestFakeKeyEvent], [X_LIBS="$X_LIBS -lXtst" AC_DEFINE(HAVE_XTST, 1, [The XTest extension is present])], [AC_MSG_ERROR([Couldn't find the Xtst library. Check config.log for details])], $X_LIBS) LIBS="$save_LIBS" AC_SUBST(X_LIBS) fi if test x"$WITHJAPANESE" = xtrue; then AC_DEFINE([JAPANESE], 1, [Japanese support enabled]) JAPANESE_SOURCES='CannaConversionHelper.$(OBJEXT)' else JAPANESE_SOURCES= fi AC_SUBST(JAPANESE_SOURCES) if test x"$WITHJOYSTICK" = xtrue; then AC_DEFINE([JOYSTICK], 1, [Linux joystick support enabled]) fi if test x"$WITHTILT" = xtrue; then AC_DEFINE([TILT], 1, [Tilt input support enabled]) fi if test x"$WITHGPE" = xtrue; then AC_DEFINE([WITH_GPE], 1, [gpe is present]) fi dnl if test x"$WITHDARWIN" = xtrue ; then dnl AC_DEFINE([WITH_DARWIN], 1, [Targeting Darwin/X11]) dnl fi if test x"$WITHMAEMO" = xtrue; then AC_DEFINE([WITH_MAEMO], 1, [Maemo is present]) PKG_CHECK_MODULES(hildon, hildon-libs) AC_CHECK_LIB(osso, osso_initialize,, AC_MSG_ERROR([Osso library not found.])) fi if test x"$WITHMAEMOFULLSCREEN" = xtrue; then AC_DEFINE([WITH_MAEMOFULLSCREEN], 1, [Building as fullscreen Maemo app]) fi if test x"$WITHCAIRO" = xtrue; then PKG_CHECK_MODULES(cairo, gtk+-2.0 >= 2.8.0) AC_DEFINE([WITH_CAIRO], 1, [use cairo (needs Gtk+ >= 2.8.0)]) fi if test x"$BUILDGTK2" = xtrue; then PKG_CHECK_MODULES(gthread, gthread-2.0) fi AC_SUBST(gnome_speech_LIBS) AC_SUBST(gnome_speech_CFLAGS) AC_SUBST([SPEECH_SOURCES]) AC_SUBST(gnome_a11y_LIBS) AC_SUBST(gnome_a11y_CFLAGS) AC_SUBST([A11Y_SOURCES]) AC_SUBST(gnome_LIBS) AC_SUBST(gnome_CFLAGS) AC_SUBST(gthread_LIBS) AC_SUBST(gthread_CFLAGS) AC_SUBST(hildon_LIBS) AC_SUBST(hildon_CFLAGS) AC_SUBST(GETTEXT_PACKAGE) AM_CONDITIONAL(DOGTK2, test x$BUILDGTK2 = xtrue) AM_CONDITIONAL(DOQTE, test x$WITHQTE = xtrue) AM_CONDITIONAL(GNOME_SPEECH, test x$WITHSPEECH = xtrue) AM_CONDITIONAL(GNOME_A11Y, test x$WITHA11Y = xtrue) AM_CONDITIONAL(GNOME_HELP, test x$WITHGNOME = xtrue) AM_CONDITIONAL(WITH_GPE, test x$WITHGPE = xtrue) AM_CONDITIONAL(WITH_MAEMO, test x$WITHMAEMO = xtrue) AM_CONDITIONAL(WITH_MAEMOFULLSCREEN, test x$WITHMAEMOFULLSCREEN = xtrue) AM_CONDITIONAL(JAPANESE, test x$WITHJAPANESE = xtrue) AM_CONDITIONAL(JOYSTICK, test x$WITHJOYSTICK = xtrue) AC_SUBST(GTK2_CFLAGS) AC_SUBST(GTK2_LIBS) AC_SUBST(GCONF_CFLAGS) AC_SUBST(GCONF_LIBS) if test x"$WITHGPE" = xtrue ; then SETTINGS_CFLAGS=" " SETTINGS_LIBS="-lgpewidget -lXsettings-client -lXsettings" else SETTINGS_CFLAGS=$GCONF_CFLAGS SETTINGS_LIBS=$GCONF_LIBS fi AC_SUBST(SETTINGS_CFLAGS) AC_SUBST(SETTINGS_LIBS) GTK2BUILD_CFLAGS="$GTK2_CFLAGS $GIO_CFLAGS $SETTINGS_CFLAGS $gthread_CFLAGS $gnome_speech_CFLAGS $gnome_a11y_CFLAGS $gnome_CFLAGS $hildon_CFLAGS" GTK2BUILD_LIBS="$X_LIBS $GTK2_LIBS $GIO_LIBS $SETTINGS_LIBS $gthread_LIBS $gnome_speech_LIBS $gnome_a11y_LIBS $gnome_LIBS $hildon_LIBS" AC_SUBST(GTK2BUILD_CFLAGS) AC_SUBST(GTK2BUILD_LIBS) AC_MSG_CHECKING([for gnome-doc-utils]) dnl Avoid default action which is to complain if not found GNOME_DOC_INIT([0.9.0],[gdu_cv_have_gdu=yes],[gdu_cv_have_gdu=no]) AC_MSG_RESULT($gdu_cv_have_gdu) if test x"$WITHGNOME" = xtrue -a x"$gdu_cv_have_gdu" = xno ; then AC_MSG_ERROR([gnome-doc-utils not found!]) fi dnl XXX PRLW How is this better than the standard dnl gdu_cv_have_gdu && enable_scrollkeeper ? AM_CONDITIONAL(ENABLE_SK, test x"$WITHGNOME" = xfalse -a x"$enable_scrollkeeper" = "xyes") AC_CONFIG_FILES([Data/dasher.desktop.in Data/Makefile Data/training/Makefile Data/alphabets/Makefile Data/colours/Makefile Data/controllabels/Makefile Data/GUI/Makefile Data/Help/Makefile Data/Help/Gnome/Makefile Doc/Makefile Doc/user/Makefile Makefile Src/Makefile Src/Common/Makefile Src/DasherCore/Makefile Src/DasherCore/LanguageModelling/Makefile Src/DasherIM/Makefile Src/Gtk2/Makefile Src/Installer/Makefile Src/InstallerTobii/Makefile Src/InstallerW2K/Makefile Src/Win32/Makefile po/Makefile.in ]) AC_OUTPUT
rgee/HFOSS-Dasher
655502a996a6d7aaf5b4690dd421b4e325b7700f
Hard coded version number for now. m4 macro to get version number does not work. Specifically, git describe --abbrev=4 gives an error
diff --git a/configure.ac b/configure.ac index b592424..8464f11 100644 --- a/configure.ac +++ b/configure.ac @@ -1,421 +1,417 @@ AC_PREREQ(2.59) -AC_INIT([dasher], - m4_esyscmd([build-aux/mkversion]), - [http://bugzilla.gnome.org/enter_bug.cgi?product=dasher], - [dasher], - [http://www.inference.phy.cam.ac.uk/dasher/]) +AC_INIT([dasher],[4.11]) # This becomes part of AC_INIT in autoconf 2.64 m4_ifndef([AC_PACKAGE_URL], [m4_define([AC_PACKAGE_URL],["http://www.inference.phy.cam.ac.uk/dasher/"]) AC_DEFINE_UNQUOTED([PACKAGE_URL], [AC_PACKAGE_URL], [Define to the home page for this package.]) AC_SUBST([PACKAGE_URL],[AC_PACKAGE_URL])]) AC_CONFIG_SRCDIR([Src/main.cc]) AC_CONFIG_HEADERS(config.h) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE([1.8 gnu check-news dist-bzip2]) AM_MAINTAINER_MODE AC_PROG_MAKE_SET # IT_PROG_INTLTOOL requires AM_NLS but ignores --enable-nls AM_NLS AM_CONDITIONAL(USE_INTLTOOL, test "x$USE_NLS" = "xyes") AS_IF([test "x$USE_NLS" = "xyes"],[ IT_PROG_INTLTOOL([0.40.1]) ], [touch po/Makefile.in.in]) dnl as intltoolize insists LT_INIT([disable-static]) dnl AM_ICONV GETTEXT_PACKAGE=dasher AC_SUBST(GETTEXT_PACKAGE) AC_DEFINE_UNQUOTED(GETTEXT_PACKAGE,"$GETTEXT_PACKAGE", [Gettext package]) AM_GLIB_GNU_GETTEXT AC_PROG_CXX AC_PROG_LD_GNU WITHGTK2=true; PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.6) AC_LANG_PUSH(C++) AC_CHECK_FUNCS(lldiv) AC_CHECK_FUNC(socket,,[AC_CHECK_LIB(socket,socket)]) AC_LANG_POP(C++) AC_ARG_ENABLE(debug, AS_HELP_STRING([--enable-debug], [build with additional debugging checks (default is NO)]), if test "x$enable_debug" = "xno"; then DEBUG=false else DEBUG=true fi, DEBUG=false) AC_ARG_WITH([gnome], AS_HELP_STRING([--with-gnome],[build GNOME documentation (default is YES)]), if test "x$with_gnome" = "xno"; then WITHGNOME=false else WITHGNOME=true # Need to work out how to translate replaced variables before uncommenting # AC_CONFIG_FILES([Data/Help/Gnome/C/dasher.xml]) fi, WITHGNOME=true) dnl Just useful for debugging AC_ARG_WITH([gvfs], AS_HELP_STRING([--with-gvfs], [build with gvfs from gio in glib (default is YES)]), [], with_gvfs="yes") if test "x$with_gvfs" != "xno"; then PKG_CHECK_MODULES(GIO, gio-2.0, [have_gio=true AC_DEFINE(HAVE_GIO, 1, [gio exists so use gvfs])], [have_gio=false]) fi AC_ARG_ENABLE([speech], AS_HELP_STRING([--enable-speech],[build with speech support (default is NO)]), if test "x$enableval" = "xno"; then WITHSPEECH=false; else WITHSPEECH=true; fi, WITHSPEECH=false) AC_ARG_WITH([qte], AS_HELP_STRING([--with-qte],[build with QTE support (default is NO -- currently untested)]), if test "x$withval" = "xno"; then WITHQTE=false; else WITHQTE=true; fi, WITHQTE=false) AC_ARG_WITH([gpe], AS_HELP_STRING([--with-gpe],[build with GPE support (default is NO -- currently untested)]), if test "x$withval" = "xno"; then WITHGPE=false; else WITHGPE=true; fi, WITHGPE=false) AC_ARG_ENABLE([a11y], AS_HELP_STRING([--enable-a11y],[build with support for the GNOME accessibility framework (default is YES)]), if test "x$enableval" = "xno"; then WITHA11Y=false; else WITHA11Y=true; fi, WITHA11Y=true) AC_ARG_ENABLE([japanese], AS_HELP_STRING([--enable-japanese],[build with support for Japanese Kanji entry (experimental -- default is NO)]), if test "x$enableval" = "xno"; then WITHJAPANESE=false; else AC_CHECK_LIB(canna, RkBgnBun,, AC_MSG_ERROR([Canna library not found (required for Japanese).])) WITHJAPANESE=true; fi, WITHJAPANESE=false) AC_ARG_ENABLE([joystick], AS_HELP_STRING([--enable-joystick],[Build with Linux joystick support (note that other UNIX based operating systems aren't supported here)]), if test "x$enableval" = "xno"; then WITHJOYSTICK=false; else WITHJOYSTICK=true; fi, WITHJOYSTICK=false) AC_ARG_ENABLE([tilt], AS_HELP_STRING([--enable-tilt],[Build with experimental support for tilt sensor input (experimental -- default is NO)]), if test "x$enableval" = "xno"; then WITHTILT=false; else WITHTILT=true; fi, WITHTILT=false) AC_ARG_WITH([maemo], AS_HELP_STRING([--with-maemo],[build with Maemo support (default is NO)]), if test "x$withval" = "xyes"; then WITHMAEMO=true; WITHGNOME=false; WITHA11Y=false; else WITHMAEMO=false; fi, WITHMAEMO=false) AC_ARG_WITH([maemo-fullscreen], AS_HELP_STRING([--with-maemo-fullscreen],[build as standalone Maemo fullscreen app (default is NO)]), if test "x$withval" = "xyes"; then WITHMAEMOFULLSCREEN=true; WITHMAEMO=true; WITHGNOME=false; WITHA11Y=false; else WITHMAEMOFULLSCREEN=false; fi, WITHMAEMOFULLSCREEN=false) dnl AC_ARG_WITH([darwin], dnl AS_HELP_STRING([--with-darwin],[build with Darwin (Mac OS X) support (default is NO)]), dnl if test "x$withval" = "xyes"; then dnl WITHDARWIN=true; dnl else dnl WITHDARWIN=false; dnl fi, dnl WITHDARWIN=false) AC_ARG_WITH([cairo], AS_HELP_STRING([--with-cairo],[build with cairo support (default is YES)]), if test "x$withval" = "xno"; then WITHCAIRO=false; else WITHCAIRO=true; fi, WITHCAIRO=true) if test x"$WITHGTK2" = xtrue then PKG_CHECK_MODULES(GTK2, gtk+-2.0 >= 2.6.0,[GTK2HERE=true],[GTK2HERE=false]) fi if test x"$GTK2HERE" = xtrue -a x"$WITHGTK2" = xtrue -a x"$WITHQTE" != xtrue then BUILDGTK2=true elif test x"$GTK2HERE" = xtrue -a x"$WITHQTE" != xtrue then BUILDGTK2=true else BUILDGTK2=false fi DAM_GCONF_SOURCE_2 if test x$BUILDGTK2 = xtrue then PKG_CHECK_MODULES(GCONF, gconf-2.0, [AC_DEFINE([WITH_GCONF], 1, [Use GConf])], [AC_MSG_WARN([GConf was not detected - user preferences will not be stored.])]) save_CFLAGS="$CFLAGS" save_LIBS="$LIBS" CFLAGS="$CFLAGS $GTK2_CFLAGS" LIBS="$LIBS $GTK2_LIBS" AC_CHECK_FUNCS([gtk_builder_new gtk_show_uri], [], [if test "x$ac_cv_func_gtk_builder_new" = "xno"; then AC_MSG_ERROR([A version of GTK+ providing GtkBuilder is necessary.]) fi if test "x$ac_cv_func_gtk_show_uri" = "xno"; then AC_MSG_WARN([This version of GTK+ doesn't provide gtk_show_uri - help will not be displayed from within dasher.]) fi] ) CFLAGS="$save_CFLAGS" LIBS="$save_LIBS" # GtkBuilder's autoconnect feature requires dasher to be linked with # the --export-dynamic flag. pkg-config does not provide it, and libtool # knows what to do with -export-dynamic. # (We need this e.g., for <object class="DasherEditor">) GTK2_LIBS="$GTK2_LIBS -export-dynamic" else AC_MSG_ERROR("Unable to find GTK2 or another necessary library.") fi if test x"$DEBUG" = xtrue; then AC_DEFINE([DEBUG], 1, [Additional debug checks enabled]) fi if test x"$WITHSPEECH" = xtrue; then PKG_CHECK_MODULES(gnome_speech, gnome-speech-1.0 bonobo-activation-2.0 libbonobo-2.0 ORBit-2.0) AC_DEFINE([GNOME_SPEECH], 1, [gnome_speech-1 libraries are present]) # SPEECH_SOURCES='speech.$(OBJEXT)' fi if test x"$WITHA11Y" = xtrue; then PKG_CHECK_MODULES(gnome_a11y, bonobo-activation-2.0 libbonobo-2.0 ORBit-2.0 libgnomeui-2.0 cspi-1.0 atk) AC_DEFINE([GNOME_A11Y], 1, [gnome_a11y libraries are present]) fi AC_PATH_XTRA AC_CHECK_LIB(expat, XML_Parse,,[ if test x$no_x = xyes ; then AC_MSG_ERROR([Expat library not found.]) else CPPFLAGS="$CPPFLAGS $X_CFLAGS" LDFLAGS="$LDFLAGS $X_LIBS" dnl Check for different function to avoid cached "no" result. AC_CHECK_LIB(expat, XML_SetElementHandler,, [AC_MSG_ERROR([Expat library not found.])]) fi ]) if test x"$WITHQTE" != xtrue -a x"$WITHA11Y" != xtrue; then if test x$no_x = xyes ; then AC_MSG_ERROR([X development libraries not found]) else X_LIBS="$X_LIBS $X_PRE_LIBS -lX11 $X_EXTRA_LIBS" fi save_LIBS="$LIBS" AC_CHECK_LIB([Xtst], [XTestFakeKeyEvent], [X_LIBS="$X_LIBS -lXtst" AC_DEFINE(HAVE_XTST, 1, [The XTest extension is present])], [AC_MSG_ERROR([Couldn't find the Xtst library. Check config.log for details])], $X_LIBS) LIBS="$save_LIBS" AC_SUBST(X_LIBS) fi if test x"$WITHJAPANESE" = xtrue; then AC_DEFINE([JAPANESE], 1, [Japanese support enabled]) JAPANESE_SOURCES='CannaConversionHelper.$(OBJEXT)' else JAPANESE_SOURCES= fi AC_SUBST(JAPANESE_SOURCES) if test x"$WITHJOYSTICK" = xtrue; then AC_DEFINE([JOYSTICK], 1, [Linux joystick support enabled]) fi if test x"$WITHTILT" = xtrue; then AC_DEFINE([TILT], 1, [Tilt input support enabled]) fi if test x"$WITHGPE" = xtrue; then AC_DEFINE([WITH_GPE], 1, [gpe is present]) fi dnl if test x"$WITHDARWIN" = xtrue ; then dnl AC_DEFINE([WITH_DARWIN], 1, [Targeting Darwin/X11]) dnl fi if test x"$WITHMAEMO" = xtrue; then AC_DEFINE([WITH_MAEMO], 1, [Maemo is present]) PKG_CHECK_MODULES(hildon, hildon-libs) AC_CHECK_LIB(osso, osso_initialize,, AC_MSG_ERROR([Osso library not found.])) fi if test x"$WITHMAEMOFULLSCREEN" = xtrue; then AC_DEFINE([WITH_MAEMOFULLSCREEN], 1, [Building as fullscreen Maemo app]) fi if test x"$WITHCAIRO" = xtrue; then PKG_CHECK_MODULES(cairo, gtk+-2.0 >= 2.8.0) AC_DEFINE([WITH_CAIRO], 1, [use cairo (needs Gtk+ >= 2.8.0)]) fi if test x"$BUILDGTK2" = xtrue; then PKG_CHECK_MODULES(gthread, gthread-2.0) fi AC_SUBST(gnome_speech_LIBS) AC_SUBST(gnome_speech_CFLAGS) AC_SUBST([SPEECH_SOURCES]) AC_SUBST(gnome_a11y_LIBS) AC_SUBST(gnome_a11y_CFLAGS) AC_SUBST([A11Y_SOURCES]) AC_SUBST(gnome_LIBS) AC_SUBST(gnome_CFLAGS) AC_SUBST(gthread_LIBS) AC_SUBST(gthread_CFLAGS) AC_SUBST(hildon_LIBS) AC_SUBST(hildon_CFLAGS) AC_SUBST(GETTEXT_PACKAGE) AM_CONDITIONAL(DOGTK2, test x$BUILDGTK2 = xtrue) AM_CONDITIONAL(DOQTE, test x$WITHQTE = xtrue) AM_CONDITIONAL(GNOME_SPEECH, test x$WITHSPEECH = xtrue) AM_CONDITIONAL(GNOME_A11Y, test x$WITHA11Y = xtrue) AM_CONDITIONAL(GNOME_HELP, test x$WITHGNOME = xtrue) AM_CONDITIONAL(WITH_GPE, test x$WITHGPE = xtrue) AM_CONDITIONAL(WITH_MAEMO, test x$WITHMAEMO = xtrue) AM_CONDITIONAL(WITH_MAEMOFULLSCREEN, test x$WITHMAEMOFULLSCREEN = xtrue) AM_CONDITIONAL(JAPANESE, test x$WITHJAPANESE = xtrue) AM_CONDITIONAL(JOYSTICK, test x$WITHJOYSTICK = xtrue) AC_SUBST(GTK2_CFLAGS) AC_SUBST(GTK2_LIBS) AC_SUBST(GCONF_CFLAGS) AC_SUBST(GCONF_LIBS) if test x"$WITHGPE" = xtrue ; then SETTINGS_CFLAGS=" " SETTINGS_LIBS="-lgpewidget -lXsettings-client -lXsettings" else SETTINGS_CFLAGS=$GCONF_CFLAGS SETTINGS_LIBS=$GCONF_LIBS fi AC_SUBST(SETTINGS_CFLAGS) AC_SUBST(SETTINGS_LIBS) GTK2BUILD_CFLAGS="$GTK2_CFLAGS $GIO_CFLAGS $SETTINGS_CFLAGS $gthread_CFLAGS $gnome_speech_CFLAGS $gnome_a11y_CFLAGS $gnome_CFLAGS $hildon_CFLAGS" GTK2BUILD_LIBS="$X_LIBS $GTK2_LIBS $GIO_LIBS $SETTINGS_LIBS $gthread_LIBS $gnome_speech_LIBS $gnome_a11y_LIBS $gnome_LIBS $hildon_LIBS" AC_SUBST(GTK2BUILD_CFLAGS) AC_SUBST(GTK2BUILD_LIBS) AC_MSG_CHECKING([for gnome-doc-utils]) dnl Avoid default action which is to complain if not found GNOME_DOC_INIT([0.9.0],[gdu_cv_have_gdu=yes],[gdu_cv_have_gdu=no]) AC_MSG_RESULT($gdu_cv_have_gdu) if test x"$WITHGNOME" = xtrue -a x"$gdu_cv_have_gdu" = xno ; then AC_MSG_ERROR([gnome-doc-utils not found!]) fi dnl XXX PRLW How is this better than the standard dnl gdu_cv_have_gdu && enable_scrollkeeper ? AM_CONDITIONAL(ENABLE_SK, test x"$WITHGNOME" = xfalse -a x"$enable_scrollkeeper" = "xyes") AC_CONFIG_FILES([Data/dasher.desktop.in Data/Makefile Data/training/Makefile Data/alphabets/Makefile Data/colours/Makefile Data/controllabels/Makefile Data/GUI/Makefile Data/Help/Makefile Data/Help/Gnome/Makefile Doc/Makefile Doc/user/Makefile Makefile Src/Makefile Src/Common/Makefile Src/DasherCore/Makefile Src/DasherCore/LanguageModelling/Makefile Src/DasherIM/Makefile Src/Gtk2/Makefile Src/Installer/Makefile Src/InstallerTobii/Makefile Src/InstallerW2K/Makefile Src/Win32/Makefile po/Makefile.in ]) AC_OUTPUT
rgee/HFOSS-Dasher
2fd3b5c21f71e3823c5c2a42e55cf6ffd4094832
Added m4's in gtest. This better work
diff --git a/Testing/gtest/m4/acx_pthread.m4 b/Testing/gtest/m4/acx_pthread.m4 new file mode 100644 index 0000000..2cf20de --- /dev/null +++ b/Testing/gtest/m4/acx_pthread.m4 @@ -0,0 +1,363 @@ +# This was retrieved from +# http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?revision=1277&root=avahi +# See also (perhaps for new versions?) +# http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?root=avahi +# +# We've rewritten the inconsistency check code (from avahi), to work +# more broadly. In particular, it no longer assumes ld accepts -zdefs. +# This caused a restructing of the code, but the functionality has only +# changed a little. + +dnl @synopsis ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]]) +dnl +dnl @summary figure out how to build C programs using POSIX threads +dnl +dnl This macro figures out how to build C programs using POSIX threads. +dnl It sets the PTHREAD_LIBS output variable to the threads library and +dnl linker flags, and the PTHREAD_CFLAGS output variable to any special +dnl C compiler flags that are needed. (The user can also force certain +dnl compiler flags/libs to be tested by setting these environment +dnl variables.) +dnl +dnl Also sets PTHREAD_CC to any special C compiler that is needed for +dnl multi-threaded programs (defaults to the value of CC otherwise). +dnl (This is necessary on AIX to use the special cc_r compiler alias.) +dnl +dnl NOTE: You are assumed to not only compile your program with these +dnl flags, but also link it with them as well. e.g. you should link +dnl with $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS +dnl $LIBS +dnl +dnl If you are only building threads programs, you may wish to use +dnl these variables in your default LIBS, CFLAGS, and CC: +dnl +dnl LIBS="$PTHREAD_LIBS $LIBS" +dnl CFLAGS="$CFLAGS $PTHREAD_CFLAGS" +dnl CC="$PTHREAD_CC" +dnl +dnl In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute +dnl constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to +dnl that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX). +dnl +dnl ACTION-IF-FOUND is a list of shell commands to run if a threads +dnl library is found, and ACTION-IF-NOT-FOUND is a list of commands to +dnl run it if it is not found. If ACTION-IF-FOUND is not specified, the +dnl default action will define HAVE_PTHREAD. +dnl +dnl Please let the authors know if this macro fails on any platform, or +dnl if you have any other suggestions or comments. This macro was based +dnl on work by SGJ on autoconf scripts for FFTW (www.fftw.org) (with +dnl help from M. Frigo), as well as ac_pthread and hb_pthread macros +dnl posted by Alejandro Forero Cuervo to the autoconf macro repository. +dnl We are also grateful for the helpful feedback of numerous users. +dnl +dnl @category InstalledPackages +dnl @author Steven G. Johnson <[email protected]> +dnl @version 2006-05-29 +dnl @license GPLWithACException +dnl +dnl Checks for GCC shared/pthread inconsistency based on work by +dnl Marcin Owsiany <[email protected]> + + +AC_DEFUN([ACX_PTHREAD], [ +AC_REQUIRE([AC_CANONICAL_HOST]) +AC_LANG_SAVE +AC_LANG_C +acx_pthread_ok=no + +# We used to check for pthread.h first, but this fails if pthread.h +# requires special compiler flags (e.g. on True64 or Sequent). +# It gets checked for in the link test anyway. + +# First of all, check if the user has set any of the PTHREAD_LIBS, +# etcetera environment variables, and if threads linking works using +# them: +if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then + save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + save_LIBS="$LIBS" + LIBS="$PTHREAD_LIBS $LIBS" + AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS]) + AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes) + AC_MSG_RESULT($acx_pthread_ok) + if test x"$acx_pthread_ok" = xno; then + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" + fi + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" +fi + +# We must check for the threads library under a number of different +# names; the ordering is very important because some systems +# (e.g. DEC) have both -lpthread and -lpthreads, where one of the +# libraries is broken (non-POSIX). + +# Create a list of thread flags to try. Items starting with a "-" are +# C compiler flags, and other items are library names, except for "none" +# which indicates that we try without any flags at all, and "pthread-config" +# which is a program returning the flags for the Pth emulation library. + +acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config" + +# The ordering *is* (sometimes) important. Some notes on the +# individual items follow: + +# pthreads: AIX (must check this before -lpthread) +# none: in case threads are in libc; should be tried before -Kthread and +# other compiler flags to prevent continual compiler warnings +# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h) +# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able) +# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread) +# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads) +# -pthreads: Solaris/gcc +# -mthreads: Mingw32/gcc, Lynx/gcc +# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it +# doesn't hurt to check since this sometimes defines pthreads too; +# also defines -D_REENTRANT) +# ... -mt is also the pthreads flag for HP/aCC +# pthread: Linux, etcetera +# --thread-safe: KAI C++ +# pthread-config: use pthread-config program (for GNU Pth library) + +case "${host_cpu}-${host_os}" in + *solaris*) + + # On Solaris (at least, for some versions), libc contains stubbed + # (non-functional) versions of the pthreads routines, so link-based + # tests will erroneously succeed. (We need to link with -pthreads/-mt/ + # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather + # a function called by this macro, so we could check for that, but + # who knows whether they'll stub that too in a future libc.) So, + # we'll just look for -pthreads and -lpthread first: + + acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags" + ;; +esac + +if test x"$acx_pthread_ok" = xno; then +for flag in $acx_pthread_flags; do + + case $flag in + none) + AC_MSG_CHECKING([whether pthreads work without any flags]) + ;; + + -*) + AC_MSG_CHECKING([whether pthreads work with $flag]) + PTHREAD_CFLAGS="$flag" + ;; + + pthread-config) + AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no) + if test x"$acx_pthread_config" = xno; then continue; fi + PTHREAD_CFLAGS="`pthread-config --cflags`" + PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`" + ;; + + *) + AC_MSG_CHECKING([for the pthreads library -l$flag]) + PTHREAD_LIBS="-l$flag" + ;; + esac + + save_LIBS="$LIBS" + save_CFLAGS="$CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + # Check for various functions. We must include pthread.h, + # since some functions may be macros. (On the Sequent, we + # need a special flag -Kthread to make this header compile.) + # We check for pthread_join because it is in -lpthread on IRIX + # while pthread_create is in libc. We check for pthread_attr_init + # due to DEC craziness with -lpthreads. We check for + # pthread_cleanup_push because it is one of the few pthread + # functions on Solaris that doesn't have a non-functional libc stub. + # We try pthread_create on general principles. + AC_TRY_LINK([#include <pthread.h>], + [pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], + [acx_pthread_ok=yes]) + + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + + AC_MSG_RESULT($acx_pthread_ok) + if test "x$acx_pthread_ok" = xyes; then + break; + fi + + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" +done +fi + +# Various other checks: +if test "x$acx_pthread_ok" = xyes; then + save_LIBS="$LIBS" + LIBS="$PTHREAD_LIBS $LIBS" + save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + # Detect AIX lossage: JOINABLE attribute is called UNDETACHED. + AC_MSG_CHECKING([for joinable pthread attribute]) + attr_name=unknown + for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do + AC_TRY_LINK([#include <pthread.h>], [int attr=$attr; return attr;], + [attr_name=$attr; break]) + done + AC_MSG_RESULT($attr_name) + if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then + AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name, + [Define to necessary symbol if this constant + uses a non-standard name on your system.]) + fi + + AC_MSG_CHECKING([if more special flags are required for pthreads]) + flag=no + case "${host_cpu}-${host_os}" in + *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";; + *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";; + esac + AC_MSG_RESULT(${flag}) + if test "x$flag" != xno; then + PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS" + fi + + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + # More AIX lossage: must compile with xlc_r or cc_r + if test x"$GCC" != xyes; then + AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC}) + else + PTHREAD_CC=$CC + fi + + # The next part tries to detect GCC inconsistency with -shared on some + # architectures and systems. The problem is that in certain + # configurations, when -shared is specified, GCC "forgets" to + # internally use various flags which are still necessary. + + # + # Prepare the flags + # + save_CFLAGS="$CFLAGS" + save_LIBS="$LIBS" + save_CC="$CC" + + # Try with the flags determined by the earlier checks. + # + # -Wl,-z,defs forces link-time symbol resolution, so that the + # linking checks with -shared actually have any value + # + # FIXME: -fPIC is required for -shared on many architectures, + # so we specify it here, but the right way would probably be to + # properly detect whether it is actually required. + CFLAGS="-shared -fPIC -Wl,-z,defs $CFLAGS $PTHREAD_CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + CC="$PTHREAD_CC" + + # In order not to create several levels of indentation, we test + # the value of "$done" until we find the cure or run out of ideas. + done="no" + + # First, make sure the CFLAGS we added are actually accepted by our + # compiler. If not (and OS X's ld, for instance, does not accept -z), + # then we can't do this test. + if test x"$done" = xno; then + AC_MSG_CHECKING([whether to check for GCC pthread/shared inconsistencies]) + AC_TRY_LINK(,, , [done=yes]) + + if test "x$done" = xyes ; then + AC_MSG_RESULT([no]) + else + AC_MSG_RESULT([yes]) + fi + fi + + if test x"$done" = xno; then + AC_MSG_CHECKING([whether -pthread is sufficient with -shared]) + AC_TRY_LINK([#include <pthread.h>], + [pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], + [done=yes]) + + if test "x$done" = xyes; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + fi + fi + + # + # Linux gcc on some architectures such as mips/mipsel forgets + # about -lpthread + # + if test x"$done" = xno; then + AC_MSG_CHECKING([whether -lpthread fixes that]) + LIBS="-lpthread $PTHREAD_LIBS $save_LIBS" + AC_TRY_LINK([#include <pthread.h>], + [pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], + [done=yes]) + + if test "x$done" = xyes; then + AC_MSG_RESULT([yes]) + PTHREAD_LIBS="-lpthread $PTHREAD_LIBS" + else + AC_MSG_RESULT([no]) + fi + fi + # + # FreeBSD 4.10 gcc forgets to use -lc_r instead of -lc + # + if test x"$done" = xno; then + AC_MSG_CHECKING([whether -lc_r fixes that]) + LIBS="-lc_r $PTHREAD_LIBS $save_LIBS" + AC_TRY_LINK([#include <pthread.h>], + [pthread_t th; pthread_join(th, 0); + pthread_attr_init(0); pthread_cleanup_push(0, 0); + pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], + [done=yes]) + + if test "x$done" = xyes; then + AC_MSG_RESULT([yes]) + PTHREAD_LIBS="-lc_r $PTHREAD_LIBS" + else + AC_MSG_RESULT([no]) + fi + fi + if test x"$done" = xno; then + # OK, we have run out of ideas + AC_MSG_WARN([Impossible to determine how to use pthreads with shared libraries]) + + # so it's not safe to assume that we may use pthreads + acx_pthread_ok=no + fi + + CFLAGS="$save_CFLAGS" + LIBS="$save_LIBS" + CC="$save_CC" +else + PTHREAD_CC="$CC" +fi + +AC_SUBST(PTHREAD_LIBS) +AC_SUBST(PTHREAD_CFLAGS) +AC_SUBST(PTHREAD_CC) + +# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND: +if test x"$acx_pthread_ok" = xyes; then + ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1]) + : +else + acx_pthread_ok=no + $2 +fi +AC_LANG_RESTORE +])dnl ACX_PTHREAD diff --git a/Testing/gtest/m4/gtest.m4 b/Testing/gtest/m4/gtest.m4 new file mode 100644 index 0000000..6598ba7 --- /dev/null +++ b/Testing/gtest/m4/gtest.m4 @@ -0,0 +1,74 @@ +dnl GTEST_LIB_CHECK([minimum version [, +dnl action if found [,action if not found]]]) +dnl +dnl Check for the presence of the Google Test library, optionally at a minimum +dnl version, and indicate a viable version with the HAVE_GTEST flag. It defines +dnl standard variables for substitution including GTEST_CPPFLAGS, +dnl GTEST_CXXFLAGS, GTEST_LDFLAGS, and GTEST_LIBS. It also defines +dnl GTEST_VERSION as the version of Google Test found. Finally, it provides +dnl optional custom action slots in the event GTEST is found or not. +AC_DEFUN([GTEST_LIB_CHECK], +[ +dnl Provide a flag to enable or disable Google Test usage. +AC_ARG_ENABLE([gtest], + [AS_HELP_STRING([--enable-gtest], + [Enable tests using the Google C++ Testing Framework. + (Default is enabled.)])], + [], + [enable_gtest=]) +AC_ARG_VAR([GTEST_CONFIG], + [The exact path of Google Test's 'gtest-config' script.]) +AC_ARG_VAR([GTEST_CPPFLAGS], + [C-like preprocessor flags for Google Test.]) +AC_ARG_VAR([GTEST_CXXFLAGS], + [C++ compile flags for Google Test.]) +AC_ARG_VAR([GTEST_LDFLAGS], + [Linker path and option flags for Google Test.]) +AC_ARG_VAR([GTEST_LIBS], + [Library linking flags for Google Test.]) +AC_ARG_VAR([GTEST_VERSION], + [The version of Google Test available.]) +HAVE_GTEST="no" +AS_IF([test "x${enable_gtest}" != "xno"], + [AC_MSG_CHECKING([for 'gtest-config']) + AS_IF([test "x${enable_gtest}" != "xyes"], + [AS_IF([test -x "${enable_gtest}/scripts/gtest-config"], + [GTEST_CONFIG="${enable_gtest}/scripts/gtest-config"], + [GTEST_CONFIG="${enable_gtest}/bin/gtest-config"]) + AS_IF([test -x "${GTEST_CONFIG}"], [], + [AC_MSG_RESULT([no]) + AC_MSG_ERROR([dnl +Unable to locate either a built or installed Google Test. +The specific location '${enable_gtest}' was provided for a built or installed +Google Test, but no 'gtest-config' script could be found at this location.]) + ])], + [AC_PATH_PROG([GTEST_CONFIG], [gtest-config])]) + AS_IF([test -x "${GTEST_CONFIG}"], + [AC_MSG_RESULT([${GTEST_CONFIG}]) + m4_ifval([$1], + [_gtest_min_version="--min-version=$1" + AC_MSG_CHECKING([for Google Test at least version >= $1])], + [_gtest_min_version="--min-version=0" + AC_MSG_CHECKING([for Google Test])]) + AS_IF([${GTEST_CONFIG} ${_gtest_min_version}], + [AC_MSG_RESULT([yes]) + HAVE_GTEST='yes'], + [AC_MSG_RESULT([no])])], + [AC_MSG_RESULT([no])]) + AS_IF([test "x${HAVE_GTEST}" = "xyes"], + [GTEST_CPPFLAGS=`${GTEST_CONFIG} --cppflags` + GTEST_CXXFLAGS=`${GTEST_CONFIG} --cxxflags` + GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags` + GTEST_LIBS=`${GTEST_CONFIG} --libs` + GTEST_VERSION=`${GTEST_CONFIG} --version` + AC_DEFINE([HAVE_GTEST],[1],[Defined when Google Test is available.])], + [AS_IF([test "x${enable_gtest}" = "xyes"], + [AC_MSG_ERROR([dnl +Google Test was enabled, but no viable version could be found.]) + ])])]) +AC_SUBST([HAVE_GTEST]) +AM_CONDITIONAL([HAVE_GTEST],[test "x$HAVE_GTEST" = "xyes"]) +AS_IF([test "x$HAVE_GTEST" = "xyes"], + [m4_ifval([$2], [$2])], + [m4_ifval([$3], [$3])]) +])
rgee/HFOSS-Dasher
3d4daa76164d8df5204b017edf3d294619305fcb
Continuing work on game mode UI elements - now have a useless, but functioning dialog box and file chooser
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index c7f4e10..484e688 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1116 +1,1112 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); - //if game mode is enabled , initialize the game module - // if(GetBoolParameter(BP_GAME_MODE)) - InitGameModule(); - // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } - if(m_pGameModule) { + if(m_pGameModule && GetBoolParameter(BP_GAME_MODE)) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"), new CFileWordGenerator("test_text.txt"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index def6a38..2922a70 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,140 +1,140 @@ #include "GameModule.h" using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ -const int Dasher::CGameModule::vEvents[2] = {EV_EDIT, EV_GAME_NODE_DRAWN}; +const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_PARAM_NOTIFY}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 4e9afa8..0f7c53d 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,225 +1,220 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; - - if(m_pWordGenerator == NULL) - g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); - if(m_sTargetString == "") - g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ - static const int vEvents[2]; + static const int vEvents[3]; }; } #endif diff --git a/Src/DasherCore/Parameters.h b/Src/DasherCore/Parameters.h index d0d25dd..3de96ba 100644 --- a/Src/DasherCore/Parameters.h +++ b/Src/DasherCore/Parameters.h @@ -1,367 +1,367 @@ // Parameters.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __parameters_h__ #define __parameters_h__ #include <string> #ifdef HAVE_CONFIG_H #include <config.h> #endif // All parameters go into the enums here // They are unique across the different types enum { BP_DRAW_MOUSE_LINE, BP_DRAW_MOUSE, BP_CURVE_MOUSE_LINE, BP_SHOW_SLIDER, BP_START_MOUSE, BP_START_SPACE, BP_STOP_IDLE, BP_CONTROL_MODE, BP_COLOUR_MODE, BP_MOUSEPOS_MODE, BP_OUTLINE_MODE, BP_PALETTE_CHANGE, BP_AUTOCALIBRATE, BP_DASHER_PAUSED, BP_GAME_MODE, BP_TRAINING, BP_REDRAW, BP_LM_DICTIONARY, BP_LM_LETTER_EXCLUSION, BP_AUTO_SPEEDCONTROL, BP_LM_ADAPTIVE, BP_SOCKET_INPUT_ENABLE, BP_SOCKET_DEBUG, BP_CIRCLE_START, BP_GLOBAL_KEYBOARD, BP_NONLINEAR_Y, BP_SMOOTH_OFFSET, BP_CONVERSION_MODE, BP_PAUSE_OUTSIDE, BP_BACKOFF_BUTTON, BP_TWOBUTTON_REVERSE, BP_2B_INVERT_DOUBLE, BP_SLOW_START, #ifdef TARGET_OS_IPHONE BP_CUSTOM_TILT, BP_DOUBLE_X, #endif END_OF_BPS }; enum { LP_ORIENTATION = END_OF_BPS, LP_REAL_ORIENTATION, LP_MAX_BITRATE, LP_FRAMERATE, LP_VIEW_ID, LP_LANGUAGE_MODEL_ID, LP_DASHER_FONTSIZE, LP_UNIFORM, LP_YSCALE, LP_MOUSEPOSDIST, LP_STOP_IDLETIME, LP_LM_MAX_ORDER, LP_LM_EXCLUSION, LP_LM_UPDATE_EXCLUSION, LP_LM_ALPHA, LP_LM_BETA, LP_LM_MIXTURE, LP_MOUSE_POS_BOX, LP_NORMALIZATION, LP_LINE_WIDTH, LP_LM_WORD_ALPHA, LP_USER_LOG_LEVEL_MASK, LP_ZOOMSTEPS, LP_B, LP_S, LP_BUTTON_SCAN_TIME, LP_R, LP_RIGHTZOOM, LP_NODE_BUDGET, LP_NONLINEAR_X, LP_BOOSTFACTOR, LP_AUTOSPEED_SENSITIVITY, LP_SOCKET_PORT, LP_SOCKET_INPUT_X_MIN, LP_SOCKET_INPUT_X_MAX, LP_SOCKET_INPUT_Y_MIN, LP_SOCKET_INPUT_Y_MAX, LP_OX, LP_OY, LP_MAX_Y, LP_INPUT_FILTER, LP_CIRCLE_PERCENT, LP_TWO_BUTTON_OFFSET, LP_HOLD_TIME, LP_MULTIPRESS_TIME, LP_SLOW_START_TIME, LP_CONVERSION_ORDER, LP_CONVERSION_TYPE, LP_TWO_PUSH_OUTER, LP_TWO_PUSH_UP, LP_TWO_PUSH_DOWN, LP_TWO_PUSH_TOLERANCE, LP_DYNAMIC_BUTTON_LAG, LP_STATIC1B_TIME, LP_STATIC1B_ZOOM, LP_DEMO_SPRING, LP_DEMO_NOISE_MEM, LP_DEMO_NOISE_MAG, LP_MAXZOOM, LP_DYNAMIC_SPEED_INC, LP_DYNAMIC_SPEED_FREQ, LP_DYNAMIC_SPEED_DEC, LP_TAP_TIME, LP_MARGIN_WIDTH, END_OF_LPS }; enum { SP_ALPHABET_ID = END_OF_LPS, SP_ALPHABET_1, SP_ALPHABET_2, SP_ALPHABET_3, SP_ALPHABET_4, SP_COLOUR_ID, SP_DEFAULT_COLOUR_ID, SP_DASHER_FONT, SP_SYSTEM_LOC, SP_USER_LOC, SP_GAME_TEXT_FILE, SP_TRAIN_FILE, SP_SOCKET_INPUT_X_LABEL, SP_SOCKET_INPUT_Y_LABEL, SP_INPUT_FILTER, SP_INPUT_DEVICE, SP_BUTTON_0, SP_BUTTON_1, SP_BUTTON_2, SP_BUTTON_3, SP_BUTTON_4, SP_BUTTON_10, SP_JOYSTICK_DEVICE, #ifdef TARGET_OS_IPHONE SP_CUSTOM_TILT, SP_VERTICAL_TILT, #endif END_OF_SPS }; // Define first int value of the first element of each type. // Useful for offsetting into specific arrays, // since each setting is a unique int, but all 3 arrays start at 0 #define FIRST_BP 0 #define FIRST_LP END_OF_BPS #define FIRST_SP END_OF_LPS // Define the number of each type of setting #define NUM_OF_BPS END_OF_BPS #define NUM_OF_LPS (END_OF_LPS - END_OF_BPS) #define NUM_OF_SPS (END_OF_SPS - END_OF_LPS) #define PERS true // First level structures with only basic data types because you // cannot initialize struct tables with objects // These will be turned into std::strings in the ParamTables() object struct bp_table { int key; const char *regName; bool persistent; bool defaultValue; const char *humanReadable; }; struct lp_table { int key; const char *regName; bool persistent; long defaultValue; const char *humanReadable; }; struct sp_table { int key; const char *regName; bool persistent; const char *defaultValue; const char *humanReadable; }; // The only important thing here is that these are in the same order // as the enum declarations (could add check in class that enforces this instead) static bp_table boolparamtable[] = { {BP_DRAW_MOUSE_LINE, "DrawMouseLine", PERS, true, "Draw Mouse Line"}, {BP_DRAW_MOUSE, "DrawMouse", PERS, false, "Draw Mouse Position"}, {BP_CURVE_MOUSE_LINE, "CurveMouseLine", PERS, false, "Curve mouse line according to screen nonlinearity"}, #ifdef WITH_MAEMO {BP_SHOW_SLIDER, "ShowSpeedSlider", PERS, false, "ShowSpeedSlider"}, #else {BP_SHOW_SLIDER, "ShowSpeedSlider", PERS, true, "ShowSpeedSlider"}, #endif {BP_START_MOUSE, "StartOnLeft", PERS, true, "StartOnLeft"}, {BP_START_SPACE, "StartOnSpace", PERS, false, "StartOnSpace"}, {BP_STOP_IDLE, "StopOnIdle", PERS, false, "StopOnIdle"}, {BP_CONTROL_MODE, "ControlMode", PERS, false, "ControlMode"}, {BP_COLOUR_MODE, "ColourMode", PERS, true, "ColourMode"}, {BP_MOUSEPOS_MODE, "StartOnMousePosition", PERS, false, "StartOnMousePosition"}, {BP_OUTLINE_MODE, "OutlineBoxes", PERS, true, "OutlineBoxes"}, {BP_PALETTE_CHANGE, "PaletteChange", PERS, true, "PaletteChange"}, {BP_AUTOCALIBRATE, "Autocalibrate", PERS, true, "Autocalibrate"}, {BP_DASHER_PAUSED, "DasherPaused", !PERS, true, "Dasher Paused"}, - {BP_GAME_MODE, "GameMode", PERS, false, "Dasher Game Mode"}, + {BP_GAME_MODE, "GameMode", !PERS, false, "Dasher Game Mode"}, {BP_TRAINING, "Training", !PERS, false, "Provides locking during training"}, {BP_REDRAW, "Redraw", !PERS, false, "Force a full redraw at the next timer event"}, {BP_LM_DICTIONARY, "Dictionary", PERS, true, "Whether the word-based language model uses a dictionary"}, {BP_LM_LETTER_EXCLUSION, "LetterExclusion", PERS, true, "Whether to do letter exclusion in the word-based model"}, {BP_AUTO_SPEEDCONTROL, "AutoSpeedControl", PERS, true, "AutoSpeedControl"}, {BP_LM_ADAPTIVE, "LMAdaptive", PERS, true, "Whether language model should learn as you enter text"}, {BP_SOCKET_INPUT_ENABLE, "SocketInputEnable", PERS, false, "Read pointer coordinates from network socket instead of mouse"}, {BP_SOCKET_DEBUG, "SocketInputDebug", PERS, false, "Print information about socket input processing to console"}, {BP_CIRCLE_START, "CircleStart", PERS, false, "Start on circle mode"}, {BP_GLOBAL_KEYBOARD, "GlobalKeyboard", PERS, false, "Whether to assume global control of the keyboard"}, #ifdef WITH_MAEMO {BP_NONLINEAR_Y, "NonlinearY", PERS, false, "Apply nonlinearities to Y axis (i.e. compress top &amp; bottom)"}, #else {BP_NONLINEAR_Y, "NonlinearY", PERS, true, "Apply nonlinearities to Y axis (i.e. compress top &amp; bottom)"}, #endif {BP_SMOOTH_OFFSET, "DelayView", !PERS, false, "Smooth dynamic-button-mode jumps over several frames"}, {BP_CONVERSION_MODE, "ConversionMode", !PERS, false, "Whether Dasher is operating in conversion (eg Japanese) mode"}, {BP_PAUSE_OUTSIDE, "PauseOutside", PERS, false, "Whether to pause when pointer leaves canvas area"}, #ifdef TARGET_OS_IPHONE {BP_BACKOFF_BUTTON, "BackoffButton", PERS, false, "Whether to enable the extra backoff button in dynamic mode"}, #else {BP_BACKOFF_BUTTON, "BackoffButton", PERS, true, "Whether to enable the extra backoff button in dynamic mode"}, #endif {BP_TWOBUTTON_REVERSE, "TwoButtonReverse", PERS, false, "Reverse the up/down buttons in two button mode"}, {BP_2B_INVERT_DOUBLE, "TwoButtonInvertDouble", PERS, false, "Double-press acts as opposite button in two-button mode"}, {BP_SLOW_START, "SlowStart", PERS, false, "Start at low speed and increase"}, #ifdef TARGET_OS_IPHONE {BP_CUSTOM_TILT, "CustomTilt", PERS, false, "Use custom tilt axes"}, {BP_DOUBLE_X, "DoubleXCoords", PERS, false, "Double X-coordinate of touch"}, #endif }; static lp_table longparamtable[] = { {LP_ORIENTATION, "ScreenOrientation", PERS, -2, "Screen Orientation"}, {LP_REAL_ORIENTATION, "RealOrientation", !PERS, 0, "Actual screen orientation (allowing for alphabet default)"}, {LP_MAX_BITRATE, "MaxBitRateTimes100", PERS, 80, "Max Bit Rate Times 100"}, {LP_FRAMERATE, "FrameRate", PERS, 3200, "Last known frame rate, times 100"}, {LP_VIEW_ID, "ViewID", PERS, 1, "ViewID"}, {LP_LANGUAGE_MODEL_ID, "LanguageModelID", PERS, 0, "LanguageModelID"}, {LP_DASHER_FONTSIZE, "DasherFontSize", PERS, 2, "DasherFontSize"}, {LP_UNIFORM, "UniformTimes1000", PERS, 50, "UniformTimes1000"}, {LP_YSCALE, "YScaling", PERS, 0, "YScaling"}, {LP_MOUSEPOSDIST, "MousePositionBoxDistance", PERS, 50, "MousePositionBoxDistance"}, {LP_STOP_IDLETIME, "StopIdleTime", PERS, 1000, "StopIdleTime" }, {LP_LM_MAX_ORDER, "LMMaxOrder", PERS, 5, "LMMaxOrder"}, {LP_LM_EXCLUSION, "LMExclusion", PERS, 0, "LMExclusion"}, {LP_LM_UPDATE_EXCLUSION, "LMUpdateExclusion", PERS, 1, "LMUpdateExclusion"}, {LP_LM_ALPHA, "LMAlpha", PERS, 49, "LMAlpha"}, {LP_LM_BETA, "LMBeta", PERS, 77, "LMBeta"}, {LP_LM_MIXTURE, "LMMixture", PERS, 50, "LMMixture"}, {LP_MOUSE_POS_BOX, "MousePosBox", !PERS, -1, "Mouse Position Box Indicator"}, {LP_NORMALIZATION, "Normalization", !PERS, 1 << 16, "Interval for child nodes"}, {LP_LINE_WIDTH, "LineWidth", PERS, 1, "Width to draw crosshair and mouse line"}, {LP_LM_WORD_ALPHA, "WordAlpha", PERS, 50, "Alpha value for word-based model"}, {LP_USER_LOG_LEVEL_MASK, "UserLogLevelMask", PERS, 0, "Controls level of user logging, 0 = none, 1 = short, 2 = detailed, 3 = both"}, {LP_ZOOMSTEPS, "Zoomsteps", PERS, 32, "Integerised ratio of zoom size for click/button mode, denom 64."}, {LP_B, "ButtonMenuBoxes", PERS, 4, "Number of boxes for button menu mode"}, {LP_S, "ButtonMenuSafety", PERS, 25, "Safety parameter for button mode, in percent."}, #ifdef TARGET_OS_IPHONE {LP_BUTTON_SCAN_TIME, "ButtonMenuScanTime", PERS, 600, "Scanning time in menu mode (0 = don't scan), in ms"}, #else {LP_BUTTON_SCAN_TIME, "ButtonMenuScanTime", PERS, 0, "Scanning time in menu mode (0 = don't scan), in ms"}, #endif {LP_R, "ButtonModeNonuniformity", PERS, 0, "Button mode box non-uniformity"}, {LP_RIGHTZOOM, "ButtonCompassModeRightZoom", PERS, 5120, "Zoomfactor (*1024) for compass mode"}, #if defined(WITH_MAEMO) || defined (TARGET_OS_IPHONE) {LP_NODE_BUDGET, "NodeBudget", PERS, 1000, "Target (min) number of node objects to maintain"}, #else {LP_NODE_BUDGET, "NodeBudget", PERS, 3000, "Target (min) number of node objects to maintain"}, #endif #ifdef WITH_MAEMO {LP_NONLINEAR_X, "NonLinearX", PERS, 0, "Nonlinear compression of X-axis (0 = none, higher = more extreme)"}, #else {LP_NONLINEAR_X, "NonLinearX", PERS, 5, "Nonlinear compression of X-axis (0 = none, higher = more extreme)"}, #endif {LP_BOOSTFACTOR, "BoostFactor", !PERS, 100, "Boost/brake factor (multiplied by 100)"}, {LP_AUTOSPEED_SENSITIVITY, "AutospeedSensitivity", PERS, 100, "Sensitivity of automatic speed control (percent)"}, {LP_SOCKET_PORT, "SocketPort", PERS, 20320, "UDP/TCP socket to use for network socket input"}, {LP_SOCKET_INPUT_X_MIN, "SocketInputXMinTimes1000", PERS, 0, "Bottom of range of X values expected from network input"}, {LP_SOCKET_INPUT_X_MAX, "SocketInputXMaxTimes1000", PERS, 1000, "Top of range of X values expected from network input"}, {LP_SOCKET_INPUT_Y_MIN, "SocketInputYMinTimes1000", PERS, 0, "Bottom of range of Y values expected from network input"}, {LP_SOCKET_INPUT_Y_MAX, "SocketInputYMaxTimes1000", PERS, 1000, "Top of range of Y values expected from network input"}, {LP_OX, "OX", PERS, 2048, "X coordinate of crosshair"}, {LP_OY, "OY", PERS, 2048, "Y coordinate of crosshair"}, {LP_MAX_Y, "MaxY", PERS, 4096, "Maximum Y coordinate"}, {LP_INPUT_FILTER, "InputFilterID", PERS, 3, "Module ID of input filter"}, {LP_CIRCLE_PERCENT, "CirclePercent", PERS, 10, "Percentage of nominal vertical range to use for radius of start circle"}, {LP_TWO_BUTTON_OFFSET, "TwoButtonOffset", PERS, 1638, "Offset for two button dynamic mode"}, {LP_HOLD_TIME, "HoldTime", PERS, 1000, "Time for which buttons must be held to count as long presses, in ms"}, {LP_MULTIPRESS_TIME, "MultipressTime", PERS, 1000, "Time in which multiple presses must occur, in ms"}, {LP_SLOW_START_TIME, "SlowStartTime", PERS, 1000, "Time over which slow start occurs"}, {LP_CONVERSION_ORDER, "ConversionOrder", PERS, 0, "Conversion ordering"}, {LP_CONVERSION_TYPE, "ConversionType", PERS, 0, "Conversion type"}, {LP_TWO_PUSH_OUTER, "TwoPushOuter", PERS, 1792, "Offset for one button dynamic mode outer marker"}, {LP_TWO_PUSH_UP, "TwoPushUp", PERS, 1536, "Offset to up marker in one button dynamic"}, {LP_TWO_PUSH_DOWN, "TwoPushDown", PERS, 1280, "Offset to down marker in one button dynamic"}, {LP_TWO_PUSH_TOLERANCE, "TwoPushTolerance", PERS, 100, "Tolerance of two-push-mode pushes, in ms"}, {LP_DYNAMIC_BUTTON_LAG, "DynamicButtonLag", PERS, 50, "Lag of pushes in dynamic button mode (ms)"}, {LP_STATIC1B_TIME, "Static1BTime", PERS, 2000, "Time for static-1B mode to scan from top to bottom (ms)"}, {LP_STATIC1B_ZOOM, "Static1BZoom", PERS, 8, "Zoom factor for static-1B mode"}, {LP_DEMO_SPRING, "DemoSpring", PERS, 100, "Springyness in Demo-mode"}, {LP_DEMO_NOISE_MEM, "DemoNoiseMem", PERS, 100, "Memory parameter for noise in Demo-mode"}, {LP_DEMO_NOISE_MAG, "DemoNoiseMag", PERS, 325, "Magnitude of noise in Demo-mode"}, {LP_MAXZOOM, "ClickMaxZoom", PERS, 200, "Maximum zoom possible in click mode (times 10)"}, {LP_DYNAMIC_SPEED_INC, "DynamicSpeedInc", PERS, 3, "%age by which dynamic mode auto speed control increases speed"}, {LP_DYNAMIC_SPEED_FREQ, "DynamicSpeedFreq", PERS, 10, "Seconds after which dynamic mode auto speed control increases speed"}, {LP_DYNAMIC_SPEED_DEC, "DynamicSpeedDec", PERS, 8, "%age by which dynamic mode auto speed control decreases speed on reverse"}, {LP_TAP_TIME, "TapTime", PERS, 200, "Max length of a stylus 'tap' rather than hold (ms)"}, #ifdef TARGET_OS_IPHONE {LP_MARGIN_WIDTH, "MarginWidth", PERS, 500, "Width of RHS margin (in Dasher co-ords)"}, #else {LP_MARGIN_WIDTH, "MarginWidth", PERS, 300, "Width of RHS margin (in Dasher co-ords)"}, #endif }; static sp_table stringparamtable[] = { {SP_ALPHABET_ID, "AlphabetID", PERS, "", "AlphabetID"}, {SP_ALPHABET_1, "Alphabet1", PERS, "", "Alphabet History 1"}, {SP_ALPHABET_2, "Alphabet2", PERS, "", "Alphabet History 2"}, {SP_ALPHABET_3, "Alphabet3", PERS, "", "Alphabet History 3"}, {SP_ALPHABET_4, "Alphabet4", PERS, "", "Alphabet History 4"}, {SP_COLOUR_ID, "ColourID", PERS, "", "ColourID"}, {SP_DEFAULT_COLOUR_ID, "DefaultColourID", !PERS, "", "Default Colour ID (Used for auto-colour mode)"}, {SP_DASHER_FONT, "DasherFont", PERS, "", "DasherFont"}, {SP_SYSTEM_LOC, "SystemLocation", !PERS, "sys_", "System Directory"}, {SP_USER_LOC, "UserLocation", !PERS, "usr_", "User Directory"}, {SP_GAME_TEXT_FILE, "GameTextFile", !PERS, "", "File with strings to practice writing"}, {SP_TRAIN_FILE, "TrainingFile", !PERS, "", "Training text for alphabet"}, {SP_SOCKET_INPUT_X_LABEL, "SocketInputXLabel", PERS, "x", "Label preceding X values for network input"}, {SP_SOCKET_INPUT_Y_LABEL, "SocketInputYLabel", PERS, "y", "Label preceding Y values for network input"}, #if defined(WITH_MAEMO) || defined(TARGET_OS_IPHONE) {SP_INPUT_FILTER, "InputFilter", PERS, "Stylus Control", "Input filter used to provide the current control mode"}, #else {SP_INPUT_FILTER, "InputFilter", PERS, "Normal Control", "Input filter used to provide the current control mode"}, #endif {SP_INPUT_DEVICE, "InputDevice", PERS, "Mouse Input", "Driver for the input device"}, {SP_BUTTON_0, "Button0", PERS, "", "Assignment to button 0"}, {SP_BUTTON_1, "Button1", PERS, "", "Assignment to button 1"}, {SP_BUTTON_2, "Button2", PERS, "", "Assignment to button 2"}, {SP_BUTTON_3, "Button3", PERS, "", "Assignment to button 3"}, {SP_BUTTON_4, "Button4", PERS, "", "Assignment to button 4"}, {SP_BUTTON_10, "Button10", PERS, "", "Assignment to button 10"}, {SP_JOYSTICK_DEVICE, "JoystickDevice", PERS, "/dev/input/js0", "Joystick device"}, #ifdef TARGET_OS_IPHONE {SP_CUSTOM_TILT, "CustomTiltParams", PERS, "(0.0,0.0,0.0) - (0.0,-1.0,0.0) / (-1.0,0.0,0.0)", "Custom tilt axes"}, {SP_VERTICAL_TILT, "VerticalTiltParams", PERS, "-0.1 - -0.9 / -0.4 - 0.4", "Limits of vertical tilting"}, #endif }; // This is the structure of each table that the settings will access // Everything is const except the current value of the setting struct bp_info { int key; std::string regName; bool persistent; bool value; bool defaultVal; std::string humanReadable; }; struct lp_info { int key; std::string regName; bool persistent; long value; long defaultVal; std::string humanReadable; }; struct sp_info { int key; std::string regName; bool persistent; std::string value; std::string defaultVal; std::string humanReadable; }; namespace Dasher { class CParamTables; } /// \ingroup Core /// \{ class Dasher::CParamTables { // These are the parameter tables that store everything public: bp_info BoolParamTable[NUM_OF_BPS]; lp_info LongParamTable[NUM_OF_LPS]; sp_info StringParamTable[NUM_OF_SPS]; public: CParamTables() { // Initialize all the tables with default values // and convert the char* to std::string in the object for(int ii = 0; ii < NUM_OF_BPS; ii++) { BoolParamTable[ii].key = boolparamtable[ii].key; BoolParamTable[ii].value = boolparamtable[ii].defaultValue; BoolParamTable[ii].defaultVal = boolparamtable[ii].defaultValue; BoolParamTable[ii].humanReadable = boolparamtable[ii].humanReadable; BoolParamTable[ii].persistent = boolparamtable[ii].persistent; BoolParamTable[ii].regName = boolparamtable[ii].regName; } for(int ij = 0; ij < NUM_OF_LPS; ij++) { LongParamTable[ij].key = longparamtable[ij].key; LongParamTable[ij].value = longparamtable[ij].defaultValue; LongParamTable[ij].defaultVal = longparamtable[ij].defaultValue; LongParamTable[ij].humanReadable = longparamtable[ij].humanReadable; LongParamTable[ij].persistent = longparamtable[ij].persistent; LongParamTable[ij].regName = longparamtable[ij].regName; } for(int ik = 0; ik < NUM_OF_SPS; ik++) { StringParamTable[ik].key = stringparamtable[ik].key; StringParamTable[ik].value = stringparamtable[ik].defaultValue; StringParamTable[ik].defaultVal = stringparamtable[ik].defaultValue; StringParamTable[ik].humanReadable = stringparamtable[ik].humanReadable; StringParamTable[ik].persistent = stringparamtable[ik].persistent; StringParamTable[ik].regName = stringparamtable[ik].regName; } }; /// \} }; #endif diff --git a/Src/Gtk2/dasher_editor_internal.cpp b/Src/Gtk2/dasher_editor_internal.cpp index 306dd2b..3dc49b0 100644 --- a/Src/Gtk2/dasher_editor_internal.cpp +++ b/Src/Gtk2/dasher_editor_internal.cpp @@ -412,1025 +412,1025 @@ dasher_editor_internal_handle_start(DasherEditor *pSelf) { // The edit box keeps track of where we started // TODO: This should be filtered through the buffer, rather than directly to the edit box // set_mark(); } /* TODO: This is obsolete - sort this out when commands are reconsidered */ void dasher_editor_internal_handle_control(DasherEditor *pSelf, int iNodeID) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(iNodeID == Dasher::CControlManager::CTL_USER + 1) dasher_editor_internal_clear(pSelf, false); // Clear node is a special case (it shouldn't be) else { EditorAction *pCurrentAction = pPrivate->pActionRing; bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; if((iNodeID >= pCurrentAction->iControlID) && (iNodeID <= pCurrentAction->iControlID + pCurrentAction->iNSub)) { dasher_action_execute(pCurrentAction->pAction, DASHER_EDITOR(pSelf), iNodeID - pCurrentAction->iControlID - 1); // dasher_editor_internal_clear(pSelf, true); } pCurrentAction = pCurrentAction->pNext; } } // TODO: Think about changing signals so we don't need to do this translation struct SControlMap { int iEvent; int iDir; int iDist; bool bDelete; }; static struct SControlMap sMap[] = { {Dasher::CControlManager::CTL_MOVE_FORWARD_CHAR, EDIT_FORWARDS, EDIT_CHAR, false}, {Dasher::CControlManager::CTL_MOVE_FORWARD_WORD, EDIT_FORWARDS, EDIT_WORD, false}, {Dasher::CControlManager::CTL_MOVE_FORWARD_LINE, EDIT_FORWARDS, EDIT_LINE, false}, {Dasher::CControlManager::CTL_MOVE_FORWARD_FILE, EDIT_FORWARDS, EDIT_FILE, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_CHAR, EDIT_BACKWARDS, EDIT_CHAR, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_WORD, EDIT_BACKWARDS, EDIT_WORD, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_LINE, EDIT_BACKWARDS, EDIT_LINE, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_FILE, EDIT_BACKWARDS, EDIT_FILE, false}, {Dasher::CControlManager::CTL_DELETE_FORWARD_CHAR, EDIT_FORWARDS, EDIT_CHAR, true}, {Dasher::CControlManager::CTL_DELETE_FORWARD_WORD, EDIT_FORWARDS, EDIT_WORD, true}, {Dasher::CControlManager::CTL_DELETE_FORWARD_LINE, EDIT_FORWARDS, EDIT_LINE, true}, {Dasher::CControlManager::CTL_DELETE_FORWARD_FILE, EDIT_FORWARDS, EDIT_FILE, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_CHAR, EDIT_BACKWARDS, EDIT_CHAR, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_WORD, EDIT_BACKWARDS, EDIT_WORD, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_LINE, EDIT_BACKWARDS, EDIT_LINE, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_FILE, EDIT_BACKWARDS, EDIT_FILE, true} }; if(pPrivate->pBufferSet) { for(unsigned int i(0); i < sizeof(sMap)/sizeof(struct SControlMap); ++i) { if(sMap[i].iEvent == iNodeID) { if(sMap[i].bDelete) idasher_buffer_set_edit_delete(pPrivate->pBufferSet, sMap[i].iDir, sMap[i].iDist); else idasher_buffer_set_edit_move(pPrivate->pBufferSet, sMap[i].iDir, sMap[i].iDist); } } } } void dasher_editor_internal_action_button(DasherEditor *pSelf, DasherAction *pAction) { if(pAction) { dasher_action_execute(pAction, DASHER_EDITOR(pSelf), -1); dasher_editor_internal_clear(pSelf, true); } else { // Clear button dasher_editor_internal_clear(pSelf, false); } } static void dasher_editor_internal_clear(DasherEditor *pSelf, gboolean bStore) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(IS_DASHER_INTERNAL_BUFFER(pPrivate->pBufferSet)) dasher_internal_buffer_clear(DASHER_INTERNAL_BUFFER(pPrivate->pBufferSet)); } void dasher_editor_internal_actions_start(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); pPrivate->bActionIterStarted = false; pPrivate->pActionIter = pPrivate->pActionRing; } bool dasher_editor_internal_actions_more(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return(!pPrivate->bActionIterStarted || (pPrivate->pActionIter != pPrivate->pActionRing)); } void dasher_editor_internal_actions_get_next(DasherEditor *pSelf, const gchar **szName, gint *iID, gboolean *bShow, gboolean *bControl, gboolean *bAuto) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); *szName = dasher_action_get_name(pPrivate->pActionIter->pAction); *iID = pPrivate->pActionIter->iID; *bShow = pPrivate->pActionIter->bShow; *bControl = pPrivate->pActionIter->bControl; *bAuto = pPrivate->pActionIter->bAuto; pPrivate->pActionIter = pPrivate->pActionIter->pNext; pPrivate->bActionIterStarted = true; } void dasher_editor_internal_action_set_show(DasherEditor *pSelf, int iActionID, bool bValue) { EditorAction *pAction; pAction = dasher_editor_internal_get_action_by_id(pSelf, iActionID); if(pAction) { pAction->bShow = bValue; dasher_editor_internal_check_activity(pSelf, pAction); dasher_editor_internal_rebuild_action_pane(pSelf); dasher_editor_internal_action_save_state(pSelf, pAction); } } void dasher_editor_internal_action_set_control(DasherEditor *pSelf, int iActionID, bool bValue) { // TODO: Need to actually change behaviour in resonse to these calls // TODO: Reimplement // EditorAction *pAction; // pAction = dasher_editor_internal_get_action_by_id(pSelf, iActionID); // if(pAction) { // pAction->bControl = bValue; // dasher_editor_internal_check_activity(pSelf, pAction); // if(bValue) // gtk_dasher_control_connect_node(GTK_DASHER_CONTROL(pDasherWidget), pAction->iControlID, Dasher::CControlManager::CTL_USER, -2); // else // gtk_dasher_control_disconnect_node(GTK_DASHER_CONTROL(pDasherWidget), pAction->iControlID, Dasher::CControlManager::CTL_USER); // dasher_editor_internal_action_save_state(pSelf, pAction); // } } void dasher_editor_internal_action_set_auto(DasherEditor *pSelf, int iActionID, bool bValue) { EditorAction *pAction; pAction = dasher_editor_internal_get_action_by_id(pSelf, iActionID); if(pAction) { pAction->bAuto = bValue; dasher_editor_internal_check_activity(pSelf, pAction); dasher_editor_internal_action_save_state(pSelf, pAction); } } void dasher_editor_internal_grab_focus(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(pPrivate->pTextView) gtk_widget_grab_focus(GTK_WIDGET(pPrivate->pTextView)); } static void dasher_editor_internal_create_buffer(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); /* Make an external buffer anyway, for keyboard command */ /* TODO: Review this */ if(!(pPrivate->pExternalBuffer)) pPrivate->pExternalBuffer = IDASHER_BUFFER_SET(dasher_external_buffer_new()); if(!(pPrivate->pBufferSet)) pPrivate->pBufferSet = IDASHER_BUFFER_SET(dasher_internal_buffer_new(pPrivate->pTextView)); // TODO: Fix this g_signal_connect(G_OBJECT(pPrivate->pBufferSet), "offset_changed", G_CALLBACK(context_changed_handler), pSelf); g_signal_connect(G_OBJECT(pPrivate->pBufferSet), "buffer_changed", G_CALLBACK(buffer_changed_handler), pSelf); } void dasher_editor_internal_output(DasherEditor *pSelf, const gchar *szText, int iOffset) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); // TODO: tidy this up, actionlookup by name, more flexible // definition of space // Python scripting? if(!strcmp(szText, " ")) { gboolean bActionIterStarted = false; EditorAction *pActionIter = pPrivate->pActionRing; while((pActionIter != pPrivate->pActionRing) || !bActionIterStarted) { bActionIterStarted = true; if(!strcmp(dasher_action_get_name(pActionIter->pAction), "Speak")) { dasher_action_preview(pActionIter->pAction, DASHER_EDITOR(pSelf)); } pActionIter = pActionIter->pNext; } } if(pPrivate->pBufferSet) idasher_buffer_set_insert(pPrivate->pBufferSet, szText, iOffset); // if(pPrivate->pGameModeHelper) // game_mode_helper_output(pPrivate->pGameModeHelper, szText); pPrivate->bFileModified = TRUE; } void dasher_editor_internal_delete(DasherEditor *pSelf, int iLength, int iOffset) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(pPrivate->pBufferSet) idasher_buffer_set_delete(pPrivate->pBufferSet, iLength, iOffset); // if(pPrivate->pGameModeHelper) // game_mode_helper_delete(pPrivate->pGameModeHelper, iLength); pPrivate->bFileModified = TRUE; } const gchar * dasher_editor_internal_get_context(DasherEditor *pSelf, int iOffset, int iLength) { // TODO: Check where this function is used DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); const gchar *szContext; if(pPrivate->pBufferSet) szContext = idasher_buffer_set_get_context(pPrivate->pBufferSet, iOffset, iLength); else szContext = ""; // TODO: reimplement // if(szContext && (strlen(szContext) > 0)) // gtk_dasher_control_set_context( GTK_DASHER_CONTROL(pDasherWidget), szContext ); return szContext; } gint dasher_editor_internal_get_offset(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return idasher_buffer_set_get_offset(pPrivate->pBufferSet); } static void dasher_editor_internal_generate_filename(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); gchar *szNewFilename = NULL; if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_TIME_STAMP )) { // Build a filename based on the current time and date tm *t_struct; time_t ctime; char cwd[1000]; char tbuffer[200]; ctime = time(NULL); t_struct = localtime(&ctime); getcwd(cwd, 1000); snprintf(tbuffer, 200, "dasher-%04d%02d%02d-%02d%02d.txt", (t_struct->tm_year + 1900), (t_struct->tm_mon + 1), t_struct->tm_mday, t_struct->tm_hour, t_struct->tm_min); szNewFilename = g_build_path("/", cwd, tbuffer, NULL); } dasher_editor_internal_set_filename(pSelf, szNewFilename); g_free(szNewFilename); } static void dasher_editor_internal_open(DasherEditor *pSelf, const gchar *szFilename) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); gsize size; gchar *buffer; #ifdef HAVE_GIO if(!dasher_editor_internal_gvfs_open_file(pSelf, szFilename, &buffer, &size)) { return; } #else if(!dasher_editor_internal_unix_vfs_open_file(pSelf, szFilename, &buffer, &size)) { return; } #endif // FIXME - REIMPLEMENT (shouldn't happen through core) // dasher_clear(); if(size != 0) { // Don't attempt to insert new text if the file is empty as it makes // GTK cry if(!g_utf8_validate(buffer, size, NULL)) { // PRLW: size as gssize = signed int // It's not UTF8, so we do the best we can... // If there are zero bytes in the file then we have a problem - // for now, just assert that we can't load these files. for(gsize i = 0; i < size; ++i) if(buffer[i] == 0) { // GtkWidget *pErrorBox = gtk_message_dialog_new(GTK_WINDOW(window), // GTK_DIALOG_MODAL, // GTK_MESSAGE_ERROR, // GTK_BUTTONS_OK, // "Could not open the file \"%s\". Please note that Dasher cannot load files containing binary data, which may be the cause of this error.\n", // myfilename); GtkWidget *pErrorBox = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open the file \"%s\". Please note that Dasher cannot load files containing binary data, which may be the cause of this error.\n", szFilename); gtk_dialog_run(GTK_DIALOG(pErrorBox)); gtk_widget_destroy(pErrorBox); return; } pPrivate->bFileModified = TRUE; gsize iNewSize; gchar *buffer2 = g_strdup(g_locale_to_utf8(buffer, size, NULL, &iNewSize, NULL)); // TODO: This function probably needs more thought // const gchar *pEnd; //gboolean bValid = g_utf8_validate(buffer2, -1, &pEnd); g_free(buffer); buffer = buffer2; size = iNewSize; } gtk_text_buffer_insert_at_cursor(GTK_TEXT_BUFFER(pPrivate->pBuffer), buffer, size); gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(pPrivate->pTextView), gtk_text_buffer_get_insert(GTK_TEXT_BUFFER(pPrivate->pBuffer))); } dasher_editor_internal_set_filename(pSelf, szFilename); } static bool dasher_editor_internal_save_as(DasherEditor *pSelf, const gchar *szFilename, bool bAppend) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); unsigned long long length; gchar *inbuffer, *outbuffer = NULL; // gsize bytes_read, bytes_written; gsize bytes_written; // GError *error = NULL; GtkTextIter *start, *end; // GIConv cd; start = new GtkTextIter; end = new GtkTextIter; gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), start, 0); gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), end, -1); inbuffer = gtk_text_iter_get_slice(start, end); // g_message("String %s", inbuffer); //length = gtk_text_iter_get_offset(end) - gtk_text_iter_get_offset(start); //length = gtk_text_buffer_get_byte_count(GTK_TEXT_BUFFER(the_text_buffer)); // I'm pretty certain that this is null terminated, but not 100% length = strlen(inbuffer); // g_message("Length is %d", length); outbuffer = (char *)malloc((length + 1) * sizeof(gchar)); memcpy((void *)outbuffer, (void *)inbuffer, length * sizeof(gchar)); outbuffer[length] = 0; g_free(inbuffer); inbuffer = outbuffer; outbuffer = NULL; // switch (fileencoding) { // case Dasher::Opts::UserDefault: // case Dasher::Opts::AlphabetDefault: // //FIXME - need to call GetAlphabetType and do appropriate stuff regarding // //the character set. Arguably we should always be saving in either UTF-8 or // //the user's locale (which may, of course, be UTF-8) because otherwise // //we're going to read in rubbish, and we shouldn't be encouraging weird // //codepage madness any further // //FIXME - error handling // outbuffer = g_locale_from_utf8(inbuffer, -1, &bytes_read, &bytes_written, &error); // if(outbuffer == NULL) { // // We can't represent the text in the current locale, so fall back to // // UTF-8 // outbuffer = inbuffer; // bytes_written = length; // } // case Dasher::Opts::UTF8: // outbuffer = inbuffer; // bytes_written = length; // break; // // Does /anyone/ want to save text files in UTF16? // // (in any case, my opinions regarding encouragement of data formats with // // endianness damage are almost certainly unprintable) // case Dasher::Opts::UTF16LE: // cd = g_iconv_open("UTF16LE", "UTF8"); // outbuffer = g_convert_with_iconv(inbuffer, -1, cd, &bytes_read, &bytes_written, &error); // break; // case Dasher::Opts::UTF16BE: // cd = g_iconv_open("UTF16BE", "UTF8"); // outbuffer = g_convert_with_iconv(inbuffer, -1, cd, &bytes_read, &bytes_written, &error); // break; // default: outbuffer = inbuffer; bytes_written = length; // } #ifdef HAVE_GIO if(!dasher_editor_internal_gvfs_save_file(pSelf, szFilename, outbuffer, bytes_written, bAppend)) { return false; } #else if(!dasher_editor_internal_unix_vfs_save_file(pSelf, szFilename, outbuffer, bytes_written, bAppend)) { return false; } #endif pPrivate->bFileModified = FALSE; dasher_editor_internal_set_filename(pSelf, szFilename); return true; } // void // dasher_editor_internal_start_tutorial(DasherEditor *pSelf) { // DasherEditorInternalPrivate *pPrivate = (DasherEditorInternalPrivate *)(pSelf->private_data); // // TODO: reimplement // // pPrivate->pGameModeHelper = GAME_MODE_HELPER(game_mode_helper_new(GTK_DASHER_CONTROL(pDasherWidget))); // } gboolean dasher_editor_internal_command(DasherEditor *pSelf, const gchar *szCommand) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "action_new")) { //select_new_file dasher_editor_internal_command_new(pSelf); return TRUE; } if(!strcmp(szCommand, "action_open")) { //select open file dasher_editor_internal_command_open(pSelf); return TRUE; } if(!strcmp(szCommand, "action_save")) { //save_file dasher_editor_internal_command_save(pSelf, FALSE, FALSE); return TRUE; } if(!strcmp(szCommand, "action_saveas")) { // select_save_file_as dasher_editor_internal_command_save(pSelf, TRUE, FALSE); return TRUE; } if(!strcmp(szCommand, "action_append")) { // select_append_file dasher_editor_internal_command_save(pSelf, TRUE, TRUE); return TRUE; } if(!strcmp(szCommand, "action_cut")) { // clipboard_cut dasher_editor_internal_clipboard(pSelf, CLIPBOARD_CUT); return TRUE; } if(!strcmp(szCommand, "action_copy")) { // clipboard_copy dasher_editor_internal_clipboard(pSelf, CLIPBOARD_COPY); return TRUE; } if(!strcmp(szCommand, "action_copyall")) { // clipboard_copyall dasher_editor_internal_clipboard(pSelf, CLIPBOARD_COPYALL); return TRUE; } if(!strcmp(szCommand, "action_paste")) { // clipboard_paste dasher_editor_internal_clipboard(pSelf, CLIPBOARD_PASTE); return TRUE; } // TODO: This isn't actually accessible from anywhere if(!strcmp(szCommand, "action_selectall")) { // clipboard_paste dasher_editor_internal_clipboard(pSelf, CLIPBOARD_SELECTALL); return TRUE; } if(!strcmp(szCommand, "action_toggle_game_mode")) { //toggle game mode - dasher_main_toggle_game_mode((DASHER_MAIN_GET_PRIVATE(pPrivate->pDasherMain))->pAppSettings); + dasher_main_toggle_game_mode(pPrivate->pDasherMain); return TRUE; } /* TODO: We need a rethink here */ const gchar *szForwardCommand = NULL; gint iSubCommand = 0; if(!strcmp(szCommand, "speakall")) { szForwardCommand = "Speak"; iSubCommand = 0; } else if(!strcmp(szCommand, "speaklast")) { szForwardCommand = "Speak"; iSubCommand = 1; } else if(!strcmp(szCommand, "speakrepeat")) { szForwardCommand = "Speak"; iSubCommand = 2; } if(szForwardCommand) { gboolean bActionIterStarted = false; EditorAction *pActionIter = pPrivate->pActionRing; while((pActionIter != pPrivate->pActionRing) || !bActionIterStarted) { bActionIterStarted = true; if(!strcmp(dasher_action_get_name(pActionIter->pAction), szForwardCommand)) { dasher_action_execute(pActionIter->pAction, DASHER_EDITOR(pSelf), iSubCommand); return TRUE; } pActionIter = pActionIter->pNext; } return TRUE; } return FALSE; } void dasher_editor_internal_handle_font(DasherEditor *pSelf, const gchar *szFont) { if(strcmp(szFont, "")) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); PangoFontDescription *pFD = pango_font_description_from_string(szFont); gtk_widget_modify_font(GTK_WIDGET(pPrivate->pTextView), pFD); } } gboolean dasher_editor_internal_file_changed(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return pPrivate->bFileModified; } const gchar * dasher_editor_internal_get_filename(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return pPrivate->szFilename; } // TODO: We shouldn't need to know about the buffer here - make this a method of the buffer set const gchar * dasher_editor_internal_get_all_text(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkTextIter oStart; GtkTextIter oEnd; gtk_text_buffer_get_start_iter(pPrivate->pBuffer, &oStart); gtk_text_buffer_get_end_iter(pPrivate->pBuffer, &oEnd); pPrivate->pNewMark = gtk_text_buffer_create_mark(pPrivate->pBuffer, NULL, &oEnd, TRUE); return gtk_text_buffer_get_text(pPrivate->pBuffer, &oStart, &oEnd, false ); } const gchar * dasher_editor_internal_get_new_text(DasherEditor *pSelf) { // TODO: Implement this properly DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkTextIter oStart; GtkTextIter oEnd; gtk_text_buffer_get_end_iter(pPrivate->pBuffer, &oEnd); gtk_text_buffer_get_iter_at_mark(pPrivate->pBuffer, &oStart, pPrivate->pNewMark); const gchar *szRetVal = gtk_text_buffer_get_text(pPrivate->pBuffer, &oStart, &oEnd, false ); pPrivate->pNewMark = gtk_text_buffer_create_mark(pPrivate->pBuffer, NULL, &oEnd, TRUE); return szRetVal; } /* Private methods */ static void dasher_editor_internal_select_all(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkTextIter *start, *end; start = new GtkTextIter; end = new GtkTextIter; gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), start, 0); gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), end, -1); GtkTextMark *selection = gtk_text_buffer_get_mark(pPrivate->pBuffer, "selection_bound"); GtkTextMark *cursor = gtk_text_buffer_get_mark(pPrivate->pBuffer, "insert"); gtk_text_buffer_move_mark(pPrivate->pBuffer, selection, start); gtk_text_buffer_move_mark(pPrivate->pBuffer, cursor, end); delete start; delete end; } static void dasher_editor_internal_setup_actions(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); // TODO: Activate and deactivate methods for actions // TODO: Clear shouldn't be a special case (include support for false in clear method) #ifdef GNOME_SPEECH dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_speech_new())); #endif dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_keyboard_new(pPrivate->pExternalBuffer))); #ifdef WITH_MAEMO dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_keyboard_maemo_new())); #else // dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_copy_new(pSelf))); GDir *pDirectory; G_CONST_RETURN gchar *szFilename; gchar *szUserScriptDir = new gchar[strlen(dasher_app_settings_get_string(pPrivate->pAppSettings, SP_USER_LOC))+9]; strcpy(szUserScriptDir, dasher_app_settings_get_string(pPrivate->pAppSettings, SP_USER_LOC)); strcat(szUserScriptDir, "scripts/"); pDirectory = g_dir_open(szUserScriptDir, 0, NULL); if(pDirectory) { while((szFilename = g_dir_read_name(pDirectory))) { dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_script_new(szUserScriptDir, szFilename))); } g_dir_close(pDirectory); } delete[] szUserScriptDir; gchar *szSystemScriptDir = new gchar[strlen(dasher_app_settings_get_string(pPrivate->pAppSettings, SP_SYSTEM_LOC))+9]; strcpy(szSystemScriptDir, dasher_app_settings_get_string(pPrivate->pAppSettings, SP_SYSTEM_LOC)); strcat(szSystemScriptDir, "scripts/"); pDirectory = g_dir_open(szSystemScriptDir, 0, NULL); if(pDirectory) { while((szFilename = g_dir_read_name(pDirectory))) { dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_script_new(szSystemScriptDir, szFilename))); } g_dir_close(pDirectory); } delete[] szSystemScriptDir; #endif // TODO: Reimplement // // TODO: This doesn't get re-called if the preferences change // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER, "Actions", -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); // int iControlOffset(1); // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, "Clear", -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, Dasher::CControlManager::CTL_USER, -2); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), -1, Dasher::CControlManager::CTL_USER + iControlOffset, -2); // ++iControlOffset; // EditorAction *pCurrentAction = pPrivate->pActionRing; // bool bStarted = false; // while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { // bStarted = true; // if(pCurrentAction->bControl) { // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, dasher_action_get_name(pCurrentAction->pAction), -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, Dasher::CControlManager::CTL_USER, -2); // int iNSub(dasher_action_get_sub_count(pCurrentAction->pAction)); // if(iNSub == 0) { // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), -1, Dasher::CControlManager::CTL_USER + iControlOffset, -2); // } // else { // for(int i(0); i < iNSub; ++i) { // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset + i + 1, dasher_action_get_sub_name(pCurrentAction->pAction, i), -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset + i + 1, Dasher::CControlManager::CTL_USER + iControlOffset, -2); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), -1, Dasher::CControlManager::CTL_USER + iControlOffset + i + 1, -2); // } // } // pCurrentAction->iControlID = Dasher::CControlManager::CTL_USER + iControlOffset; // pCurrentAction->iNSub = iNSub; // iControlOffset += iNSub + 1; // } // pCurrentAction = pCurrentAction->pNext; // } #ifndef WITH_MAEMOFULLSCREEN // dasher_editor_internal_rebuild_action_pane(pSelf); #endif } static void dasher_editor_internal_add_action(DasherEditor *pSelf, DasherAction *pNewAction) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); EditorAction *pNewEditorAction = new EditorAction; pNewEditorAction->pAction = pNewAction; pNewEditorAction->iID = pPrivate->iNextActionID; ++pPrivate->iNextActionID; gchar szRegistryName[256]; strncpy(szRegistryName, "Action_", 256); strncat(szRegistryName, dasher_action_get_name(pNewEditorAction->pAction), 255 - strlen(szRegistryName)); for(unsigned int i(0); i < strlen(szRegistryName); ++i) if(szRegistryName[i] == ' ') szRegistryName[i] = '_'; gint iState; if(!dasher_app_settings_get_free_long(pPrivate->pAppSettings, szRegistryName, iState)) { if(!strcmp(dasher_action_get_name(pNewEditorAction->pAction), "Speak")) iState = 0; else iState = ACTION_STATE_SHOW | ACTION_STATE_CONTROL; dasher_app_settings_set_free_long(pPrivate->pAppSettings, szRegistryName, iState); } pNewEditorAction->bShow = iState & ACTION_STATE_SHOW; pNewEditorAction->bControl = iState & ACTION_STATE_CONTROL; pNewEditorAction->bAuto = iState & ACTION_STATE_AUTO; dasher_editor_internal_check_activity(pSelf, pNewEditorAction); if(pPrivate->pActionRing) { pNewEditorAction->pNext = pPrivate->pActionRing; pNewEditorAction->pPrevious = pPrivate->pActionRing->pPrevious; pPrivate->pActionRing->pPrevious->pNext = pNewEditorAction; pPrivate->pActionRing->pPrevious = pNewEditorAction; } else { pNewEditorAction->pNext = pNewEditorAction; pNewEditorAction->pPrevious = pNewEditorAction; } pPrivate->pActionRing = pNewEditorAction; // TODO: Reimplement // if(iState & ACTION_STATE_SHOW) // gtk_dasher_control_add_action_button(GTK_DASHER_CONTROL(pDasherWidget), dasher_action_get_name(pNewEditorAction->pAction)); } static EditorAction * dasher_editor_internal_get_action_by_id(DasherEditor *pSelf, int iID){ DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); EditorAction *pCurrentAction = pPrivate->pActionRing; bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; if(pCurrentAction->iID == iID) return pCurrentAction; pCurrentAction = pCurrentAction->pNext; } return 0; } static void dasher_editor_internal_rebuild_action_pane(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); // Delete any existing widgets gtk_container_foreach(GTK_CONTAINER(pPrivate->pActionPane), delete_children_callback, 0); // Add the cancel button GtkButton *pNewButton = GTK_BUTTON(gtk_button_new_with_label("Clear")); gtk_widget_show(GTK_WIDGET(pNewButton)); void **pUserData = new void *[2]; pUserData[0] = (void *)pSelf; pUserData[1] = 0; g_signal_connect(G_OBJECT(pNewButton), "clicked", G_CALLBACK(action_button_callback), pUserData); #ifdef WITH_MAEMO // For Maemo we want the packing to expand gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), true, true, 0); #else gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), false, false, 0); #endif EditorAction *pCurrentAction = pPrivate->pActionRing; bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; if(pCurrentAction->bShow) { GtkButton *pNewButton = GTK_BUTTON(gtk_button_new_with_label(dasher_action_get_name(pCurrentAction->pAction))); gtk_widget_show(GTK_WIDGET(pNewButton)); pUserData = new void *[2]; pUserData[0] = (void *)pSelf; pUserData[1] = (void *)(pCurrentAction->pAction); g_signal_connect(G_OBJECT(pNewButton), "clicked", G_CALLBACK(action_button_callback), pUserData); #ifdef WITH_MAEMO // For Maemo we want the packing to expand gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), true, true, 0); #else gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), false, false, 0); #endif } pCurrentAction = pCurrentAction->pNext; } } // TODO: This shouldn't be a part of the editor //static void //dasher_editor_internal_display_message(DasherEditor *pSelf, DasherMessageInfo *pMessageInfo) { // GtkMessageDialog *pDialog = GTK_MESSAGE_DIALOG(gtk_message_dialog_new(0, GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, pMessageInfo->szMessage)); // gtk_dialog_run(GTK_DIALOG(pDialog)); // gtk_widget_destroy(GTK_WIDGET(pDialog)); //} static void dasher_editor_internal_check_activity(DasherEditor *pSelf, EditorAction *pAction) { gboolean bNeedActive(pAction->bShow || pAction->bControl || pAction->bAuto); gboolean bActive(dasher_action_get_active(pAction->pAction)); if(bNeedActive && !bActive) dasher_action_activate(pAction->pAction); else if(!bNeedActive && bActive) dasher_action_deactivate(pAction->pAction); } static void dasher_editor_internal_action_save_state(DasherEditor *pSelf, EditorAction *pAction) { gchar szRegistryName[256]; strncpy(szRegistryName, "Action_", 256); strncat(szRegistryName, dasher_action_get_name(pAction->pAction), 255 - strlen(szRegistryName)); for(unsigned int i(0); i < strlen(szRegistryName); ++i) if(szRegistryName[i] == ' ') szRegistryName[i] = '_'; gint iState = 0; if(pAction->bShow) iState += ACTION_STATE_SHOW; if(pAction->bControl) iState += ACTION_STATE_CONTROL; if(pAction->bAuto) iState += ACTION_STATE_AUTO; DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); dasher_app_settings_set_free_long(pPrivate->pAppSettings, szRegistryName, iState); } static void dasher_editor_internal_command_new(DasherEditor *pSelf) { dasher_editor_internal_new_buffer(pSelf, NULL); } static void dasher_editor_internal_command_open(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkWidget *pTopLevel = gtk_widget_get_toplevel(GTK_WIDGET(pPrivate->pTextView)); GtkWidget *filesel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pTopLevel), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef HAVE_GIO gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(filesel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) { #ifdef HAVE_GIO char *filename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(filesel)); #else char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel)); #endif dasher_editor_internal_new_buffer(pSelf, filename); g_free(filename); } gtk_widget_destroy(filesel); } static void dasher_editor_internal_command_save(DasherEditor *pSelf, gboolean bPrompt, gboolean bAppend) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); gchar *szFilename = NULL; // Hmm... this makes no sense - surely this always evaluates to true? if(bPrompt || !szFilename) { GtkWidget *pTopLevel = gtk_widget_get_toplevel(GTK_WIDGET(pPrivate->pTextView)); GtkWidget *filesel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pTopLevel), GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef HAVE_GIO gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(filesel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) { #ifdef HAVE_GIO szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(filesel)); #else szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel)); #endif } else { gtk_widget_destroy(filesel); return; } gtk_widget_destroy(filesel); } else { szFilename = g_strdup(pPrivate->szFilename); } dasher_editor_internal_save_as(pSelf, szFilename, bAppend); g_free(szFilename); } #ifdef HAVE_GIO static void dasher_editor_internal_gvfs_print_error(DasherEditor *pSelf, GError *error, const char *myfilename) { // Turns a GVFS error into English GtkWidget *error_dialog; error_dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open the file \"%s\"\n%s\n", myfilename, error->message); gtk_dialog_set_default_response(GTK_DIALOG(error_dialog), GTK_RESPONSE_OK); gtk_window_set_resizable(GTK_WINDOW(error_dialog), FALSE); gtk_dialog_run(GTK_DIALOG(error_dialog)); gtk_widget_destroy(error_dialog); return; } static gboolean dasher_editor_internal_gvfs_open_file(DasherEditor *pSelf, const char *uri, gchar **buffer, gsize *size) { GFile *file; GFileInputStream *read_handle; GError *error; GFileInfo *info; gssize bytes_read; file = g_file_new_for_uri (uri); read_handle = g_file_read (file, NULL, &error); /* If URI didn't work, try path */ if (read_handle == NULL) { // PRLW: g_object_unref isn't actually stipulated by g_file_new_for_uri g_object_unref (file); file = g_file_new_for_path (uri); read_handle = g_file_read (file, NULL, &error); } if (read_handle == NULL) { dasher_editor_internal_gvfs_print_error (pSelf, error, uri); g_object_unref (file); return FALSE; } info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NONE, NULL, &error); if (info == NULL) { diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index 0d330df..03c560c 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -48,1025 +48,1067 @@ static void dasher_main_setup_internal_layout(DasherMain *pSelf); static void dasher_main_set_window_title(DasherMain *pSelf); /* ... Table based menu/toolbar commands */ static void dasher_main_command_import(DasherMain *pSelf); static void dasher_main_command_quit(DasherMain *pSelf); static void dasher_main_command_preferences(DasherMain *pSelf); static void dasher_main_command_preferences_alphabet(DasherMain *pSelf); static void dasher_main_command_tutorial(DasherMain *pSelf); static void dasher_main_command_help(DasherMain *pSelf); static void dasher_main_command_about(DasherMain *pSelf); /* c.f. WRAP_CPP_CB below */ extern "C" void dasher_main_cb_import(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_quit(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_preferences(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_help(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_about(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_editor(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_toggle_game_mode(GtkAction*, DasherMain*); static gboolean dasher_main_speed_changed(DasherMain *pSelf); static void dasher_main_alphabet_combo_changed(DasherMain *pSelf); // TODO: populate speed slider static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); /* TODO: order these in file */ static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; -// } +// + +void show_game_file_dialog(GtkWidget *widget, GtkWidget *pButton, gpointer pParent) { + + GtkWidget *pFileDialog = gtk_file_chooser_dialog_new("Choose a Training Text", + static_cast<GtkWindow*> (pParent), + GTK_FILE_CHOOSER_ACTION_OPEN, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, + NULL); + + gtk_window_set_destroy_with_parent(GTK_DIALOG(pDialog)); + + if(gtk_dialog_run(GTK_DIALOG(pFileDialog)) == GTK_RESPONSE_ACCEPT) { + + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileDialog)); + + } + + gtk_widget_destroy(pFileDialog); +} + +void dasher_main_toggle_game_mode(DasherMain *pSelf) { + + DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); + GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, + GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, + _("Welcome to Game Mode! Please select a training text:")); + + GtkWidget *pDefaultButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Use Default"), GTK_RESPONSE_CLOSE); + GtkWidget *pFileButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Choose File..."), 2); + GtkWidget *pCancelButton = gtk_dialog_add_button(GTK_DIALOG(pDialog), _("Cancel"), GTK_RESPONSE_CLOSE); + + g_signal_connect(pDefaultButton, "button-press-event", G_CALLBACK) + g_signal_connect(pFileButton, "button-press-event", G_CALLBACK(show_game_file_dialog), + pDialog); + + gtk_dialog_run(GTK_DIALOG(pDialog)); + + gtk_widget_destroy(pDialog); + + dasher_app_settings_set_bool(pPrivate->pAppSettings, BP_GAME_MODE, true); +} static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; #ifndef WITH_MAEMO case LP_MAX_BITRATE: gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); break; #endif case SP_ALPHABET_ID: dasher_main_populate_alphabet_combo(pSelf); break; case BP_GLOBAL_KEYBOARD: dasher_main_setup_window(pSelf); break; #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN case APP_LP_MAEMO_SIZE: { g_message("Maemo size"); bool bVisible = GTK_WIDGET_VISIBLE(pPrivate->pMainWindow); gtk_widget_hide(pPrivate->pMainWindow); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_MAEMO_SIZE) == 0) { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 150); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 150); gtk_widget_set_size_request(pPrivate->pDasherWidget, 175, -1); } else { int iWidth; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWidth, NULL); gtk_widget_set_size_request(pPrivate->pMainWindow, -1, 250); gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWidth, 250); gtk_widget_set_size_request(pPrivate->pDasherWidget, 280, -1); } if(bVisible) gtk_widget_show(pPrivate->pMainWindow); break; } #endif } if(pPrivate->pPreferencesDialogue) dasher_preferences_dialogue_handle_parameter_change(pPrivate->pPreferencesDialogue, iParameter); if(pPrivate->pEditor) dasher_editor_handle_parameter_change(pPrivate->pEditor, iParameter); } static void dasher_main_load_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); int iWindowWidth; int iWindowHeight; int iEditHeight; if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT); } else { iEditHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH); iWindowWidth = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H); iWindowHeight = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H); } #ifndef WITH_MAEMO gtk_window_resize(GTK_WINDOW(pPrivate->pMainWindow), iWindowWidth, iWindowHeight); #endif gtk_paned_set_position(pPrivate->pDivider, iEditHeight); pPrivate->iWidth = iWindowWidth; pPrivate->iHeight = iWindowHeight; int iWindowX; int iWindowY; iWindowX = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_X); iWindowY = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_Y); gtk_window_move(GTK_WINDOW(pPrivate->pMainWindow), iWindowX, iWindowY); // pPrivate->iPosition = dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION); } static void dasher_main_save_state(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!pPrivate->bWidgetsInitialised) return; int iWindowWidth; int iWindowHeight; int iEditHeight; gtk_window_get_size(GTK_WINDOW(pPrivate->pMainWindow), &iWindowWidth, &iWindowHeight); iEditHeight = gtk_paned_get_position(pPrivate->pDivider); if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_COMPOSE) { // APP_STYLE_DIRECT doesn't have an edit window. if (dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) != APP_STYLE_DIRECT) dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_HEIGHT, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT, iWindowHeight); } else { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_EDIT_WIDTH, iEditHeight); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_WIDTH_H, iWindowWidth); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_SCREEN_HEIGHT_H, iWindowHeight); } int iWindowX; int iWindowY; gtk_window_get_position(GTK_WINDOW(pPrivate->pMainWindow), &iWindowX, &iWindowY); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_X, iWindowX); dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_Y, iWindowY); // dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_DOCK_POSITION, pPrivate->iPosition); } void dasher_main_show(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_widget_show(GTK_WIDGET(pPrivate->pMainWindow)); } static void dasher_main_setup_window(DasherMain *pSelf) { dasher_main_setup_window_style(pSelf); dasher_main_setup_window_state(pSelf); dasher_main_setup_internal_layout(pSelf); // DasherMainPrivate *pPrivate = (DasherMainPrivate *)(pSelf->private_data); // if(dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_GLOBAL_KEYBOARD)) // gdk_window_add_filter(0, keyboard_filter_cb, 0); // else // gdk_window_remove_filter(0, keyboard_filter_cb, 0); } static void dasher_main_populate_controls(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // Populate the alphabet chooser dasher_main_populate_alphabet_combo(pSelf); // Set the value of the speed spinner gtk_spin_button_set_value(pPrivate->pSpeedBox, dasher_app_settings_get_long(pPrivate->pAppSettings, LP_MAX_BITRATE) / 100.0); } static void dasher_main_connect_control(DasherMain *pSelf) { /* TODO: This is very much temporary - we need to think of a better way of presenting application commands in a unified way */ #ifdef GNOME_SPEECH DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, "Speak", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, "All", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, "Last", -1 ); gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, "Repeat", -1 ); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 1, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 1, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 2, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 2, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), Dasher::CControlManager::CTL_USER + 3, Dasher::CControlManager::CTL_USER, -2); gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pPrivate->pDasherWidget), -1, Dasher::CControlManager::CTL_USER + 3, -2); #endif } static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "import")) { dasher_main_command_import(pSelf); return TRUE; } if(!strcmp(szCommand, "quit")) { dasher_main_command_quit(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences")) { dasher_main_command_preferences(pSelf); return TRUE; } if(!strcmp(szCommand, "preferences_alphabet")) { dasher_main_command_preferences_alphabet(pSelf); return TRUE; } if(!strcmp(szCommand, "tutorial")) { dasher_main_command_tutorial(pSelf); return TRUE; } if(!strcmp(szCommand, "help")) { dasher_main_command_help(pSelf); return TRUE; } if(!strcmp(szCommand, "about")) { dasher_main_command_about(pSelf); return TRUE; } if(pPrivate->pEditor) return dasher_editor_command(pPrivate->pEditor, szCommand); return FALSE; } /* Private methods */ /* Window state is basically size and position */ static void dasher_main_setup_window_state(DasherMain *pSelf) { dasher_main_load_state(pSelf); // TODO: Setup positioning here - need to think up a policy on this } /* Setup the window style - this is defined to be window manager hints and the like */ static void dasher_main_setup_window_style(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: // Nothing to do break; case APP_STYLE_COMPOSE: // Nothing to do break; case APP_STYLE_DIRECT: // Direct mode - set always on top gtk_window_set_keep_above(GTK_WINDOW(pPrivate->pMainWindow), true); // Refuse focus gtk_window_set_accept_focus(GTK_WINDOW(pPrivate->pMainWindow), false); // Stick on all desktops gtk_window_stick(GTK_WINDOW(pPrivate->pMainWindow)); break; case APP_STYLE_FULLSCREEN: // Fullscreen mode - set fullscreen gtk_window_fullscreen(GTK_WINDOW(pPrivate->pMainWindow)); break; default: g_error("Inconsistent application style specified."); } } /* Internal layout is the visibility of various widgets */ static void dasher_main_setup_internal_layout(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); if(pPrivate->pToolbar) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); } if(pPrivate->pStatusControl) { if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); } } // TODO: Fold into setup controls? static void dasher_main_set_window_title(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); // Note to translators: This is the name of the dasher program as it appears // in a window title. gchar * dasher = _("Dasher"); if(szFilename == 0) { gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), dasher); } else { gchar *title = g_strdup_printf("%s - %s", dasher, szFilename); gtk_window_set_title(GTK_WINDOW(pPrivate->pMainWindow), title); g_free (title); } } static void dasher_main_command_import(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pFileSel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pPrivate->pMainWindow), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(pFileSel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(pFileSel)) == GTK_RESPONSE_ACCEPT) { #ifdef TEACH_TRAINING_HELPER_LOAD_FILE_ABOUT_URI gchar *szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(pFileSel)); #else gchar *szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSel)); #endif gtk_dasher_control_train(GTK_DASHER_CONTROL(pPrivate->pDasherWidget), szFilename); g_free(szFilename); } gtk_widget_destroy(pFileSel); } static void dasher_main_command_quit(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GtkWidget *pDialogue = NULL; if(dasher_editor_file_changed(pPrivate->pEditor)) { // XXX PRLW: Just open the save dialogue box. #if 0 const gchar *szFilename = dasher_editor_get_filename(pPrivate->pEditor); if(szFilename) { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes to %s?\n\nYour changes will be lost if you don't save them."), szFilename); } else { #endif pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Do you want to save your changes?\n\nYour changes will be lost if you don't save them.")); #if 0 } #endif gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't save"), GTK_RESPONSE_REJECT, _("Don't quit"), GTK_RESPONSE_CANCEL, _("Save and quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_main_quit(); break; case GTK_RESPONSE_CANCEL: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: dasher_editor_command(pPrivate->pEditor, "save"); gtk_main_quit(); break; } } else { pDialogue = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("Are you sure you wish to quit?")); gtk_dialog_add_buttons(GTK_DIALOG(pDialogue), _("Don't quit"), GTK_RESPONSE_REJECT, _("Quit"), GTK_RESPONSE_ACCEPT, NULL); switch (gtk_dialog_run(GTK_DIALOG(pDialogue))) { case GTK_RESPONSE_REJECT: gtk_widget_destroy(GTK_WIDGET(pDialogue)); break; case GTK_RESPONSE_ACCEPT: gtk_main_quit(); } } } static void dasher_main_command_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 0); } static void dasher_main_command_preferences_alphabet(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); dasher_preferences_dialogue_show(pPrivate->pPreferencesDialogue, 1); } static void dasher_main_command_tutorial(DasherMain *pSelf) { // TODO: Implement this } static void dasher_main_command_help(DasherMain *pSelf) { #ifdef HAVE_GTK_SHOW_URI DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); GdkScreen *scr; GError *err = NULL; scr = gtk_widget_get_screen(GTK_WIDGET(pPrivate->pMainWindow)); if (!gtk_show_uri(scr, "ghelp:dasher", gtk_get_current_event_time(), &err)) { GtkWidget *d; d = gtk_message_dialog_new(GTK_WINDOW(pPrivate->pMainWindow), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", _("Unable to open help file")); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d), "%s", err->message); g_signal_connect(d, "response", G_CALLBACK(gtk_widget_destroy), NULL); gtk_window_present(GTK_WINDOW(d)); g_error_free (err); } #endif } static void dasher_main_command_about(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // In alphabetical order - please keep this in sync with the AUTHORS // file at root of the package tree const gchar *authors[] = { "Chris Ball", "Ignas Budvytis", "Peter Conlon", "Phil Cowans", "Frederik Eaton", "Behdad Esfahbod", "Matthew Garrett", "Chris Hack", "Takashi Kaburagi", "Sega Kazue", "Alan Lawrence", "David MacKay", "Iain Murray", diff --git a/Src/Gtk2/dasher_main.h b/Src/Gtk2/dasher_main.h index e6a0106..4b29a4a 100644 --- a/Src/Gtk2/dasher_main.h +++ b/Src/Gtk2/dasher_main.h @@ -1,94 +1,91 @@ #ifndef __dasher_main_h__ #define __dasher_main_h__ #include <glib.h> #include <glib-object.h> #include "Preferences.h" #include "KeyboardHelper.h" #include "DasherAppSettings.h" G_BEGIN_DECLS #define DASHER_TYPE_MAIN (dasher_main_get_type()) #define DASHER_MAIN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), DASHER_TYPE_MAIN, DasherMain )) #define DASHER_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), DASHER_TYPE_MAIN, DasherMainClass )) #define DASHER_IS_MAIN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), DASHER_TYPE_MAIN)) #define DASHER_IS_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), DASHER_TYPE_MAIN)) #define DASHER_MAIN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), DASHER_TYPE_MAIN, DasherMainClass)) // TODO: Make sure this is actually used #define DASHER_MAIN_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), DASHER_TYPE_MAIN, DasherMainPrivate)) typedef struct _DasherMain DasherMain; typedef struct _DasherMainClass DasherMainClass; struct _DasherMain { GObject parent; }; struct _DasherMainClass { GObjectClass parent_class; void (*realized)(DasherMain *pDasherMain); }; struct _DasherMainPrivate { GtkBuilder *pXML; GtkBuilder *pPrefXML; // Child objects owned here DasherAppSettings *pAppSettings; DasherPreferencesDialogue *pPreferencesDialogue; DasherEditor *pEditor; CKeyboardHelper *pKeyboardHelper; // Various widgets which need to be cached: // GtkWidget *pBufferView; GtkPaned *pDivider; GtkWindow *pMainWindow; GtkWidget *pToolbar; GtkSpinButton *pSpeedBox; GtkWidget *pAlphabetCombo; GtkWidget *pStatusControl; GtkWidget *pDasherWidget; GtkListStore *pAlphabetList; GtkAccelGroup *pAccel; gulong iAlphabetComboHandler; // Widgets used for maemo #ifdef WITH_MAEMO DasherMaemoHelper *pMaemoHelper; #ifdef WITH_MAEMOFULLSCREEN HildonProgram *pProgram; HildonWindow *pHWindow; #endif #endif // Properties of the main window int iWidth; int iHeight; bool bWidgetsInitialised; }; typedef struct _DasherMainPrivate DasherMainPrivate; typedef struct _SCommandLine SCommandLine; struct _SCommandLine { gchar *szFilename; gchar *szAppStyle; gchar *szOptions; }; DasherMain *dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine); GType dasher_main_get_type(); //DasherEditorInternal *dasher_main_get_editor(DasherMain *pSelf); void dasher_main_show(DasherMain *pSelf); -static void dasher_main_toggle_game_mode(DasherAppSettings* pAppSettings) { - dasher_app_settings_set_bool(pAppSettings, BP_GAME_MODE, true); -} - +void dasher_main_toggle_game_mode(DasherMain *pSelf); G_END_DECLS #endif diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index efa7306..acedf7e 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,157 +1,157 @@ #include "gtest/gtest.h" #include "../../Src/TestPlatform/MockInterfaceBase.h" #include "../../Src/TestPlatform/MockSettingsStore.h" #include "../../Src/DasherCore/EventHandler.h" #include "../../Src/DasherCore/SettingsStore.h" //A Dasher component that allows tests to easily determine whether //or not it was notified of an event which it subscribed to. class DummyComponent : public Dasher::CDasherComponent { public: int evtCount; std::vector<Dasher::CEvent*> receivedEvents; DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : Dasher::CDasherComponent(pEventHandler, pSettingsStore, std::vector<int>()) { evtCount = 0; } virtual void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; receivedEvents.push_back(pEvent); } }; //An extension of DummyComponent that fires a CStartEvent every time its HandleEvent is called class RecursionComponent : public DummyComponent { public: RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : DummyComponent(pEventHandler, pSettingsStore) { } void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); } }; //Test fixture - sets up the EventHandler, SettingsStore, and InterfaceBase instances. class EventTest : public ::testing::Test { public: EventTest() { interfaceBase = new CMockInterfaceBase(); evtHandler = new Dasher::CEventHandler(interfaceBase); settingsStore = new CMockSettingsStore(evtHandler); } protected: Dasher::CEventHandler *evtHandler; CMockInterfaceBase *interfaceBase; CMockSettingsStore *settingsStore; }; //very basic test - subscribe 5 components, fire one event, and assert that they all were notified TEST_F(EventTest, BasicTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 5; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } evtHandler->InsertEvent(new CParameterNotificationEvent(0)); for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { EXPECT_EQ((*iter)->evtCount, 1); } } //stress test - register a lot of listeners, fire a lot of events, and EXPECT that //everything was notified without crashing TEST_F(EventTest, StressTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 1000; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } for(int c = 0; c < 1000; c++) { evtHandler->InsertEvent(new CParameterNotificationEvent(0)); } for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { EXPECT_EQ((*iter)->evtCount, 1000); } } //test for proper behavior when components call InsertEvent in their HandleEvent TEST_F(EventTest, RecursionTest) { RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); evtHandler->RegisterListener(listener, EV_START); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(rec1->evtCount, 1); EXPECT_EQ(rec2->evtCount, 1); EXPECT_EQ(listener->evtCount, 2); } //register listeners for one event, fire a different event, and //check that they DON'T receieve that event TEST_F(EventTest, StaysQuiet) { DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); - evtHandler->RegisterListener(listener1, EV_TEXTDRAW); + evtHandler->RegisterListener(listener1, EV_GAME_NODE_DRAWN); evtHandler->RegisterListener(listener2, EV_COMMAND); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(listener1->evtCount, 0); EXPECT_EQ(listener2->evtCount, 0); } //verify that events are fired in the order we claim them to be TEST_F(EventTest, EventOrdering) { std::vector<CEvent*> events; DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(listener, EV_START); for(int c = 0; c < 5; c++) { Dasher::CStartEvent *curEvt = new Dasher::CStartEvent(); events.push_back(curEvt); evtHandler->InsertEvent(curEvt); } for(int c = 0; c < 5; c++) { EXPECT_EQ(events[c], listener->receivedEvents[c]); } }
rgee/HFOSS-Dasher
5189b7cc0ea5580c4dcedd91736b9e028d50375e
Started approximation function. Untested
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 352352b..bc87d4e 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,623 +1,671 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } +void CDasherModel::GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode) { + int iTargetSymbol = m_pNodeCreationManager->GetAlphabet()->GetSymbol(m_strGameTarget); + + // If the first symbol is greater than the target, we know the target + // must be off the child list to the left + if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().begin()))->iSymbol > iTargetSymbol ) { + m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair(static_cast<CDasherNode*>(NULL), (*pNode->GetChildren().begin())))); + return; + } + + // If the last symbol is less than the target, we know the target must + // be off the child list to the right + if( static_cast<CAlphabetManager::CSymbolNode*>((*pNode->GetChildren().end()))->iSymbol < iTargetSymbol ) { + m_pEventHandler->InsertEvent(new CNoGameNodeEvent(std::make_pair( (*pNode->GetChildren().end()), static_cast<CDasherNode*>(NULL) ))); + return; + } + + // Otherwise, it's between two elements of the child list. Find those + // elements and send them out. + for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); + it != pNode->GetChildren().end(); it++) { + if( static_cast<CAlphabetManager::CSymbolNode*>((*it))->iSymbol > iTargetSymbol ) { + m_pEventHandler->InsertEvent(new CNoGameNodeEvent( std::make_pair( (*--it), (*it) ) )); + return; + } + } + +} + bool CDasherModel::GameSearchChildren(CDasherNode* pNode) { for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); it != pNode->GetChildren().end(); it++) { if( GameSearchIndividual((*it)) ) return true; } + + // If we cannot find the target string, it must not be drawn. We know this because every subtree + // in the dasher model has one instance of each node in the alphabet. It must be there + // somewhere or it's not drawn OR it's not in the alphabet at all. In the last case, we have + // larger problems... + int iType = pNode->GetType(); + if((iType == NT_GROUP) || (iType == NT_SYMBOL)) { + if(iType == NT_SYMBOL) { + CAlphabetManager::CSymbolNode* newNode = static_cast<CAlphabetManager::CSymbolNode*>(pNode); + GameSearchApproximate(newNode); + } +/* + if(iType == NT_GROUP) { + CAlphabetManager::CGroupNode* newNode = static_cast<CAlphabetManager::CGroupNode*>(pNode); + GameSearchApproximate(newNode); + } +*/ + } + return false; } bool CDasherModel::GameSearchIndividual(CDasherNode* pNode) { int iType = pNode->GetType(); if(iType == NT_GROUP) { if(GameSearchChildren(pNode)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } else if(iType == NT_SYMBOL) { if(pNode->IsTarget(m_strGameTarget)) { pNode->SetFlag(NF_GAME, true); return true; } return false; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. GameSearchChildren(Get_node_under_crosshair()); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 828364d..857b614 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,398 +1,406 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; /** * The string a user must type if game mode is active. */ std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Search the model for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchChildren(CDasherNode* pNode); /// /// Search the model (recursively) for the target string /// /// \param pNode The node to search /// \return True if a node was found, false otherwise /// bool GameSearchIndividual(CDasherNode* pNode); - + + /// + /// Approximate the position of the target node, if it was not + /// explicitly found. + /// + /// \param pNode The node to begin the search from + /// \warning Currently only works for symbol or group nodes. This + /// needs to be improved. + void GameSearchApproximate(CAlphabetManager::CSymbolNode* pNode); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */ diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index e6b811f..65d52a1 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,195 +1,201 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; class CNoGameNodeEvent; } /* * The enumeration of event types. Whenever you add a new event type, * you must add its enum representation here. You must also make sure * to change the constant in EventHandler that refers to the number of events * or you will likely get errors. */ enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; /** * An event that represents when the game target node cannot be found * among the current last-typed node's children. Since the set of child * nodes is a set consisting of all possible characters in the current * alphabet, the only way for it not to exist at all is if it was not * drawn yet. */ class Dasher::CNoGameNodeEvent : public Dasher::CEvent { public: - CNoGameNodeEvent(CDasherNode* pNode) - : m_pNode(pNode) { + CNoGameNodeEvent(std::pair<CDasherNode*, CDasherNode*> pNodes) + : m_pNodes(pNodes) { m_iEventType = EV_NO_GAME_NODE; }; /* - * One of the nodes we use to approximate the position of the target - * Node + * The pair of nodes that represent the closest drawn nodes to the top + * and bottom of where the target node /should/ be. + * + * If the left of this pair is null, the target node is at the top-most + * node in the current subtree of the model (in Dasher space). + * + * Conversely, if the right of this pair is null, the target node exists + * at the bottom of the current subtree of the model. */ - CDasherNode* m_pNode; + std::pair<CDasherNode*, CDasherNode*> m_pNodes; }; class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; CDasherNode* m_pNode; screenint m_iX, m_iY; CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index b712343..0c91d79 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,141 +1,141 @@ #include "GameModule.h" using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ -const int Dasher::CGameModule::vEvents[2] = {EV_EDIT, EV_GAME_NODE_DRAWN}; +const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_GAME_NODE_DRAWN, EV_NO_GAME_NODE}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 7c58e11..20e4e4f 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,228 +1,228 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" #include <tr1/memory> namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::tr1::shared_ptr<CWordGeneratorBase> pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ std::tr1::shared_ptr<CWordGeneratorBase> m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /** * Flag that denotes whether we are approximating the target position * or not. */ bool m_bApproximating; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ - static const int vEvents[2]; + static const int vEvents[3]; }; } #endif
rgee/HFOSS-Dasher
6383e69b5a932c6bc902f31f45f69049626f09c8
Finished moving game node searching to the model. The model now searches for game nodes itself.
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index 12ca4e4..9795a16 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,489 +1,452 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iType, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, iType), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, NT_SYMBOL, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, NT_SYMBOL, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup) : CAlphNode(pParent, NT_GROUP, iOffset, iLbnd, iHbnd, pGroup ? (pGroup->bVisible ? pGroup->iColour : pParent->getColour()) : pMgr->m_pNCManager->GetAlphabet()->GetColour(0, iOffset%2), pGroup ? pGroup->strLabel : "", pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { return new CSymbolNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup) { return new CGroupNode(pParent, iOffset, iLbnd, iHbnd, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pNewNode = makeGroup(pParent, iNewOffset, iLower, iUpper, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pNewNode = makeSymbol(pParent, iNewOffset, iLower, iUpper, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->iContext = iContext; return pNewNode; } -bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { - if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { - SetFlag(NF_GAME, true); - return true; - } - return false; -} - bool CAlphabetManager::CSymbolNode::IsTarget(string strTargetUtf8Char) { - return m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char; -} - -/* -bool CAlphabetManager::CSymbolNode::GameSearchBounds(string strTargetUtf8Char) { - int targetSymbol = m_pMgr->m_pNCManager->GetAlphabet()->GetSymbol(strTargetUtf8Char); - - if( (targetSymbol == iSymbol - 1) || - (targetSymbol == iSymbol + 1)) { - - } + g_pLogger->Log("Comparing to: " + m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol)); + return (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char); } -*/ - -bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { - if (GameSearchChildren(strTargetUtf8Char)) { - SetFlag(NF_GAME, true); - return true; - } - return false; -} - -/* -bool CAlphabetManager::CGroupNode::GameSearchBounds(string strTargetUtf8Char) { - if (GameSearchChildBounds(strTargetUtf8Char)) { - return true; - } - return false; -} -*/ - - CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->offset() == offset()); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // When creating a group node... // ...the offset is the same as the parent... CGroupNode *pNewNode = makeGroup(pParent, pParent->offset(), iLbnd, iHbnd, pInfo); //...as is the context! pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (offset() == pParent->offset()); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); } else { // TODO: Exceptions / error handling in general CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, pParent->offset()+1, iLbnd, iHbnd, iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(offset() == pParent->offset() + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); //loop for eliding groups with single children (see below). // Variables store necessary properties of any elided groups: std::string groupPrefix=""; int iOverrideColour=-1; SGroupInfo *pInner=pCurrentNode; while (true) { if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop break; //exit inner (group elision) loop } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); i = pInner->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) // (maybe not of pCurrentNode now, which might be a subgroup filling the original) break; //exit inner (group elision) loop } //were about to create a group node, which would have only one child // (eventually, if the group node were PopulateChildren'd). // Such a child would entirely fill it's parent (the group), and thus, // creation/destruction of the child would cause the node's colour to flash // between that for parent group and child. // Hence, instead we elide the group node and create the child _here_... //1. however we also have to take account of the appearance of the elided group. Hence: groupPrefix += pInner->strLabel; if (pInner->bVisible) iOverrideColour=pInner->iColour; //2. now go into the group... pInner = pInner->pChild; bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok //3. loop round inner loop... } //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); //now adjust the node we've actually created, to take account of any elided group(s)... // tho not if we've reused the existing node, assume that's been adjusted already if (pNewChild && pNewChild!=buildAround) pNewChild->PrependElidedGroup(iOverrideColour, groupPrefix); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(offset()); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(offset()-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/AlphabetManager.h b/Src/DasherCore/AlphabetManager.h index 3c6c77b..9b2a1eb 100644 --- a/Src/DasherCore/AlphabetManager.h +++ b/Src/DasherCore/AlphabetManager.h @@ -1,172 +1,161 @@ // AlphabetManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __alphabetmanager_h__ #define __alphabetmanager_h__ #include "LanguageModelling/LanguageModel.h" #include "DasherNode.h" #include "Parameters.h" #include "NodeManager.h" class CNodeCreationManager; struct SGroupInfo; namespace Dasher { class CDasherInterfaceBase; /// \ingroup Model /// @{ /// Implementation of CNodeManager for regular 'alphabet' nodes, ie /// the basic Dasher behaviour. Child nodes are populated according /// to the appropriate alphabet file, with sizes given by the /// language model. /// class CAlphabetManager : public CNodeManager { public: CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel); class CGroupNode; class CAlphNode : public CDasherNode { public: virtual CAlphabetManager *mgr() {return m_pMgr;} CAlphNode(CDasherNode *pParent, int iType, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr); CLanguageModel::Context iContext; /// /// Delete any storage alocated for this node /// virtual ~CAlphNode(); virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel); CDasherNode *RebuildParent(int iNewOffset); ///Have to call this from CAlphabetManager, and from CGroupNode on a _different_ CAlphNode, hence public... virtual std::vector<unsigned int> *GetProbInfo(); virtual int ExpectedNumChildren(); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd)=0; virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd)=0; private: std::vector<unsigned int> *m_pProbInfo; protected: CAlphabetManager *m_pMgr; }; class CSymbolNode : public CAlphNode { public: ///Standard constructor, gets colour+label by looking up symbol in current alphabet (& computing phase from offset) CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol iSymbol); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual CDasherNode *RebuildParent(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization); virtual void Undo(int *pNumDeleted); virtual void SetFlag(int iFlag, bool bValue); /** * Checks whether this node represents the target string. * In the case of group nodes, this function checks this node's * children, which are symbol nodes. * @param strTargetUtf8Char The string to compare to. * @return True if this node represents the target string. False * otherwise. */ - virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual bool IsTarget(std::string strTargetUTf8Char); virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); virtual symbol GetAlphSymbol(); const symbol iSymbol; virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); private: virtual const std::string &outputText(); protected: ///Compatibility constructor, so that subclasses can specify their own colour & label CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol); }; class CGroupNode : public CAlphNode { public: CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup); /// /// Provide children for the supplied node /// virtual CDasherNode *RebuildParent(); virtual void PopulateChildren(); virtual int ExpectedNumChildren(); - - /** - * Checks whether this node represents the target string. - * In the case of group nodes, this function checks this node's - * children, which are symbol nodes. - * @param strTargetUtf8Char The string to compare to. - * @return True if this node represents the target string. False - * otherwise. - */ - virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); std::vector<unsigned int> *GetProbInfo(); private: SGroupInfo *m_pGroup; }; public: /// /// Get a new root node owned by this manager /// bEnteredLast - true if this "root" node should be considered as entering the preceding symbol /// Offset is the index of the character which _child_ nodes (i.e. between which this root allows selection) /// will enter. (Also used to build context for preceding characters.) virtual CAlphNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset); protected: /// /// Factory method for CAlphNode construction, so subclasses can override. /// virtual CSymbolNode *makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol); virtual CGroupNode *makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup); virtual CDasherNode *CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CLanguageModel::Context CreateSymbolContext(CAlphNode *pParent, symbol iSymbol); virtual CGroupNode *CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); CLanguageModel *m_pLanguageModel; CNodeCreationManager *m_pNCManager; private: void IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround); CLanguageModel::Context m_iLearnContext; CDasherInterfaceBase *m_pInterface; }; /// @} } #endif diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index db1f1a2..352352b 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,841 +1,832 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } -void CDasherModel::GameSearch(CDasherNode* pNode) { +bool CDasherModel::GameSearchChildren(CDasherNode* pNode) { + for(CDasherNode::ChildMap::const_iterator it = pNode->GetChildren().begin(); + it != pNode->GetChildren().end(); it++) { + if( GameSearchIndividual((*it)) ) return true; + } + return false; +} + +bool CDasherModel::GameSearchIndividual(CDasherNode* pNode) { int iType = pNode->GetType(); - - if(iType == NT_SYMBOL) { - CAlphabetManager::CSymbolNode* specNode = static_cast<CAlphabetManager::CSymbolNode*>(pNode); - if(specNode->IsTarget(m_strGameTarget)) { - specNode->SetFlag(NF_GAME, true); + if(iType == NT_GROUP) { + if(GameSearchChildren(pNode)) { + pNode->SetFlag(NF_GAME, true); + return true; } - } else if(iType == NT_GROUP) { - for(std::deque<CDasherNode*>::const_iterator it = pNode->GetChildren().begin(); - it != pNode->GetChildren().end(); ++it) { - GameSearch((*it)); + return false; + } else if(iType == NT_SYMBOL) { + if(pNode->IsTarget(m_strGameTarget)) { + pNode->SetFlag(NF_GAME, true); + return true; } + return false; } - } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. - GameSearch(Get_node_under_crosshair()); + GameSearchChildren(Get_node_under_crosshair()); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. - ///GAME MODE TEMP/////////// - // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create - // new children. - - //GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); - //if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) - if(pNode->GetFlag(NF_GAME)) - { - /*std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); - - // Check if this is the last node in the sentence... - if(strTargetUtf8Char == "GameEnd") - pNode->SetFlag(NF_END_GAME, true); - else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { - // Target character not found - not in our current alphabet?!?! - // Let's give up! - pNode->SetFlag(NF_END_GAME, true); - }*/ - GameSearch(Get_node_under_crosshair()); + if(pNode->GetFlag(NF_GAME)) { + GameSearchChildren(Get_node_under_crosshair()); } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 3f04d36..828364d 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,389 +1,398 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; /** * The string a user must type if game mode is active. */ std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Search the model for the target string + /// + /// \param pNode The node to search + /// \return True if a node was found, false otherwise + /// + bool GameSearchChildren(CDasherNode* pNode); + + /// + /// Search the model (recursively) for the target string /// /// \param pNode The node to search + /// \return True if a node was found, false otherwise /// - void GameSearch(CDasherNode* pNode); + bool GameSearchIndividual(CDasherNode* pNode); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */ diff --git a/Src/DasherCore/DasherNode.cpp b/Src/DasherCore/DasherNode.cpp index 40c128d..3f61825 100644 --- a/Src/DasherCore/DasherNode.cpp +++ b/Src/DasherCore/DasherNode.cpp @@ -1,207 +1,200 @@ // DasherNode.cpp // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" // #include "AlphabetManager.h" - doesnt seem to be required - pconlon #include "DasherInterfaceBase.h" using namespace Dasher; using namespace Opts; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif static int iNumNodes = 0; int Dasher::currentNumNodeObjects() {return iNumNodes;} //TODO this used to be inline - should we make it so again? CDasherNode::CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, int iType) : m_pParent(pParent), m_iOffset(iOffset), m_iLbnd(iLbnd), m_iHbnd(iHbnd), m_iColour(iColour), m_strDisplayText(strDisplayText), m_iType(iType) { DASHER_ASSERT(iHbnd >= iLbnd); if (pParent) { DASHER_ASSERT(!pParent->GetFlag(NF_ALLCHILDREN)); pParent->Children().push_back(this); } onlyChildRendered = NULL; // Default flags (make a definition somewhere, pass flags to constructor?) m_iFlags = 0; m_iRefCount = 0; iNumNodes++; } // TODO: put this back to being inlined CDasherNode::~CDasherNode() { // std::cout << "Deleting node: " << this << std::endl; // Release any storage that the node manager has allocated, // unreference ref counted stuff etc. Delete_children(); // std::cout << "done." << std::endl; iNumNodes--; } void CDasherNode::PrependElidedGroup(int iGroupColour, string &strGroupLabel) { if (m_iColour==-1) m_iColour = iGroupColour; m_strDisplayText = strGroupLabel + m_strDisplayText; } void CDasherNode::Trace() const { /* TODO sort out dchar out[256]; if (m_Symbol) wsprintf(out,TEXT("%7x %3c %7x %5d %7x %5d %8x %8x \n"),this,m_Symbol,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); else wsprintf(out,TEXT("%7x %7x %5d %7x %5d %8x %8x \n"),this,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); OutputDebugString(out); if (m_Children) { unsigned int i; for (i=1;i<m_iChars;i++) m_Children[i]->Dump_node(); } */ } void CDasherNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN)) { DASHER_ASSERT(m_pParent); if (m_pParent) m_pParent->GetContext(pInterface, vContextSymbols, iOffset,iLength); } else { std::string strContext = pInterface->GetContext(iOffset, iLength); pInterface->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } } CDasherNode *const CDasherNode::Get_node_under(int iNormalization, myint miY1, myint miY2, myint miMousex, myint miMousey) { myint miRange = miY2 - miY1; ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { CDasherNode *pChild = *i; myint miNewy1 = miY1 + (miRange * pChild->m_iLbnd) / iNormalization; myint miNewy2 = miY1 + (miRange * pChild->m_iHbnd) / iNormalization; if(miMousey < miNewy2 && miMousey > miNewy1 && miMousex < miNewy2 - miNewy1) return pChild->Get_node_under(iNormalization, miNewy1, miNewy2, miMousex, miMousey); } return this; } // kill ourselves and all other children except for the specified // child // FIXME this probably shouldn't be called after history stuff is working void CDasherNode::OrphanChild(CDasherNode *pChild) { DASHER_ASSERT(ChildCount() > 0); ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { if((*i) != pChild) { (*i)->Delete_children(); delete (*i); } } pChild->m_pParent=NULL; Children().clear(); SetFlag(NF_ALLCHILDREN, false); } // Delete nephews of the child which has the specified symbol // TODO: Need to allow for subnode void CDasherNode::DeleteNephews(CDasherNode *pChild) { DASHER_ASSERT(Children().size() > 0); ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { if(*i != pChild) { (*i)->Delete_children(); } } } // TODO: Need to allow for subnodes // TODO: Incorporate into above routine void CDasherNode::Delete_children() { // std::cout << "Start: " << this << std::endl; ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { // std::cout << "CNM: " << (*i)->MgrID() << (*i) << " " << (*i)->Parent() << std::endl; delete (*i); } Children().clear(); // std::cout << "NM: " << MgrID() << std::endl; SetFlag(NF_ALLCHILDREN, false); } void CDasherNode::SetFlag(int iFlag, bool bValue) { if(bValue) m_iFlags = m_iFlags | iFlag; else m_iFlags = m_iFlags & (~iFlag); } void CDasherNode::SetParent(CDasherNode *pNewParent) { DASHER_ASSERT(pNewParent); DASHER_ASSERT(!pNewParent->GetFlag(NF_ALLCHILDREN)); m_pParent = pNewParent; pNewParent->Children().push_back(this); } int CDasherNode::MostProbableChild() { int iMax(0); int iCurrent; for(ChildMap::iterator it(m_mChildren.begin()); it != m_mChildren.end(); ++it) { iCurrent = (*it)->Range(); if(iCurrent > iMax) iMax = iCurrent; } return iMax; } -bool CDasherNode::GameSearchChildren(string strTargetUtf8Char) { - for (ChildMap::iterator i = Children().begin(); i != Children().end(); i++) { - if ((*i)->GameSearchNode(strTargetUtf8Char)) return true; - } - - return false; -} diff --git a/Src/DasherCore/DasherNode.h b/Src/DasherCore/DasherNode.h index 445063e..fdfa284 100644 --- a/Src/DasherCore/DasherNode.h +++ b/Src/DasherCore/DasherNode.h @@ -1,357 +1,357 @@ // DasherNode.h // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherNode_h__ #define __DasherNode_h__ #include "../Common/Common.h" #include "../Common/NoClones.h" #include "LanguageModelling/LanguageModel.h" #include "DasherTypes.h" #include "NodeManager.h" namespace Dasher { class CDasherNode; class CDasherInterfaceBase; }; #include <deque> #include <iostream> #include <vector> // Node flag constants #define NF_COMMITTED 1 #define NF_SEEN 2 #define NF_CONVERTED 4 #define NF_GAME 8 #define NF_ALLCHILDREN 16 #define NF_SUPER 32 #define NF_END_GAME 64 // Node types. One for each type of node. enum { NT_GROUP = 1, NT_SYMBOL, NT_CONTROL, NT_CONV, NT_CONVROOT }; /// \ingroup Model /// @{ /// @brief A node in the Dasher model /// /// The Dasher node represents a box drawn on the display. This class /// contains the information required to render the node, as well as /// navigation within the model (parents and children /// etc.). Additional information is stored in m_pUserData, which is /// interpreted by the node manager associated with this class. Any /// logic specific to a particular node manager should be stored here. /// /// @todo Encapsulate presentation data in a structure? /// @todo Check that all methods respect the pseudochild attribute class Dasher::CDasherNode:private NoClones { public: inline int GetType() const { return m_iType; } /// Display attributes of this node, used for rendering. /// Colour: -1 for invisible inline int getColour() {return m_iColour;} inline std::string &getDisplayText() {return m_strDisplayText;} ///Whether labels on child nodes should be displaced to the right of this node's label. /// (Default implementation returns true, subclasses should override if appropriate) virtual bool bShove() {return true;} inline int offset() {return m_iOffset;} CDasherNode *onlyChildRendered; //cache that only one child was rendered (as it filled the screen) /// Container type for storing children. Note that it's worth /// optimising this as lookup happens a lot typedef std::deque<CDasherNode*> ChildMap; /// @brief Constructor /// /// @param pParent Parent of the new node /// @param iLbnd Lower bound of node within parent /// @param iHbnd Upper bound of node within parent /// @param pDisplayInfo Struct containing information on how to display the node /// CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, int iType); /// @brief Destructor /// virtual ~CDasherNode(); /// Adjusts the colour & label of this node to look as it would if it /// were the sole child of another node with the specified colour and label /// (without actually making the other/group node) void PrependElidedGroup(int iGroupColour, std::string &strGroupLabel); void Trace() const; // diagnostic /// @name Routines for manipulating node status /// @{ /// @brief Set a node flag /// /// Set various flags corresponding to the state of the node. The following flags are defined: /// /// NF_COMMITTED - Node is 'above' the root, so corresponding symbol /// has been added to text box, language model trained etc /// /// NF_SEEN - Node has already been output /// /// NF_CONVERTED - Node has been converted (eg Japanese mode) /// /// NF_GAME - Node is on the path in game mode /// /// NF_ALLCHILDREN - Node has all children (TODO: obsolete?) /// /// NF_SUPER - Node covers entire visible area /// /// NF_END_GAME - Node is the last one of the phrase in game mode /// /// /// @param iFlag The flag to set /// @param bValue The new value of the flag /// virtual void SetFlag(int iFlag, bool bValue); /// @brief Get the value of a flag for this node /// /// @param iFlag The flag to get /// /// @return The current value of the flag /// inline bool GetFlag(int iFlag) const; /// @} /// @name Routines relating to the size of the node /// @{ // Lower and higher bounds, and the range /// @brief Get the lower bound of a node /// /// @return The lower bound /// inline unsigned int Lbnd() const; /// @brief Get the upper bound of a node /// /// @return The upper bound /// inline unsigned int Hbnd() const; /// @brief Get the range of a node (upper - lower bound) /// /// @return The range /// /// @todo Should this be here (trivial arithmethic of existing methods) /// inline unsigned int Range() const; /// @brief Reset the range of a node /// /// @param iLower New lower bound /// @param iUpper New upper bound /// inline void SetRange(unsigned int iLower, unsigned int iUpper); /// @brief Get the size of the most probable child /// /// @return The size /// int MostProbableChild(); /// @} /// @name Routines for manipulating relatives /// @{ inline const ChildMap & GetChildren() const; inline unsigned int ChildCount() const; inline CDasherNode *Parent() const; void SetParent(CDasherNode *pNewParent); // TODO: Should this be here? CDasherNode *const Get_node_under(int, myint y1, myint y2, myint smousex, myint smousey); // find node under given co-ords /// @brief Orphan a child of this node /// /// Deletes all other children, and the node itself /// /// @param pChild The child to keep /// void OrphanChild(CDasherNode * pChild); /// @brief Delete the nephews of a given child /// /// @param pChild The child to keep /// void DeleteNephews(CDasherNode *pChild); /// @brief Delete the children of this node /// /// void Delete_children(); /// @} /// /// Sees if a *child* / descendant of the specified node (not that node itself) /// represents the specified character. If so, set the child & intervening nodes' /// NF_GAME flag, and return true; otherwise, return false. /// bool GameSearchChildren(std::string strTargetUtf8Char); /// @name Management routines (once accessed via NodeManager) /// @{ /// Gets the node manager for this object. Meaning defined by subclasses, /// which should override and refine the return type appropriately; /// the main use is to provide runtime type info to check casting! virtual CNodeManager *mgr() = 0; /// /// Provide children for the supplied node /// virtual void PopulateChildren() = 0; /// The number of children which a call to PopulateChildren can be expected to generate. /// (This is not required to be 100% accurate, but any discrepancies will likely cause /// the node budgetting algorithm to behave sub-optimally) virtual int ExpectedNumChildren() = 0; /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) {}; virtual void Undo(int *pNumDeleted) {}; virtual void Enter() {}; virtual void Leave() {}; virtual CDasherNode *RebuildParent() { return 0; }; /// /// Get as many symbols of context, up to the _end_ of the specified range, /// as possible from this node and its uncommitted ancestors /// virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); /// ACL Not really sure why we should have to have this, but seems it's needed for something /// to do with speech on Linux. I'm preserving it for now (indeed, making it part of CDasherNode, /// rather than CControlManager::CContNode, where it should be - but that would require making /// m_iOffset visible), as hopefully all speech functionality will be redone shortly... void SetControlOffset(int iOffset) {m_iOffset = iOffset;}; /// /// See if this node represents the specified alphanumeric character; if so, set it's NF_GAME flag and /// return true; otherwise, return false. - /// - virtual bool GameSearchNode(std::string strTargetUtf8Char) {return false;} + /// + virtual bool IsTarget(std::string strTargetUtf8Char) {return false;} /// Clone the context of the specified node, if it's an alphabet node; /// else return an empty context. (Used by ConversionManager) virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel) { return pLanguageModel->CreateEmptyContext(); }; virtual symbol GetAlphSymbol() { throw "Hack for pre-MandarinDasher ConversionManager::BuildTree method, needs to access CAlphabetManager-private struct"; } /// @} private: inline ChildMap &Children(); unsigned int m_iLbnd; unsigned int m_iHbnd; // the cumulative lower and upper bound prob relative to parent int m_iRefCount; // reference count if ancestor of (or equal to) root node ChildMap m_mChildren; // pointer to array of children CDasherNode *m_pParent; // pointer to parent // Binary flags representing the state of the node int m_iFlags; int m_iOffset; // The type of this node. int m_iType; protected: int m_iColour; std::string m_strDisplayText; }; /// @} namespace Dasher { /// Return the number of CDasherNode objects currently in existence. int currentNumNodeObjects(); } ///////////////////////////////////////////////////////////////////////////// // Inline functions ///////////////////////////////////////////////////////////////////////////// namespace Dasher { inline unsigned int CDasherNode::Lbnd() const { return m_iLbnd; } inline unsigned int CDasherNode::Hbnd() const { return m_iHbnd; } inline unsigned int CDasherNode::Range() const { return m_iHbnd - m_iLbnd; } inline CDasherNode::ChildMap &CDasherNode::Children() { return m_mChildren; } inline const CDasherNode::ChildMap &CDasherNode::GetChildren() const { return m_mChildren; } inline unsigned int CDasherNode::ChildCount() const { return m_mChildren.size(); } inline bool CDasherNode::GetFlag(int iFlag) const { return ((m_iFlags & iFlag) != 0); } inline CDasherNode *CDasherNode::Parent() const { return m_pParent; } inline void CDasherNode::SetRange(unsigned int iLower, unsigned int iUpper) { m_iLbnd = iLower; m_iHbnd = iUpper; } } #endif /* #ifndef __DasherNode_h__ */
rgee/HFOSS-Dasher
421f18cf90e3511dd27d8596b3bc41d609bfa393
Began moving game search to the model and out of the specific node methods. Allows us to fire events easily while searching, for example. It also makes the code clearer.
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 4bef83f..db1f1a2 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,823 +1,841 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } +void CDasherModel::GameSearch(CDasherNode* pNode) { + int iType = pNode->GetType(); + + if(iType == NT_SYMBOL) { + CAlphabetManager::CSymbolNode* specNode = static_cast<CAlphabetManager::CSymbolNode*>(pNode); + if(specNode->IsTarget(m_strGameTarget)) { + specNode->SetFlag(NF_GAME, true); + } + } else if(iType == NT_GROUP) { + for(std::deque<CDasherNode*>::const_iterator it = pNode->GetChildren().begin(); + it != pNode->GetChildren().end(); ++it) { + GameSearch((*it)); + } + } + +} + void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. - Get_node_under_crosshair()->GameSearchChildren(m_strGameTarget); + GameSearch(Get_node_under_crosshair()); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. //GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); //if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) if(pNode->GetFlag(NF_GAME)) { /*std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); }*/ - Get_node_under_crosshair()->GameSearchChildren(m_strGameTarget); + GameSearch(Get_node_under_crosshair()); } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } + diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 85dbf02..3f04d36 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,379 +1,389 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } + + /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; /** * The string a user must type if game mode is active. */ std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); + /// + /// Search the model for the target string + /// + /// \param pNode The node to search + /// + void GameSearch(CDasherNode* pNode); + + /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */ diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 2e5a2ee..e6b811f 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,166 +1,195 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; + class CNoGameNodeEvent; } +/* + * The enumeration of event types. Whenever you add a new event type, + * you must add its enum representation here. You must also make sure + * to change the constant in EventHandler that refers to the number of events + * or you will likely get errors. + */ enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN, + EV_NO_GAME_NODE }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; +/** + * An event that represents when the game target node cannot be found + * among the current last-typed node's children. Since the set of child + * nodes is a set consisting of all possible characters in the current + * alphabet, the only way for it not to exist at all is if it was not + * drawn yet. + */ +class Dasher::CNoGameNodeEvent : public Dasher::CEvent { +public: + CNoGameNodeEvent(CDasherNode* pNode) + : m_pNode(pNode) { + m_iEventType = EV_NO_GAME_NODE; + }; + + /* + * One of the nodes we use to approximate the position of the target + * Node + */ + CDasherNode* m_pNode; +}; + class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; CDasherNode* m_pNode; screenint m_iX, m_iY; CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index c9fb4b1..4b6ef71 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,167 +1,167 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ /** * This class handles the dispatch and management of events throughout Dasher. * Any class that derives from CDasherComponent can subscribe to events. These * events are enumerated in Event.h. All CDasherComponents are automatically * registered for their selected events on construction. * * Components SHOULD specify exactly which events they're interested in * instead of omitting this information. This allows the event management * system to make optimal use of time in dispatching events. (i.e. cuts * down on unused event dispatching) */ class Dasher::CEventHandler { public: - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(11), m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(12), m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. * * @warning If this is called from an Event Handler, (i.e. While events * are being processed) the event is enqueued to be dispatched * and NOT immediately dispatched. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for all events. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; /** * Dispatch all the events in the event queue, and take * care of all the pending additions/deletions to m_vSpecificListeners * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and * m_vPendSpecificUnreg */ void ProcessEventQueue(); /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index c47adfa..b712343 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,140 +1,141 @@ #include "GameModule.h" using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ const int Dasher::CGameModule::vEvents[2] = {EV_EDIT, EV_GAME_NODE_DRAWN}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); + m_bApproximating = true; evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 40a6327..7c58e11 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,222 +1,228 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" #include <tr1/memory> namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::tr1::shared_ptr<CWordGeneratorBase> pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ std::tr1::shared_ptr<CWordGeneratorBase> m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; + /** + * Flag that denotes whether we are approximating the target position + * or not. + */ + bool m_bApproximating; + /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ static const int vEvents[2]; }; } #endif
rgee/HFOSS-Dasher
5bf7f21a95f2e1657d015ec65ab1879094399e28
Added node types to each Dasher Node. Now we can perform conditional functionality without doing strange things like calling a search function on an element of the data structure you're searching.
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index 92e46c3..12ca4e4 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,463 +1,489 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } -CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) -: CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pProbInfo(NULL), m_pMgr(pMgr) { +CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iType, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) +: CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, iType), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol _iSymbol) -: CAlphNode(pParent, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { +: CAlphNode(pParent, NT_SYMBOL, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol) -: CAlphNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { +: CAlphNode(pParent, NT_SYMBOL, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup) -: CAlphNode(pParent, iOffset, iLbnd, iHbnd, +: CAlphNode(pParent, NT_GROUP, iOffset, iLbnd, iHbnd, pGroup ? (pGroup->bVisible ? pGroup->iColour : pParent->getColour()) : pMgr->m_pNCManager->GetAlphabet()->GetColour(0, iOffset%2), pGroup ? pGroup->strLabel : "", pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { return new CSymbolNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup) { return new CGroupNode(pParent, iOffset, iLbnd, iHbnd, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pNewNode = makeGroup(pParent, iNewOffset, iLower, iUpper, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pNewNode = makeSymbol(pParent, iNewOffset, iLower, iUpper, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->iContext = iContext; return pNewNode; } bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { SetFlag(NF_GAME, true); return true; } return false; } +bool CAlphabetManager::CSymbolNode::IsTarget(string strTargetUtf8Char) { + return m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char; +} + +/* +bool CAlphabetManager::CSymbolNode::GameSearchBounds(string strTargetUtf8Char) { + int targetSymbol = m_pMgr->m_pNCManager->GetAlphabet()->GetSymbol(strTargetUtf8Char); + + if( (targetSymbol == iSymbol - 1) || + (targetSymbol == iSymbol + 1)) { + + } +} +*/ + bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { if (GameSearchChildren(strTargetUtf8Char)) { SetFlag(NF_GAME, true); return true; } return false; } +/* +bool CAlphabetManager::CGroupNode::GameSearchBounds(string strTargetUtf8Char) { + if (GameSearchChildBounds(strTargetUtf8Char)) { + return true; + } + return false; +} +*/ + + + CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->offset() == offset()); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // When creating a group node... // ...the offset is the same as the parent... CGroupNode *pNewNode = makeGroup(pParent, pParent->offset(), iLbnd, iHbnd, pInfo); //...as is the context! pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (offset() == pParent->offset()); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); } else { // TODO: Exceptions / error handling in general CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, pParent->offset()+1, iLbnd, iHbnd, iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(offset() == pParent->offset() + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); //loop for eliding groups with single children (see below). // Variables store necessary properties of any elided groups: std::string groupPrefix=""; int iOverrideColour=-1; SGroupInfo *pInner=pCurrentNode; while (true) { if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop break; //exit inner (group elision) loop } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); i = pInner->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) // (maybe not of pCurrentNode now, which might be a subgroup filling the original) break; //exit inner (group elision) loop } //were about to create a group node, which would have only one child // (eventually, if the group node were PopulateChildren'd). // Such a child would entirely fill it's parent (the group), and thus, // creation/destruction of the child would cause the node's colour to flash // between that for parent group and child. // Hence, instead we elide the group node and create the child _here_... //1. however we also have to take account of the appearance of the elided group. Hence: groupPrefix += pInner->strLabel; if (pInner->bVisible) iOverrideColour=pInner->iColour; //2. now go into the group... pInner = pInner->pChild; bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok //3. loop round inner loop... } //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); //now adjust the node we've actually created, to take account of any elided group(s)... // tho not if we've reused the existing node, assume that's been adjusted already if (pNewChild && pNewChild!=buildAround) pNewChild->PrependElidedGroup(iOverrideColour, groupPrefix); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(offset()); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(offset()-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/AlphabetManager.h b/Src/DasherCore/AlphabetManager.h index 89184f7..3c6c77b 100644 --- a/Src/DasherCore/AlphabetManager.h +++ b/Src/DasherCore/AlphabetManager.h @@ -1,171 +1,172 @@ // AlphabetManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __alphabetmanager_h__ #define __alphabetmanager_h__ #include "LanguageModelling/LanguageModel.h" #include "DasherNode.h" #include "Parameters.h" #include "NodeManager.h" class CNodeCreationManager; struct SGroupInfo; namespace Dasher { class CDasherInterfaceBase; /// \ingroup Model /// @{ /// Implementation of CNodeManager for regular 'alphabet' nodes, ie /// the basic Dasher behaviour. Child nodes are populated according /// to the appropriate alphabet file, with sizes given by the /// language model. /// class CAlphabetManager : public CNodeManager { public: CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel); - protected: + class CGroupNode; class CAlphNode : public CDasherNode { public: virtual CAlphabetManager *mgr() {return m_pMgr;} - CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr); + CAlphNode(CDasherNode *pParent, int iType, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr); CLanguageModel::Context iContext; /// /// Delete any storage alocated for this node /// virtual ~CAlphNode(); virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel); CDasherNode *RebuildParent(int iNewOffset); ///Have to call this from CAlphabetManager, and from CGroupNode on a _different_ CAlphNode, hence public... virtual std::vector<unsigned int> *GetProbInfo(); virtual int ExpectedNumChildren(); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd)=0; virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd)=0; private: std::vector<unsigned int> *m_pProbInfo; protected: CAlphabetManager *m_pMgr; }; class CSymbolNode : public CAlphNode { public: ///Standard constructor, gets colour+label by looking up symbol in current alphabet (& computing phase from offset) CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol iSymbol); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual CDasherNode *RebuildParent(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization); virtual void Undo(int *pNumDeleted); virtual void SetFlag(int iFlag, bool bValue); /** * Checks whether this node represents the target string. * In the case of group nodes, this function checks this node's * children, which are symbol nodes. * @param strTargetUtf8Char The string to compare to. * @return True if this node represents the target string. False * otherwise. */ virtual bool GameSearchNode(std::string strTargetUtf8Char); + virtual bool IsTarget(std::string strTargetUTf8Char); virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); virtual symbol GetAlphSymbol(); const symbol iSymbol; virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); private: virtual const std::string &outputText(); protected: ///Compatibility constructor, so that subclasses can specify their own colour & label CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol); }; class CGroupNode : public CAlphNode { public: CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup); /// /// Provide children for the supplied node /// virtual CDasherNode *RebuildParent(); virtual void PopulateChildren(); virtual int ExpectedNumChildren(); /** * Checks whether this node represents the target string. * In the case of group nodes, this function checks this node's * children, which are symbol nodes. * @param strTargetUtf8Char The string to compare to. * @return True if this node represents the target string. False * otherwise. */ virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); std::vector<unsigned int> *GetProbInfo(); private: SGroupInfo *m_pGroup; }; public: /// /// Get a new root node owned by this manager /// bEnteredLast - true if this "root" node should be considered as entering the preceding symbol /// Offset is the index of the character which _child_ nodes (i.e. between which this root allows selection) /// will enter. (Also used to build context for preceding characters.) virtual CAlphNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset); protected: /// /// Factory method for CAlphNode construction, so subclasses can override. /// virtual CSymbolNode *makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol); virtual CGroupNode *makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup); virtual CDasherNode *CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CLanguageModel::Context CreateSymbolContext(CAlphNode *pParent, symbol iSymbol); virtual CGroupNode *CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); CLanguageModel *m_pLanguageModel; CNodeCreationManager *m_pNCManager; private: void IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround); CLanguageModel::Context m_iLearnContext; CDasherInterfaceBase *m_pInterface; }; /// @} } #endif diff --git a/Src/DasherCore/ControlManager.cpp b/Src/DasherCore/ControlManager.cpp index da580f9..47e8667 100644 --- a/Src/DasherCore/ControlManager.cpp +++ b/Src/DasherCore/ControlManager.cpp @@ -1,372 +1,372 @@ // ControlManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "ControlManager.h" #include <cstring> using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif int CControlManager::m_iNextID = 0; CControlManager::CControlManager( CNodeCreationManager *pNCManager ) : m_pNCManager(pNCManager) { string SystemString = m_pNCManager->GetStringParameter(SP_SYSTEM_LOC); string UserLocation = m_pNCManager->GetStringParameter(SP_USER_LOC); m_iNextID = 0; // TODO: Need to fix this on WinCE build #ifndef _WIN32_WCE struct stat sFileInfo; string strFileName = UserLocation + "controllabels.xml"; // check first location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // something went wrong strFileName = SystemString + "controllabels.xml"; // check second location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // all else fails do something default LoadDefaultLabels(); } else - LoadLabelsFromFile(strFileName, sFileInfo.st_size); + LoadLabelsFromFile(strFileName, sFileInfo.st_size); } else LoadLabelsFromFile(strFileName, sFileInfo.st_size); ConnectNodes(); #endif } int CControlManager::LoadLabelsFromFile(string strFileName, int iFileSize) { // Implement Unicode names via xml from file: char* szFileBuffer = new char[iFileSize]; ifstream oFile(strFileName.c_str()); oFile.read(szFileBuffer, iFileSize); XML_Parser Parser = XML_ParserCreate(NULL); // Members passed as callbacks must be static, so don't have a "this" pointer. // We give them one through horrible casting so they can effect changes. XML_SetUserData(Parser, this); XML_SetElementHandler(Parser, XmlStartHandler, XmlEndHandler); XML_SetCharacterDataHandler(Parser, XmlCDataHandler); XML_Parse(Parser, szFileBuffer, iFileSize, false); // deallocate resources XML_ParserFree(Parser); oFile.close(); delete [] szFileBuffer; return 0; } int CControlManager::LoadDefaultLabels() { // TODO: Need to figure out how to handle offset changes here RegisterNode(CTL_ROOT, "Control", 8); RegisterNode(CTL_STOP, "Stop", 242); RegisterNode(CTL_PAUSE, "Pause", 241); RegisterNode(CTL_MOVE, "Move", -1); RegisterNode(CTL_MOVE_FORWARD, "->", -1); RegisterNode(CTL_MOVE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_MOVE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_MOVE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_MOVE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_MOVE_BACKWARD, "<-", -1); RegisterNode(CTL_MOVE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_MOVE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_MOVE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_MOVE_BACKWARD_FILE, "<<<<", -1); RegisterNode(CTL_DELETE, "Delete", -1); RegisterNode(CTL_DELETE_FORWARD, "->", -1); RegisterNode(CTL_DELETE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_DELETE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_DELETE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_DELETE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_DELETE_BACKWARD, "<-", -1); RegisterNode(CTL_DELETE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_DELETE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_DELETE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_DELETE_BACKWARD_FILE, "<<<<", -1); return 0; } int CControlManager::ConnectNodes() { ConnectNode(-1, CTL_ROOT, -2); ConnectNode(CTL_STOP, CTL_ROOT, -2); ConnectNode(CTL_PAUSE, CTL_ROOT, -2); ConnectNode(CTL_MOVE, CTL_ROOT, -2); ConnectNode(CTL_DELETE, CTL_ROOT, -2); ConnectNode(-1, CTL_STOP, -2); ConnectNode(CTL_ROOT, CTL_STOP, -2); ConnectNode(-1, CTL_PAUSE, -2); ConnectNode(CTL_ROOT, CTL_PAUSE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_LINE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_FILE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD_CHAR, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_FILE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_LINE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_FILE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD_CHAR, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_FILE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_FILE, -2); return 0; } CControlManager::~CControlManager() { for(std::map<int,SControlItem*>::iterator i = m_mapControlMap.begin(); i != m_mapControlMap.end(); i++) { SControlItem* pNewNode = i->second; if (pNewNode != NULL) { delete pNewNode; pNewNode = NULL; } } } void CControlManager::RegisterNode( int iID, std::string strLabel, int iColour ) { SControlItem *pNewNode; pNewNode = new SControlItem; // FIXME - do constructor sanely pNewNode->strLabel = strLabel; pNewNode->iID = iID; pNewNode->iColour = iColour; m_mapControlMap[iID] = pNewNode; } void CControlManager::ConnectNode(int iChild, int iParent, int iAfter) { // FIXME - iAfter currently ignored (eventually -1 = start, -2 = end) if( iChild == -1 ) {// Corresponds to escaping back to alphabet SControlItem* node = m_mapControlMap[iParent]; if(node) node->vChildren.push_back(NULL); } else m_mapControlMap[iParent]->vChildren.push_back(m_mapControlMap[iChild]); } void CControlManager::DisconnectNode(int iChild, int iParent) { SControlItem* pParentNode = m_mapControlMap[iParent]; SControlItem* pChildNode = m_mapControlMap[iChild]; for(std::vector<SControlItem *>::iterator itChild(pParentNode->vChildren.begin()); itChild != pParentNode->vChildren.end(); ++itChild) if(*itChild == pChildNode) pParentNode->vChildren.erase(itChild); } CDasherNode *CControlManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { CContNode *pNewNode = new CContNode(pParent, iOffset, iLower, iUpper, m_mapControlMap[0], this); // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); return pNewNode; } CControlManager::CContNode::CContNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, const SControlItem *pControlItem, CControlManager *pMgr) -: CDasherNode(pParent, iOffset, iLbnd, iHbnd, (pControlItem->iColour != -1) ? pControlItem->iColour : (pParent->ChildCount()%99)+11, pControlItem->strLabel), m_pControlItem(pControlItem), m_pMgr(pMgr) { +: CDasherNode(pParent, iOffset, iLbnd, iHbnd, (pControlItem->iColour != -1) ? pControlItem->iColour : (pParent->ChildCount()%99)+11, pControlItem->strLabel, NT_CONTROL), m_pControlItem(pControlItem), m_pMgr(pMgr) { } void CControlManager::CContNode::PopulateChildren() { CDasherNode *pNewNode; const unsigned int iNChildren( m_pControlItem->vChildren.size() ); const unsigned int iNorm(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); unsigned int iLbnd(0), iIdx(0); for(std::vector<SControlItem *>::const_iterator it(m_pControlItem->vChildren.begin()); it != m_pControlItem->vChildren.end(); ++it) { const unsigned int iHbnd((++iIdx*iNorm)/iNChildren); if( *it == NULL ) { // Escape back to alphabet pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, offset()); } else { pNewNode = new CContNode(this, offset(), iLbnd, iHbnd, *it, m_pMgr); } iLbnd=iHbnd; DASHER_ASSERT(GetChildren().back()==pNewNode); } } int CControlManager::CContNode::ExpectedNumChildren() { return m_pControlItem->vChildren.size(); } void CControlManager::CContNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ) { CControlEvent oEvent(m_pControlItem->iID); // TODO: Need to reimplement this // m_pNCManager->m_bContextSensitive=false; m_pMgr->m_pNCManager->InsertEvent(&oEvent); } void CControlManager::CContNode::Enter() { // Slow down to half the speed we were at m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 50); //Disable auto speed control! m_pMgr->bDisabledSpeedControl = m_pMgr->m_pNCManager->GetBoolParameter(BP_AUTO_SPEEDCONTROL); m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 0); } void CControlManager::CContNode::Leave() { // Now speed back up, by doubling the speed we were at in control mode m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 100); //Re-enable auto speed control! if (m_pMgr->bDisabledSpeedControl) { m_pMgr->bDisabledSpeedControl = false; m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 1); } } void CControlManager::XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr) { int colour=-1; string str; if(0==strcmp(szName, "label")) { for(int i = 0; aszAttr[i]; i += 2) { if(0==strcmp(aszAttr[i],"value")) { str = string(aszAttr[i+1]); } if(0==strcmp(aszAttr[i],"color")) { colour = atoi(aszAttr[i+1]); } } - ((CControlManager*)pUserData)->RegisterNode(CControlManager::m_iNextID++, str, colour); + ((CControlManager*)pUserData)->RegisterNode(CControlManager::m_iNextID++, str, colour); } } void CControlManager::XmlEndHandler(void *pUserData, const XML_Char *szName) { return; } void CControlManager::XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength){ return; } diff --git a/Src/DasherCore/ControlManager.h b/Src/DasherCore/ControlManager.h index 377f94c..fb7ec9b 100644 --- a/Src/DasherCore/ControlManager.h +++ b/Src/DasherCore/ControlManager.h @@ -1,134 +1,134 @@ // ControlManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __controlmanager_h__ #define __controlmanager_h__ #include "DasherModel.h" #include "DasherNode.h" #include "Event.h" #include "NodeManager.h" #include <vector> #include <map> #include <fstream> #include <iostream> #ifndef _WIN32_WCE #include <sys/stat.h> #endif #include <string> #include <expat.h> using namespace std; namespace Dasher { class CDasherModel; /// \ingroup Model /// @{ /// A node manager which deals with control nodes. /// Currently can only have one instance due to use /// of static members for callbacks from expat. /// class CControlManager : public CNodeManager { public: enum { CTL_ROOT, CTL_STOP, CTL_PAUSE, CTL_MOVE, CTL_MOVE_FORWARD, - CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD_LINE, - CTL_MOVE_FORWARD_FILE, CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, - CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD_FILE, - CTL_DELETE, CTL_DELETE_FORWARD, - CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD_LINE, - CTL_DELETE_FORWARD_FILE, CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, - CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD_FILE, - CTL_USER + CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD_LINE, + CTL_MOVE_FORWARD_FILE, CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, + CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD_FILE, + CTL_DELETE, CTL_DELETE_FORWARD, + CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD_LINE, + CTL_DELETE_FORWARD_FILE, CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, + CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD_FILE, + CTL_USER }; CControlManager(CNodeCreationManager *pNCManager); ~CControlManager(); /// /// Get a new root node owned by this manager /// virtual CDasherNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset); void RegisterNode( int iID, std::string strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); private: struct SControlItem { std::vector<SControlItem *> vChildren; std::string strLabel; int iID; int iColour; }; class CContNode : public CDasherNode { public: CControlManager *mgr() {return m_pMgr;} CContNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, const SControlItem *pControlItem, CControlManager *pMgr); bool bShove() {return false;} /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual int ExpectedNumChildren(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ); virtual void Enter(); virtual void Leave(); const SControlItem *m_pControlItem; private: CControlManager *m_pMgr; }; static void XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr); static void XmlEndHandler(void *pUserData, const XML_Char *szName); static void XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength); int LoadLabelsFromFile(string strFileName, int iFileSize); int LoadDefaultLabels(); int ConnectNodes(); static int m_iNextID; CNodeCreationManager *m_pNCManager; std::map<int,SControlItem*> m_mapControlMap; ///Whether we'd temporarily disabled Automatic Speed Control ///(if _and only if_ so, should re-enable it when leaving a node) bool bDisabledSpeedControl; }; /// @} } #endif diff --git a/Src/DasherCore/ConversionManager.cpp b/Src/DasherCore/ConversionManager.cpp index b71fef6..62f2906 100644 --- a/Src/DasherCore/ConversionManager.cpp +++ b/Src/DasherCore/ConversionManager.cpp @@ -1,195 +1,195 @@ // ConversionManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "ConversionManager.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include "DasherModel.h" #include <iostream> #include <cstring> #include <string> #include <vector> #include <stdlib.h> //Note the new implementation in Mandarin Dasher may not be compatible with the previous implementation of Japanese Dasher //Need to reconcile (a small project) using namespace Dasher; using namespace std; CConversionManager::CConversionManager(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet) { m_pNCManager = pNCManager; m_pAlphabet = pAlphabet; m_iRefCount = 1; //Testing for alphabet details, delete if needed: /* int alphSize = pNCManager->GetAlphabet()->GetNumberSymbols(); std::cout<<"Alphabet size: "<<alphSize<<std::endl; for(int i =0; i<alphSize; i++) std::cout<<"symbol: "<<i<<" display text:"<<pNCManager->GetAlphabet()->GetDisplayText(i)<<std::endl; */ } CConversionManager::CConvNode *CConversionManager::makeNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText) { return new CConvNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, this); } CConversionManager::CConvNode *CConversionManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { // TODO: Parameters here are placeholders - need to figure out what's right //TODO: hard-coded colour, and hard-coded displaytext... (ACL: read from Alphabet -> startConversionSymbol ?) CConvNode *pNewNode = makeNode(pParent, iOffset, iLower, iUpper, 9, ""); // FIXME - handle context properly // TODO: Reimplemnt ----- // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->bisRoot = true; pNewNode->pLanguageModel = NULL; pNewNode->pSCENode = 0; return pNewNode; } CConversionManager::CConvNode::CConvNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CConversionManager *pMgr) - : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pMgr(pMgr) { + : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, NT_CONV), m_pMgr(pMgr) { pMgr->m_iRefCount++; } void CConversionManager::CConvNode::PopulateChildren() { DASHER_ASSERT(m_pMgr->m_pNCManager); // If no helper class is present then just drop straight back to an // alphabet root. This should only happen in error cases, and the // user should have been warned here. // unsigned int iLbnd(0); unsigned int iHbnd(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); CDasherNode *pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, offset() + 1); DASHER_ASSERT(GetChildren().back()==pNewNode); } int CConversionManager::CConvNode::ExpectedNumChildren() { return 1; //the alphabet root } CConversionManager::CConvNode::~CConvNode() { pLanguageModel->ReleaseContext(iContext); m_pMgr->Unref(); } void CConversionManager::RecursiveDumpTree(SCENode *pCurrent, unsigned int iDepth) { const std::vector<SCENode *> &children = pCurrent->GetChildren(); for (std::vector<SCENode *>::const_iterator it = children.begin(); it!=children.end(); it++) { SCENode *pCurrent(*it); for(unsigned int i(0); i < iDepth; ++i) std::cout << "-"; std::cout << " " << pCurrent->pszConversion << std::endl;//" " << pCurrent->IsHeadAndCandNum << " " << pCurrent->CandIndex << " " << pCurrent->IsComplete << " " << pCurrent->AcCharCount << std::endl; RecursiveDumpTree(pCurrent, iDepth + 1); } } void CConversionManager::CConvNode::GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { //ACL I'm extrapolating from PinYinConversionHelper (in which root nodes have their // Symbol set by SetConvSymbol, and child nodes are created in PopulateChildren // from SCENode's with Symbols having been set in in AssignSizes); not really sure // whether this is applicable in the general case(! - but although I think it's right // for PinYin, it wouldn't actually be used there, as MandarinDasher overrides contexts // everywhere!) DASHER_ASSERT(bisRoot || pSCENode); if (bisRoot || pSCENode->Symbol!=-1) { if (iLength>1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(bisRoot ? iSymbol : pSCENode->Symbol); return; } //else, non-root with pSCENode->Symbol==-1 => fallthrough back to superclass code } CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } void CConversionManager::CConvNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { // TODO: Reimplement this // m_pNCManager->m_bContextSensitive = true; SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode){ Dasher::CEditEvent oEvent(1, pCurrentSCENode->pszConversion, offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if((GetChildren())[0]->mgr() == m_pMgr) { if (static_cast<CConvNode *>(GetChildren()[0])->m_pMgr == m_pMgr) { Dasher::CEditEvent oEvent(11, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } } else { if(!bisRoot) { Dasher::CEditEvent oOPEvent(1, "|", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { Dasher::CEditEvent oOPEvent(1, ">", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } Dasher::CEditEvent oEvent(10, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } void CConversionManager::CConvNode::Undo(int *pNumDeleted) { //ACL note: possibly ought to update pNumDeleted here if non-null, // but conversion symbols were not logged by old code so am not starting now! SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode) { if(pCurrentSCENode->pszConversion && (strlen(pCurrentSCENode->pszConversion) > 0)) { Dasher::CEditEvent oEvent(2, pCurrentSCENode->pszConversion, offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } else { if(!bisRoot) { Dasher::CEditEvent oOPEvent(2, "|", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { Dasher::CEditEvent oOPEvent(2, ">", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } } } diff --git a/Src/DasherCore/DasherNode.cpp b/Src/DasherCore/DasherNode.cpp index 0fb1ab6..40c128d 100644 --- a/Src/DasherCore/DasherNode.cpp +++ b/Src/DasherCore/DasherNode.cpp @@ -1,206 +1,207 @@ // DasherNode.cpp // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" // #include "AlphabetManager.h" - doesnt seem to be required - pconlon #include "DasherInterfaceBase.h" using namespace Dasher; using namespace Opts; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif static int iNumNodes = 0; int Dasher::currentNumNodeObjects() {return iNumNodes;} //TODO this used to be inline - should we make it so again? -CDasherNode::CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText) -: m_pParent(pParent), m_iOffset(iOffset), m_iLbnd(iLbnd), m_iHbnd(iHbnd), m_iColour(iColour), m_strDisplayText(strDisplayText) { +CDasherNode::CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, int iType) +: m_pParent(pParent), m_iOffset(iOffset), m_iLbnd(iLbnd), m_iHbnd(iHbnd), m_iColour(iColour), m_strDisplayText(strDisplayText), m_iType(iType) { DASHER_ASSERT(iHbnd >= iLbnd); - + if (pParent) { DASHER_ASSERT(!pParent->GetFlag(NF_ALLCHILDREN)); pParent->Children().push_back(this); } onlyChildRendered = NULL; - + // Default flags (make a definition somewhere, pass flags to constructor?) m_iFlags = 0; - + m_iRefCount = 0; iNumNodes++; } // TODO: put this back to being inlined CDasherNode::~CDasherNode() { // std::cout << "Deleting node: " << this << std::endl; // Release any storage that the node manager has allocated, // unreference ref counted stuff etc. Delete_children(); // std::cout << "done." << std::endl; iNumNodes--; } void CDasherNode::PrependElidedGroup(int iGroupColour, string &strGroupLabel) { if (m_iColour==-1) m_iColour = iGroupColour; m_strDisplayText = strGroupLabel + m_strDisplayText; } void CDasherNode::Trace() const { /* TODO sort out dchar out[256]; if (m_Symbol) wsprintf(out,TEXT("%7x %3c %7x %5d %7x %5d %8x %8x \n"),this,m_Symbol,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); else wsprintf(out,TEXT("%7x %7x %5d %7x %5d %8x %8x \n"),this,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); OutputDebugString(out); if (m_Children) { unsigned int i; for (i=1;i<m_iChars;i++) m_Children[i]->Dump_node(); } */ } void CDasherNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN)) { DASHER_ASSERT(m_pParent); if (m_pParent) m_pParent->GetContext(pInterface, vContextSymbols, iOffset,iLength); } else { std::string strContext = pInterface->GetContext(iOffset, iLength); pInterface->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } } CDasherNode *const CDasherNode::Get_node_under(int iNormalization, myint miY1, myint miY2, myint miMousex, myint miMousey) { myint miRange = miY2 - miY1; ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { CDasherNode *pChild = *i; myint miNewy1 = miY1 + (miRange * pChild->m_iLbnd) / iNormalization; myint miNewy2 = miY1 + (miRange * pChild->m_iHbnd) / iNormalization; if(miMousey < miNewy2 && miMousey > miNewy1 && miMousex < miNewy2 - miNewy1) return pChild->Get_node_under(iNormalization, miNewy1, miNewy2, miMousex, miMousey); } return this; } // kill ourselves and all other children except for the specified // child // FIXME this probably shouldn't be called after history stuff is working void CDasherNode::OrphanChild(CDasherNode *pChild) { DASHER_ASSERT(ChildCount() > 0); ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { if((*i) != pChild) { (*i)->Delete_children(); delete (*i); } } pChild->m_pParent=NULL; Children().clear(); SetFlag(NF_ALLCHILDREN, false); } // Delete nephews of the child which has the specified symbol // TODO: Need to allow for subnode void CDasherNode::DeleteNephews(CDasherNode *pChild) { DASHER_ASSERT(Children().size() > 0); ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { if(*i != pChild) { - (*i)->Delete_children(); + (*i)->Delete_children(); } } } // TODO: Need to allow for subnodes // TODO: Incorporate into above routine void CDasherNode::Delete_children() { // std::cout << "Start: " << this << std::endl; ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { // std::cout << "CNM: " << (*i)->MgrID() << (*i) << " " << (*i)->Parent() << std::endl; delete (*i); } Children().clear(); // std::cout << "NM: " << MgrID() << std::endl; SetFlag(NF_ALLCHILDREN, false); } void CDasherNode::SetFlag(int iFlag, bool bValue) { if(bValue) m_iFlags = m_iFlags | iFlag; else m_iFlags = m_iFlags & (~iFlag); } void CDasherNode::SetParent(CDasherNode *pNewParent) { DASHER_ASSERT(pNewParent); DASHER_ASSERT(!pNewParent->GetFlag(NF_ALLCHILDREN)); m_pParent = pNewParent; pNewParent->Children().push_back(this); } int CDasherNode::MostProbableChild() { int iMax(0); int iCurrent; for(ChildMap::iterator it(m_mChildren.begin()); it != m_mChildren.end(); ++it) { iCurrent = (*it)->Range(); if(iCurrent > iMax) iMax = iCurrent; } return iMax; } bool CDasherNode::GameSearchChildren(string strTargetUtf8Char) { for (ChildMap::iterator i = Children().begin(); i != Children().end(); i++) { if ((*i)->GameSearchNode(strTargetUtf8Char)) return true; } + return false; } diff --git a/Src/DasherCore/DasherNode.h b/Src/DasherCore/DasherNode.h index b700500..445063e 100644 --- a/Src/DasherCore/DasherNode.h +++ b/Src/DasherCore/DasherNode.h @@ -1,346 +1,357 @@ // DasherNode.h // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherNode_h__ #define __DasherNode_h__ #include "../Common/Common.h" #include "../Common/NoClones.h" #include "LanguageModelling/LanguageModel.h" #include "DasherTypes.h" #include "NodeManager.h" namespace Dasher { class CDasherNode; class CDasherInterfaceBase; }; #include <deque> #include <iostream> #include <vector> // Node flag constants #define NF_COMMITTED 1 #define NF_SEEN 2 #define NF_CONVERTED 4 #define NF_GAME 8 #define NF_ALLCHILDREN 16 #define NF_SUPER 32 #define NF_END_GAME 64 + +// Node types. One for each type of node. +enum { + NT_GROUP = 1, NT_SYMBOL, NT_CONTROL, NT_CONV, NT_CONVROOT +}; + + /// \ingroup Model /// @{ /// @brief A node in the Dasher model /// /// The Dasher node represents a box drawn on the display. This class /// contains the information required to render the node, as well as /// navigation within the model (parents and children /// etc.). Additional information is stored in m_pUserData, which is /// interpreted by the node manager associated with this class. Any /// logic specific to a particular node manager should be stored here. /// /// @todo Encapsulate presentation data in a structure? /// @todo Check that all methods respect the pseudochild attribute class Dasher::CDasherNode:private NoClones { public: + inline int GetType() const { return m_iType; } /// Display attributes of this node, used for rendering. /// Colour: -1 for invisible inline int getColour() {return m_iColour;} inline std::string &getDisplayText() {return m_strDisplayText;} ///Whether labels on child nodes should be displaced to the right of this node's label. /// (Default implementation returns true, subclasses should override if appropriate) virtual bool bShove() {return true;} inline int offset() {return m_iOffset;} CDasherNode *onlyChildRendered; //cache that only one child was rendered (as it filled the screen) /// Container type for storing children. Note that it's worth /// optimising this as lookup happens a lot typedef std::deque<CDasherNode*> ChildMap; /// @brief Constructor /// /// @param pParent Parent of the new node /// @param iLbnd Lower bound of node within parent /// @param iHbnd Upper bound of node within parent /// @param pDisplayInfo Struct containing information on how to display the node /// - CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText); + CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, int iType); /// @brief Destructor /// virtual ~CDasherNode(); /// Adjusts the colour & label of this node to look as it would if it /// were the sole child of another node with the specified colour and label /// (without actually making the other/group node) void PrependElidedGroup(int iGroupColour, std::string &strGroupLabel); void Trace() const; // diagnostic /// @name Routines for manipulating node status /// @{ /// @brief Set a node flag /// /// Set various flags corresponding to the state of the node. The following flags are defined: /// /// NF_COMMITTED - Node is 'above' the root, so corresponding symbol /// has been added to text box, language model trained etc /// /// NF_SEEN - Node has already been output /// /// NF_CONVERTED - Node has been converted (eg Japanese mode) /// /// NF_GAME - Node is on the path in game mode /// /// NF_ALLCHILDREN - Node has all children (TODO: obsolete?) /// /// NF_SUPER - Node covers entire visible area /// /// NF_END_GAME - Node is the last one of the phrase in game mode /// /// /// @param iFlag The flag to set /// @param bValue The new value of the flag /// virtual void SetFlag(int iFlag, bool bValue); /// @brief Get the value of a flag for this node /// /// @param iFlag The flag to get /// /// @return The current value of the flag /// inline bool GetFlag(int iFlag) const; /// @} /// @name Routines relating to the size of the node /// @{ // Lower and higher bounds, and the range /// @brief Get the lower bound of a node /// /// @return The lower bound /// inline unsigned int Lbnd() const; /// @brief Get the upper bound of a node /// /// @return The upper bound /// inline unsigned int Hbnd() const; /// @brief Get the range of a node (upper - lower bound) /// /// @return The range /// /// @todo Should this be here (trivial arithmethic of existing methods) /// inline unsigned int Range() const; /// @brief Reset the range of a node /// /// @param iLower New lower bound /// @param iUpper New upper bound /// inline void SetRange(unsigned int iLower, unsigned int iUpper); /// @brief Get the size of the most probable child /// /// @return The size /// int MostProbableChild(); /// @} /// @name Routines for manipulating relatives /// @{ inline const ChildMap & GetChildren() const; inline unsigned int ChildCount() const; inline CDasherNode *Parent() const; void SetParent(CDasherNode *pNewParent); // TODO: Should this be here? CDasherNode *const Get_node_under(int, myint y1, myint y2, myint smousex, myint smousey); // find node under given co-ords /// @brief Orphan a child of this node /// /// Deletes all other children, and the node itself /// /// @param pChild The child to keep /// void OrphanChild(CDasherNode * pChild); /// @brief Delete the nephews of a given child /// /// @param pChild The child to keep /// void DeleteNephews(CDasherNode *pChild); /// @brief Delete the children of this node /// /// void Delete_children(); /// @} /// /// Sees if a *child* / descendant of the specified node (not that node itself) /// represents the specified character. If so, set the child & intervening nodes' /// NF_GAME flag, and return true; otherwise, return false. /// bool GameSearchChildren(std::string strTargetUtf8Char); /// @name Management routines (once accessed via NodeManager) /// @{ /// Gets the node manager for this object. Meaning defined by subclasses, /// which should override and refine the return type appropriately; /// the main use is to provide runtime type info to check casting! virtual CNodeManager *mgr() = 0; /// /// Provide children for the supplied node /// virtual void PopulateChildren() = 0; /// The number of children which a call to PopulateChildren can be expected to generate. /// (This is not required to be 100% accurate, but any discrepancies will likely cause /// the node budgetting algorithm to behave sub-optimally) virtual int ExpectedNumChildren() = 0; /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) {}; virtual void Undo(int *pNumDeleted) {}; virtual void Enter() {}; virtual void Leave() {}; virtual CDasherNode *RebuildParent() { return 0; }; /// /// Get as many symbols of context, up to the _end_ of the specified range, /// as possible from this node and its uncommitted ancestors /// virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); /// ACL Not really sure why we should have to have this, but seems it's needed for something /// to do with speech on Linux. I'm preserving it for now (indeed, making it part of CDasherNode, /// rather than CControlManager::CContNode, where it should be - but that would require making /// m_iOffset visible), as hopefully all speech functionality will be redone shortly... void SetControlOffset(int iOffset) {m_iOffset = iOffset;}; /// /// See if this node represents the specified alphanumeric character; if so, set it's NF_GAME flag and /// return true; otherwise, return false. /// virtual bool GameSearchNode(std::string strTargetUtf8Char) {return false;} /// Clone the context of the specified node, if it's an alphabet node; /// else return an empty context. (Used by ConversionManager) virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel) { return pLanguageModel->CreateEmptyContext(); }; virtual symbol GetAlphSymbol() { throw "Hack for pre-MandarinDasher ConversionManager::BuildTree method, needs to access CAlphabetManager-private struct"; } /// @} private: inline ChildMap &Children(); unsigned int m_iLbnd; unsigned int m_iHbnd; // the cumulative lower and upper bound prob relative to parent int m_iRefCount; // reference count if ancestor of (or equal to) root node ChildMap m_mChildren; // pointer to array of children CDasherNode *m_pParent; // pointer to parent // Binary flags representing the state of the node int m_iFlags; int m_iOffset; + + // The type of this node. + int m_iType; protected: int m_iColour; std::string m_strDisplayText; }; /// @} namespace Dasher { /// Return the number of CDasherNode objects currently in existence. int currentNumNodeObjects(); } ///////////////////////////////////////////////////////////////////////////// // Inline functions ///////////////////////////////////////////////////////////////////////////// namespace Dasher { inline unsigned int CDasherNode::Lbnd() const { return m_iLbnd; } inline unsigned int CDasherNode::Hbnd() const { return m_iHbnd; } inline unsigned int CDasherNode::Range() const { return m_iHbnd - m_iLbnd; } inline CDasherNode::ChildMap &CDasherNode::Children() { return m_mChildren; } inline const CDasherNode::ChildMap &CDasherNode::GetChildren() const { return m_mChildren; } inline unsigned int CDasherNode::ChildCount() const { return m_mChildren.size(); } inline bool CDasherNode::GetFlag(int iFlag) const { return ((m_iFlags & iFlag) != 0); } inline CDasherNode *CDasherNode::Parent() const { return m_pParent; } inline void CDasherNode::SetRange(unsigned int iLower, unsigned int iUpper) { m_iLbnd = iLower; m_iHbnd = iUpper; } } #endif /* #ifndef __DasherNode_h__ */ diff --git a/Src/DasherCore/MandarinAlphMgr.cpp b/Src/DasherCore/MandarinAlphMgr.cpp index 7f186a8..e1f0044 100644 --- a/Src/DasherCore/MandarinAlphMgr.cpp +++ b/Src/DasherCore/MandarinAlphMgr.cpp @@ -1,303 +1,303 @@ // MandarinAlphMgr.cpp // // Copyright (c) 2009 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "MandarinAlphMgr.h" #include "LanguageModelling/PPMPYLanguageModel.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace std; using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CMandarinAlphMgr::CMandarinAlphMgr(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : CAlphabetManager(pInterface, pNCManager, pLanguageModel), m_pParser(new CPinyinParser(pInterface->GetStringParameter(SP_SYSTEM_LOC) +"/alphabet.chineseRuby.xml")), m_pCHAlphabet(new CAlphabet(pInterface->GetInfo("Chinese / 简体中文 (simplified chinese, in pin yin groups)"))) { } CMandarinAlphMgr::~CMandarinAlphMgr() { delete m_pParser; } CDasherNode *CMandarinAlphMgr::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if (iSymbol <= 1288) { //Will wrote: //Modified for Mandarin Dasher //The following logic switch allows punctuation nodes in Mandarin to be treated in the same way as English (i.e. display and populate next round) instead of invoking a conversion node //ACL I think by "the following logic switch" he meant that symbols <= 1288 are "normal" nodes, NOT punctuation nodes, // whereas punctuation is handled by the fallthrough case (standard AlphabetManager CreateSymbolNode) /*old code: * CDasherNode *pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); - * static_cast<CPinYinConversionHelper::CPYConvNode *>(pNewNode)->SetConvSymbol(iSymbol); - * return pNewNode; + * static_cast<CPinYinConversionHelper::CPYConvNode *>(pNewNode)->SetConvSymbol(iSymbol); + * return pNewNode; */ //CTrieNode parallels old PinyinConversionHelper's SetConvSymbol; we keep // the same offset as we've still not entered/selected a symbol (leaf) CConvRoot *pNewNode = new CConvRoot(pParent, pParent->offset(), iLbnd, iHbnd, this, m_pParser->GetTrieNode(m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol))); //from ConversionHelper: //pNewNode->m_pLanguageModel = m_pLanguageModel; pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); - return pNewNode; + return pNewNode; } return CAlphabetManager::CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CMandarinAlphMgr::CConvRoot::CConvRoot(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, CTrieNode *pTrie) -: CDasherNode(pParent, iOffset, iLbnd, iHbnd, 9, ""), m_pMgr(pMgr), m_pTrie(pTrie) { +: CDasherNode(pParent, iOffset, iLbnd, iHbnd, 9, "", NT_CONVROOT), m_pMgr(pMgr), m_pTrie(pTrie) { //colour + label from ConversionManager. } int CMandarinAlphMgr::CConvRoot::ExpectedNumChildren() { if (m_vChInfo.empty()) BuildConversions(); return m_vChInfo.size(); } void CMandarinAlphMgr::CConvRoot::BuildConversions() { if (!m_pTrie || !m_pTrie->list()) { //TODO some kind of fallback??? e.g. start new char? DASHER_ASSERT(false); return; } for(set<string>::iterator it = m_pTrie->list()->begin(); it != m_pTrie->list()->end(); ++it) { std::vector<symbol> vSyms; m_pMgr->m_pCHAlphabet->GetSymbols(vSyms, *it); DASHER_ASSERT(vSyms.size()==1); //does it ever happen? if so, Will's code would effectively push -1 DASHER_ASSERT(m_pMgr->m_pCHAlphabet->GetText(vSyms[0]) == *it); m_vChInfo.push_back(std::pair<symbol, unsigned int>(vSyms[0],0)); } //TODO would be nicer to do this only if we need the size info (i.e. PopulateChildren not ExpectedNumChildren) ? m_pMgr->AssignSizes(m_vChInfo, iContext); } void CMandarinAlphMgr::CConvRoot::PopulateChildren() { if (m_vChInfo.empty()) BuildConversions(); int iIdx(0); int iCum(0); // int parentClr = pNode->Colour(); // TODO: Fixme int parentClr = 0; // Finally loop through and create the children for (vector<pair<symbol, unsigned int> >::const_iterator it = m_vChInfo.begin(); it!=m_vChInfo.end(); it++) { // std::cout << "Current scec: " << pCurrentSCEChild << std::endl; unsigned int iLbnd(iCum); unsigned int iHbnd(iCum + it->second); iCum = iHbnd; // TODO: Parameters here are placeholders - need to figure out // what's right int iColour(m_vChInfo.size()==1 ? getColour() : m_pMgr->AssignColour(parentClr, iIdx)); // std::cout << "#" << pCurrentSCEChild->pszConversion << "#" << std::endl; CMandNode *pNewNode = new CMandSym(this, offset()+1, iLbnd, iHbnd, iColour, m_pMgr, it->first); // TODO: Reimplement ---- // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->iContext = m_pMgr->m_pLanguageModel->CloneContext(this->iContext); m_pMgr->m_pLanguageModel->EnterSymbol(iContext, it->first); // TODO: Don't use symbols? DASHER_ASSERT(GetChildren().back()==pNewNode); ++iIdx; } } void CMandarinAlphMgr::AssignSizes(std::vector<pair<symbol,unsigned int> > &vChildren, Dasher::CLanguageModel::Context context) { const uint64 iNorm(m_pNCManager->GetLongParameter(LP_NORMALIZATION)); const unsigned int uniform((m_pNCManager->GetLongParameter(LP_UNIFORM)*iNorm)/1000); int iRemaining(iNorm); uint64 sumProb=0; //CLanguageModel::Context iCurrentContext; // std::cout<<"size of symbolstore "<<SymbolStore.size()<<std::endl; // std::cout<<"norm input: "<<nonuniform_norm/(iSymbols/iNChildren/100)<<std::endl; //ACL pass in iNorm and uniform directly - GetPartProbs distributes the last param between // however elements there are in vChildren... static_cast<CPPMPYLanguageModel *>(m_pLanguageModel)->GetPartProbs(context, vChildren, iNorm, uniform); //std::cout<<"after get probs "<<std::endl; for (std::vector<pair<symbol,unsigned int> >::const_iterator it = vChildren.begin(); it!=vChildren.end(); it++) { sumProb += it->second; } // std::cout<<"Sum Prob "<<sumProb<<std::endl; // std::cout<<"norm "<<nonuniform_norm<<std::endl; //Match, sumProbs = nonuniform_norm //but fix one element 'Da4' // Finally, iterate through the nodes and actually assign the sizes. // std::cout<<"sumProb "<<sumProb<<std::endl; for (std::vector<pair<symbol,unsigned int> >::iterator it = vChildren.begin(); it!=vChildren.end(); it++) { DASHER_ASSERT(it->first>-1); //ACL Will's code tested for both these conditions explicitly, and if so DASHER_ASSERT(sumProb>0); //then used a probability of 0. I don't think either //should ever happen if the alphabet files are right (there'd have to //be either no conversions of the syllable+tone, or else the LM'd have //to assign zero probability to each), so I'm removing these tests for now... iRemaining -= it->second = (it->second*iNorm)/sumProb; if (it->second==0) { #ifdef DEBUG std::cout << "WARNING: Erasing zero-probability conversion with symbol " << it->first << std::endl; #endif vChildren.erase(it--); } // std::cout<<pNode->pszConversion<<std::endl; // std::cout<<pNode->Symbol<<std::endl; // std::cout<<"Probs i "<<pNode<<std::endl; // std::cout<<"Symbol i"<<SymbolStore[iIdx]<<std::endl; // std::cout<<"symbols size "<<SymbolStore.size()<<std::endl; // std::cout<<"Symbols address "<<&SymbolStore<<std::endl; } //std::cout<<"iRemaining "<<iRemaining<<std::endl; // Last of all, allocate anything left over due to rounding error int iLeft(vChildren.size()); for (std::vector<pair<symbol,unsigned int> >::iterator it = vChildren.begin(); it!=vChildren.end(); it++) { int iDiff(iRemaining / iLeft); it->second += iDiff; iRemaining -= iDiff; --iLeft; // std::cout<<"Node size for "<<pNode->pszConversion<<std::endl; //std::cout<<"is "<<pNode->NodeSize<<std::endl; } DASHER_ASSERT(iRemaining == 0); } static int colourStore[2][3] = { {66,//light blue 64,//very light green 62},//light yellow {78,//light purple 81,//brownish 60},//red }; //Pulled from CConversionHelper, where it's described as "needing a rethink"... int CMandarinAlphMgr::AssignColour(int parentClr, int childIndex) { int which = -1; for (int i=0; i<2; i++) for(int j=0; j<3; j++) if (parentClr == colourStore[i][j]) which = i; if(which == -1) return colourStore[0][childIndex%3]; else if(which == 0) return colourStore[1][childIndex%3]; else return colourStore[0][childIndex%3]; }; CLanguageModel::Context CMandarinAlphMgr::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { - //Context carry-over. This code may worth looking at debug - return m_pLanguageModel->CloneContext(pParent->iContext); + //Context carry-over. This code may worth looking at debug + return m_pLanguageModel->CloneContext(pParent->iContext); } CMandarinAlphMgr::CMandNode::CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, symbol iSymbol) : CSymbolNode(pParent, iOffset, iLbnd, iHbnd, pMgr, iSymbol) { } CMandarinAlphMgr::CMandNode::CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CMandarinAlphMgr *pMgr, symbol iSymbol) : CSymbolNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr, iSymbol) { } CMandarinAlphMgr::CMandNode *CMandarinAlphMgr::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { // Override standard symbol factory method, called by superclass, to make CMandNodes // - important only to disable learn-as-you-write... return new CMandNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } void CMandarinAlphMgr::CMandNode::SetFlag(int iFlag, bool bValue) { //``disable learn-as-you-write for Mandarin Dasher'' if (iFlag==NF_COMMITTED) CDasherNode::SetFlag(iFlag, bValue); //bypass CAlphNode setter! else CAlphNode::SetFlag(iFlag, bValue); } // For converted chinese symbols, we construct instead CMandSyms... CMandarinAlphMgr::CMandSym::CMandSym(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, CMandarinAlphMgr *pMgr, symbol iSymbol) : CMandNode(pParent, iOffset, iLbnd, iHbnd, iColour, pMgr->m_pCHAlphabet->GetText(iSymbol), pMgr, iSymbol) { //Note we passed a custom label into superclass constructor: // the chinese characters are in the _text_ (not label - that's e.g. "liang4") // of the alphabet (& the pszConversion from PinyinParser was converted to symbol // by CAlphabet::GetSymbols, which does string->symbol by _text_; we're reversing that) } const std::string &CMandarinAlphMgr::CMandSym::outputText() { //use chinese, not pinyin, alphabet... return mgr()->m_pCHAlphabet->GetText(iSymbol); }
rgee/HFOSS-Dasher
0ea12884a6f5fd9a4a97fecc6135b09678bc1076
Added reverse lookup to character alphabet
diff --git a/Src/DasherCore/Alphabet/Alphabet.h b/Src/DasherCore/Alphabet/Alphabet.h index ba31c45..5a44efb 100644 --- a/Src/DasherCore/Alphabet/Alphabet.h +++ b/Src/DasherCore/Alphabet/Alphabet.h @@ -1,224 +1,233 @@ // Alphabet.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DASHER_ALPHABET_H__ #define __DASHER_ALPHABET_H__ #include "AlphIO.h" #include "AlphabetMap.h" #include "../DasherTypes.h" #include "GroupInfo.h" #include <cstdlib> #include <iostream> +#include <algorithm> #include <vector> namespace Dasher { /// /// \defgroup Alphabet Alphabet information /// @{ class CAlphabet { public: CAlphabet(); CAlphabet(const CAlphIO::AlphInfo & AlphInfo); // Return size of alphabet, including control symbols int GetNumberSymbols() const { return m_Characters.size(); } // return size of alphabet /// Return number of text symbols /// Text symbols are everything which doesn't generate a new root, /// i.e. control mode and conversion mode int GetNumberTextSymbols() const { // TODO: This really does need to be fixed, as this will sometimes be 2 return m_Characters.size() - 1; } Opts::ScreenOrientations GetOrientation() { return m_Orientation; } Opts::AlphabetTypes GetType() { return m_DefaultEncoding; } const std::string & GetTrainingFile() const { return m_TrainingFile; } std::string GetGameModeFile() { return m_GameModeFile; } std::string & GetPalette() { return m_DefaultPalette; } symbol GetParagraphSymbol() const; symbol GetSpaceSymbol() const; symbol GetControlSymbol() const; symbol GetStartConversionSymbol() const; symbol GetEndConversionSymbol() const; const std::string & GetDisplayText(symbol i) const { return m_Display[i]; } // return display string for i'th symbol const std::string & GetText(symbol i) const { return m_Characters[i]; } // return string for i'th symbol + + /** + * Return the symbol id of the character with the specified text. + * Essentially a reverse lookup of GetText. + */ + const int GetSymbol(std::string & str) const { + return std::distance( std::find(m_Characters.begin(), m_Characters.end(), str), m_Characters.begin() ) - 1; + } int GetColour(symbol i, int iPhase) const; int GetTextColour(symbol i); // return the foreground colour for i'th symbol const std::string & GetForeground(symbol i) const { return m_Foreground[i]; } // return the foreground colour for i'th symbol /* int GetGroupCount() const { */ /* return m_iGroups; */ /* } int GetGroupStart(int i) const { */ /* return m_GroupStart[i]; */ /* } int GetGroupEnd(int i) const { */ /* return m_GroupEnd[i]; */ /* } */ //int get_group(symbol i) const {return m_Group[i];} // return group membership of i'th symbol class SymbolStream { public: SymbolStream(const CAlphabet *pAlph, std::istream &_in); symbol next(); private: void readMore(); const alphabet_map &map; char buf[1024]; int pos, len; std::istream &in; }; // Fills Symbols with the symbols corresponding to Input. {{{ Note that this // is not necessarily reversible by repeated use of GetText. Some text // may not be recognised and so discarded. }}} void GetSymbols(std::vector<symbol> &Symbols, const std::string &Input) const; //SymbolStream *GetSymbols(std::istream &in) const; void Trace() const; // diagnostic void SetOrientation(Opts::ScreenOrientations Orientation) { m_Orientation = Orientation; } void SetLanguage(Opts::AlphabetTypes Group) { m_DefaultEncoding = Group; } void SetTrainingFile(std::string TrainingFile) { m_TrainingFile = TrainingFile; } void SetGameModeFile(std::string GameModeFile) { m_GameModeFile = GameModeFile; } void SetPalette(std::string Palette) { m_DefaultPalette = Palette; } const std::string &GetDefaultContext() const { return m_strDefaultContext; } SGroupInfo *m_pBaseGroup; int iNumChildNodes; private: // Add the characters that can appear in Nodes void AddChar(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); // add single char to the alphabet // Alphabet language parameters void AddParagraphSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddSpaceSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddControlSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); void AddStartConversionSymbol(std::string NewCharacter, std::string Display , int Colour, std::string Foreground); void AddEndConversionSymbol(std::string NewCharacter, std::string Display, int Colour, std::string Foreground); Opts::AlphabetTypes m_DefaultEncoding; Opts::ScreenOrientations m_Orientation; symbol m_ParagraphSymbol; symbol m_SpaceSymbol; symbol m_ControlSymbol; symbol m_StartConversionSymbol; symbol m_EndConversionSymbol; std::string m_TrainingFile; std::string m_GameModeFile; std::string m_DefaultPalette; class utf8_length { public: utf8_length(); int operator[](const unsigned char) const; int max_length; private: int utf8_count_array[0x100]; }; static utf8_length m_utf8_count_array; // TODO: This is inane std::vector < std::string > m_Characters; // stores the characters std::vector < std::string > m_Display; // stores how the characters are visually represented in the Dasher nodes std::vector < int >m_Colours; // stores the colour of the characters std::vector < std::string > m_Foreground; // stores the colour of the character foreground // ---- alphabet_map TextMap; std::string m_strDefaultContext; }; /// @} inline symbol CAlphabet::GetParagraphSymbol() const { return m_ParagraphSymbol; } inline symbol CAlphabet::GetSpaceSymbol() const { return m_SpaceSymbol; } inline symbol CAlphabet::GetControlSymbol() const { return m_ControlSymbol; } inline symbol CAlphabet::GetStartConversionSymbol() const { return m_StartConversionSymbol; } inline symbol CAlphabet::GetEndConversionSymbol() const { return m_EndConversionSymbol; } } // end namespace dasher #endif // ifndef __DASHER_ALPHABET_H__
rgee/HFOSS-Dasher
401408a6fb0721f723b6cbbf5ac7dee5eb5cc38e
fixed memory leak with word generator in game module constructor
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 6ceef74..df2d3ff 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1164 +1,1170 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" #include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> -#include <memory> +#include <tr1/memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); //if game mode is enabled , initialize the game module // if(GetBoolParameter(BP_GAME_MODE)) InitGameModule(); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h + + // We use a shared ptr here for the word generator to avoid issues regarding + // object ownership. Now this class /could/ own a word generator if it wanted + // whereas before its ownership was ambiguous to the only class that + // could delete it. (The game module) Therefore, newing directly to + // the constructor leaked memory. RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"), - new CFileWordGenerator("test_text.txt"))); + std::tr1::shared_ptr<CWordGeneratorBase>(new CFileWordGenerator("test_text.txt")))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index c5af5a0..40a6327 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,222 +1,222 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" - +#include <tr1/memory> namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, - CWordGeneratorBase* pWordGenerator) + std::tr1::shared_ptr<CWordGeneratorBase> pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ - CWordGeneratorBase* m_pWordGenerator; + std::tr1::shared_ptr<CWordGeneratorBase> m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ static const int vEvents[2]; }; } #endif
rgee/HFOSS-Dasher
2645eb7a4d877d256b8596b951fe9af7a961ed64
got rid of unecessary null check
diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 4e9afa8..c5af5a0 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,225 +1,222 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; - - if(m_pWordGenerator == NULL) - g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ static const int vEvents[2]; }; } #endif
rgee/HFOSS-Dasher
1200e732e098a0b59d38fd1a57872cb3dd6252fc
Added GameModule.cpp
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 39d533f..a255e14 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,137 +1,137 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { - case EV_EDIT: + case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } }
rgee/HFOSS-Dasher
079b6ecbbecc54fd75036bb79bac22f3e2735b22
Once again, forgot to add anything before last commit. Need to stop doing that.
diff --git a/Data/GUI/dasher.traditional.ui b/Data/GUI/dasher.traditional.ui index 8a2378a..1c4c3b4 100644 --- a/Data/GUI/dasher.traditional.ui +++ b/Data/GUI/dasher.traditional.ui @@ -1,461 +1,461 @@ <?xml version="1.0"?> <!--*- mode: xml -*--> <interface> <object class="GtkAdjustment" id="adjustment1"> <property name="upper">8</property> <property name="lower">0.1</property> <property name="page_increment">1</property> <property name="step_increment">0.1</property> <property name="page_size">0</property> <property name="value">1</property> </object> <object class="GtkUIManager" id="uimanager1"> <child> <object class="GtkActionGroup" id="actiongroup1"> <child> <object class="GtkAction" id="file_menu"> <property name="label" translatable="yes">_File</property> </object> </child> <child> <object class="GtkAction" id="action_new"> <property name="stock_id">gtk-new</property> <property name="tooltip" translatable="yes">New file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_open"> <property name="stock_id">gtk-open</property> <property name="tooltip" translatable="yes">Open file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_save"> <property name="stock_id">gtk-save</property> <property name="tooltip" translatable="yes">Save file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_saveas"> <property name="stock_id">gtk-save-as</property> <property name="tooltip" translatable="yes">Save file as</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_append"> <property name="name">action_append</property> <property name="label" translatable="yes">A_ppend to file…</property> </object> </child> <child> <object class="GtkAction" id="action_import"> <property name="label" translatable="yes">_Import Training Text…</property> <signal name="activate" handler="dasher_main_cb_import"/> </object> </child> <child> <object class="GtkAction" id="action_quit"> <property name="stock_id">gtk-quit</property> <property name="tooltip" translatable="yes">Quit</property> <signal name="activate" handler="dasher_main_cb_quit"/> </object> </child> <child> <object class="GtkAction" id="edit_menu"> <property name="label" translatable="yes">_Edit</property> </object> </child> <child> <object class="GtkAction" id="action_cut"> <property name="stock_id">gtk-cut</property> <property name="tooltip" translatable="yes">Cut</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copy"> <property name="stock_id">gtk-copy</property> <property name="tooltip" translatable="yes">Copy</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copyall"> <property name="label" translatable="yes">Copy _All</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_paste"> <property name="stock_id">gtk-paste</property> <property name="tooltip" translatable="yes">Paste</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_preferences"> <property name="stock_id">gtk-preferences</property> <property name="label" translatable="yes">Pr_eferences…</property> <property name="tooltip" translatable="yes">Preferences</property> <signal name="activate" handler="dasher_main_cb_preferences"/> </object> <accelerator key="S" modifiers="GDK_CONTROL_MASK | GDK_SHIFT_MASK"/> </child> <child> <object class="GtkAction" id="help_menu"> <property name="label" translatable="yes">_Help</property> </object> </child> <child> <object class="GtkAction" id="action_help"> <property name="stock_id">gtk-help</property> <property name="label" translatable="yes">_Contents…</property> <property name="tooltip" translatable="yes">Help</property> <signal name="activate" handler="dasher_main_cb_help"/> </object> <accelerator key="F1" modifiers="0"/> </child> <child> <object class="GtkAction" id="action_about"> <property name="stock_id">gtk-about</property> <property name="label" translatable="yes">_About…</property> <signal name="activate" handler="dasher_main_cb_about"/> </object> </child> <child> <object class="GtkAction" id="action_toggle_game_mode"> <property name="stock_id">action_toggle_game_mode</property> - <property name="tooltip" translatable="yes">_Enter Game Mode</property> - <propterty name = "label" translatable="yes">_Enter GameMode</property> - <signal name="activate" handler="dasher_main_cb_about"/> + <property name="tooltip" translatable="yes">_Game Mode</property> + <property name = "label" translatable="yes">_Game Mode</property> + <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> </object> </child> <ui> <menubar name="dasher_menu_bar"> <menu action="file_menu"> <menuitem action="action_new"/> <menuitem action="action_open"/> <menuitem action="action_save"/> <menuitem action="action_saveas"/> <menuitem action="action_append"/> <menuitem action="action_toggle_game_mode"/> <separator/> <menuitem action="action_import"/> <menuitem action="action_quit"/> </menu> <menu action="edit_menu"> <menuitem action="action_cut"/> <menuitem action="action_copy"/> <menuitem action="action_copyall"/> <menuitem action="action_paste"/> <separator/> <menuitem action="action_preferences"/> </menu> <menu action="help_menu"> <menuitem action="action_help"/> <menuitem action="action_about"/> </menu> </menubar> <toolbar name="dasher_tool_bar"> <toolitem action="action_new"/> <toolitem action="action_open"/> <toolitem action="action_save"/> <toolitem action="action_saveas"/> <separator/> <toolitem action="action_cut"/> <toolitem action="action_copy"/> <toolitem action="action_paste"/> <separator/> <toolitem action="action_preferences"/> <toolitem action="action_help"/> <separator/> <toolitem action="action_quit"/> </toolbar> </ui> </object> <object class="GtkWindow" id="window"> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="events">GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">Dasher</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_NONE</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">False</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <signal handler="dasher_main_cb_window_close" name="delete_event"/> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkMenuBar" constructor="uimanager1" id="dasher_menu_bar"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Quit</property> <property name="pack_direction">GTK_PACK_DIRECTION_LTR</property> <property name="child_pack_direction">GTK_PACK_DIRECTION_LTR</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkToolbar" constructor="uimanager1" id="dasher_tool_bar"> <property name="toolbar_style">GTK_TOOLBAR_ICONS</property> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkVPaned" id="main_divider"> <property name="visible">True</property> <property name="position">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="DasherEditorInternal" id="DasherEditor"> <property name="visible">True</property> <property name="can_focus">True</property> <signal handler="dasher_main_cb_filename_changed" name="filename_changed"/> <signal handler="dasher_main_cb_buffer_changed" name="buffer_changed"/> <signal handler="dasher_main_cb_context_changed" name="context_changed"/> </object> <packing> <property name="shrink">True</property> <property name="resize">False</property> </packing> </child> <child> <object class="GtkDasherControl" id="DasherControl"> <property name="width_request">200</property> <property name="height_request">200</property> <property name="visible">True</property> <signal handler="parameter_notification" name="dasher_changed"/> <signal handler="handle_start_event" name="dasher_start"/> <signal handler="handle_stop_event" name="dasher_stop"/> <signal handler="handle_control_event" name="dasher_control"/> <signal handler="gtk2_edit_output_callback" name="dasher_edit_insert"/> <signal handler="gtk2_edit_delete_callback" name="dasher_edit_delete"/> <signal handler="handle_context_request" name="dasher_context_request"/> <signal handler="handle_request_settings" name="dasher_request_settings"/> <signal handler="focus_in_event" name="focus_in_event"/> <signal handler="on_lock_info" name="dasher_lock_info"/> <signal handler="on_message" name="dasher_message"/> <signal handler="convert_cb" name="dasher_edit_convert"/> <signal handler="protect_cb" name="dasher_edit_protect"/> <signal handler="on_command" name="dasher_command"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="shrink">True</property> <property name="resize">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkHBox" id="hbox8"> <property name="border_width">2</property> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">2</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkLabel" id="label109"> <property name="visible">True</property> <property name="label" translatable="yes">Speed:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbutton1"> <property name="width_request">64</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="climb_rate">0.10000000149</property> <property name="digits">1</property> <property name="numeric">True</property> <property name="update_policy">GTK_UPDATE_IF_VALID</property> <property name="snap_to_ticks">False</property> <property name="wrap">False</property> <property name="adjustment">adjustment1</property> <signal handler="speed_changed" name="value-changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label110"> <property name="visible">True</property> <property name="label" translatable="yes">Alphabet:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkComboBox" id="combobox1"> <property name="width_request">32</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="add_tearoffs">False</property> <property name="focus_on_click">True</property> <signal handler="alphabet_combo_changed" name="changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">True</property> </packing> </child> </object> </child> </object> <object class="GtkWindow" id="lock_window"> <property name="visible">True</property> <property name="title" translatable="yes">Please Wait…</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">True</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <child> <object class="GtkVBox" id="vbox43"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkLabel" id="lock_message"> <property name="visible">True</property> <property name="label"/> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">0</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> </object> <packing> <property name="padding">8</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkAlignment" id="alignment38"> <property name="border_width">8</property> <property name="visible">True</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xscale">1</property> <property name="yscale">1</property> <property name="top_padding">0</property> <property name="bottom_padding">0</property> <property name="left_padding">0</property> <property name="right_padding">0</property> <child> <object class="GtkProgressBar" id="lock_progress"> <property name="visible">True</property> <property name="orientation">GTK_PROGRESS_LEFT_TO_RIGHT</property> <property name="fraction">0</property> <property name="pulse_step">0.10000000149</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> </object> </child> </object> </interface> diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 0b6e807..9181596 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -308,858 +308,858 @@ void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { - m_pSettingsStore->SetBoolParameter(iParameter, bValue); + m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h int GameEvents[] = {EV_EDIT, EV_TEXTDRAW}; RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"), std::vector<int>(GameEvents, GameEvents + sizeof(GameEvents) / sizeof(int)), new CFileWordGenerator("test_text.txt"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/Gtk2/DasherAppSettings.cpp b/Src/Gtk2/DasherAppSettings.cpp index f27792d..9443e64 100644 --- a/Src/Gtk2/DasherAppSettings.cpp +++ b/Src/Gtk2/DasherAppSettings.cpp @@ -1,586 +1,585 @@ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef WITH_GCONF #include <gconf/gconf.h> #include <gconf/gconf-client.h> #include <gconf/gconf-enum-types.h> #endif #include <cstring> #include "DasherAppSettings.h" #include "../Common/AppSettingsData.h" // FIXME - not sure that we're loading parameters from the registry at startup right now // FIXME - shouldn't need to include this, but for now we need access to the global pointer to the dasher control. #include "dasher.h" #include "GtkDasherControl.h" // FIXME - should really do something to make this a singleton class // TODO: Rename this file to fit in with naming conventions // TODO: Bring this into the widget static GtkWidget *pDasherWidget = NULL; struct _DasherAppSettingsPrivate { #ifdef WITH_GCONF // GConf interface GConfClient *pGConfClient; #endif GtkDasherControl *pWidget; gboolean bWidgetSet; }; typedef struct _DasherAppSettingsPrivate DasherAppSettingsPrivate; // Private member functions static void dasher_app_settings_class_init(DasherAppSettingsClass *pClass); static void dasher_app_settings_init(DasherAppSettings *pAppSettings); static void dasher_app_settings_destroy(GObject *pObject); static void dasher_app_settings_init_gconf(DasherAppSettings *pSelf, int argc, char **argv); static void dasher_app_settings_stop_gconf(DasherAppSettings *pSelf); static void dasher_app_settings_load(DasherAppSettings *pSelf); // Function declarations GType dasher_app_settings_get_type() { static GType dasher_app_settings_type = 0; if(!dasher_app_settings_type) { static const GTypeInfo dasher_app_settings_info = { sizeof(DasherAppSettingsClass), NULL, NULL, (GClassInitFunc) dasher_app_settings_class_init, NULL, NULL, sizeof(DasherAppSettings), 0, (GInstanceInitFunc) dasher_app_settings_init, NULL }; dasher_app_settings_type = g_type_register_static(G_TYPE_OBJECT, "DasherAppSettings", &dasher_app_settings_info, static_cast < GTypeFlags > (0)); } return dasher_app_settings_type; } static void dasher_app_settings_class_init(DasherAppSettingsClass *pClass) { GObjectClass *pObjectClass = (GObjectClass *) pClass; pObjectClass->finalize = dasher_app_settings_destroy; } static void dasher_app_settings_init(DasherAppSettings *pDasherControl) { DasherAppSettingsPrivate *pPrivate = new DasherAppSettingsPrivate; pDasherControl->private_data = pPrivate; #ifdef WITH_GCONF pPrivate->pGConfClient = NULL; #endif pPrivate->pWidget = NULL; pPrivate->bWidgetSet = FALSE; } static void dasher_app_settings_destroy(GObject *pObject) { #ifdef WITH_GCONF dasher_app_settings_stop_gconf((DasherAppSettings *)pObject); #endif for(int i(0); i < NUM_OF_APP_SPS; ++i) delete[] app_stringparamtable[i].value; // FIXME - glib routines? // FIXME - do we need a typecast here? delete (DasherAppSettingsPrivate *)(((DasherAppSettings *)pObject)->private_data); // FIXME - I think we need to chain up through the finalize methods // of the parent classes here... } void dasher_app_settings_set_widget(DasherAppSettings *pSelf, GtkDasherControl *pWidget) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate*)(pSelf->private_data); pDasherWidget = GTK_WIDGET(pWidget); pPrivate->pWidget = pWidget; pPrivate->bWidgetSet = TRUE; } static void dasher_app_settings_init_gconf(DasherAppSettings *pSelf, int argc, char **argv) { #ifdef WITH_GCONF DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate*)(pSelf->private_data); GError *pGConfError; if(!gconf_init(argc, argv, &pGConfError)) g_error("Failed to initialise gconf: %s", pGConfError->message); pPrivate->pGConfClient = gconf_client_get_default(); #endif } static void dasher_app_settings_stop_gconf(DasherAppSettings *pSelf) { #ifdef WITH_GCONF DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate*)(pSelf->private_data); g_object_unref(pPrivate->pGConfClient); #endif } static void dasher_app_settings_load(DasherAppSettings *pSelf) { #ifdef WITH_GCONF DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); GError *pGConfError = NULL; GConfValue *pGConfValue; for(int i(0); i < NUM_OF_APP_BPS; ++i ) { if(app_boolparamtable[i].persistent) { gchar szName[256]; strncpy(szName, "/apps/dasher4/", 256); strncat(szName, app_boolparamtable[i].regName, 255 - strlen( szName )); pGConfValue = gconf_client_get_without_default(pPrivate->pGConfClient, szName, &pGConfError); if(pGConfValue) { app_boolparamtable[i].value = gconf_value_get_bool(pGConfValue); gconf_value_free(pGConfValue); } } } for(int i(0); i < NUM_OF_APP_LPS; ++i ) { if(app_longparamtable[i].persistent) { gchar szName[256]; strncpy(szName, "/apps/dasher4/", 256); strncat(szName, app_longparamtable[i].regName, 255 - strlen( szName )); pGConfValue = gconf_client_get_without_default(pPrivate->pGConfClient, szName, &pGConfError); if(pGConfValue) { app_longparamtable[i].value = gconf_value_get_int(pGConfValue); gconf_value_free(pGConfValue); } } } for(int i(0); i < NUM_OF_APP_SPS; ++i ) { if(app_stringparamtable[i].persistent) { gchar szName[256]; strncpy(szName, "/apps/dasher4/", 256); strncat(szName, app_stringparamtable[i].regName, 255 - strlen( szName )); pGConfValue = gconf_client_get_without_default(pPrivate->pGConfClient, szName, &pGConfError); if(pGConfValue) { delete[] app_stringparamtable[i].value; const gchar *szValue(gconf_value_get_string(pGConfValue)); gchar *szNew; szNew = new gchar[strlen(szValue) + 1]; strcpy(szNew, szValue); app_stringparamtable[i].value = szNew; gconf_value_free(pGConfValue); } } } #endif } // Public methods DasherAppSettings *dasher_app_settings_new(int argc, char **argv) { DasherAppSettings *pDasherControl; pDasherControl = (DasherAppSettings *)(g_object_new(dasher_app_settings_get_type(), NULL)); for(int i(0); i < NUM_OF_APP_SPS; ++i) { gchar *szNew; szNew = new gchar[strlen(app_stringparamtable[i].szDefaultValue) + 1]; strcpy(szNew, app_stringparamtable[i].szDefaultValue); app_stringparamtable[i].value = szNew; } #ifdef WITH_GCONF dasher_app_settings_init_gconf(pDasherControl, argc, argv); #endif dasher_app_settings_load(pDasherControl); return pDasherControl; } void dasher_app_settings_reset(DasherAppSettings *pSelf, int iParameter) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate*)(pSelf->private_data); if(iParameter < END_OF_SPS) { if(pPrivate->bWidgetSet) gtk_dasher_control_reset_parameter(GTK_DASHER_CONTROL(pDasherWidget), iParameter); return; } else { // pre_parameter_notification(0, iParameter, 0); if(iParameter < END_OF_APP_BPS) app_boolparamtable[ iParameter - FIRST_APP_BP ].value = app_boolparamtable[ iParameter - FIRST_APP_BP ].bDefaultValue; else if(iParameter < END_OF_APP_LPS) app_longparamtable[ iParameter - FIRST_APP_LP ].value = app_longparamtable[ iParameter - FIRST_APP_LP ].iDefaultValue; else { delete[] app_stringparamtable[iParameter - FIRST_APP_SP].value; gchar *szNew; szNew = new gchar[strlen(app_stringparamtable[iParameter - FIRST_APP_SP].szDefaultValue) + 1]; strcpy(szNew, app_stringparamtable[iParameter - FIRST_APP_SP].szDefaultValue); app_stringparamtable[iParameter - FIRST_APP_SP].value = szNew; } } // TODO: Use real signals to achieve this parameter_notification(0, iParameter, 0); } bool dasher_app_settings_get_bool(DasherAppSettings *pSelf, int iParameter) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate*)(pSelf->private_data); if( iParameter < END_OF_BPS ) { if(pPrivate->bWidgetSet) return gtk_dasher_control_get_parameter_bool(GTK_DASHER_CONTROL(pDasherWidget), iParameter); else return false; } else return app_boolparamtable[ iParameter - FIRST_APP_BP ].value; } void dasher_app_settings_set_bool(DasherAppSettings *pSelf, int iParameter, bool bValue) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); - if( iParameter < END_OF_BPS ) { if(pPrivate->bWidgetSet) { gtk_dasher_control_set_parameter_bool(GTK_DASHER_CONTROL(pDasherWidget), iParameter, bValue); } } else { if(dasher_app_settings_get_bool(pSelf, iParameter) == bValue) return; // Don't attempt to change to the existing value app_boolparamtable[ iParameter - FIRST_APP_BP ].value = bValue; #ifdef WITH_GCONF if(app_boolparamtable[ iParameter - FIRST_APP_BP ].persistent) { gchar szName[256]; strncpy(szName, "/apps/dasher4/", 256); strncat(szName, app_boolparamtable[ iParameter - FIRST_APP_BP ].regName, 255 - strlen( szName )); GError *pGConfError = NULL; gconf_client_set_bool(pPrivate->pGConfClient, szName, bValue, &pGConfError); if(pGConfError) g_message("Error"); } #endif // TODO: Use real signals to achieve this parameter_notification(0, iParameter, 0); } } gint dasher_app_settings_get_long(DasherAppSettings *pSelf, int iParameter) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); if( iParameter < END_OF_LPS) { if(pPrivate->bWidgetSet) return gtk_dasher_control_get_parameter_long(GTK_DASHER_CONTROL(pDasherWidget), iParameter); else return false; } else return app_longparamtable[ iParameter - FIRST_APP_LP ].value; } void dasher_app_settings_set_long(DasherAppSettings *pSelf, int iParameter, gint iValue) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); if( iParameter < END_OF_LPS) { if(pPrivate->bWidgetSet) gtk_dasher_control_set_parameter_long(GTK_DASHER_CONTROL(pDasherWidget), iParameter, iValue); } else { if(dasher_app_settings_get_long(pSelf, iParameter) == iValue) return; // Don't attempt to change to the existing value // pre_parameter_notification(0, iParameter, 0); app_longparamtable[ iParameter - FIRST_APP_LP ].value = iValue; #ifdef WITH_GCONF if(app_longparamtable[ iParameter - FIRST_APP_LP ].persistent) { gchar szName[256]; strncpy(szName, "/apps/dasher4/", 256); strncat(szName, app_longparamtable[ iParameter - FIRST_APP_LP ].regName, 255 - strlen( szName )); GError *pGConfError = NULL; gconf_client_set_int(pPrivate->pGConfClient, szName, iValue, &pGConfError); } #endif // TODO: Use real signals to achieve this parameter_notification(0, iParameter, 0); } } gboolean dasher_app_settings_get_free_long(DasherAppSettings *pSelf, const gchar *szName, gint &iValue) { #ifdef WITH_GCONF DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); gchar szFullName[256]; strncpy(szFullName, "/apps/dasher4/", 256); strncat(szFullName, szName, 255 - strlen(szFullName)); GConfValue *pGConfValue; GError *pGConfError = NULL; pGConfValue = gconf_client_get_without_default(pPrivate->pGConfClient, szFullName, &pGConfError); if(pGConfValue) { iValue = gconf_value_get_int(pGConfValue); gconf_value_free(pGConfValue); return true; } else { return false; } #else return false; #endif } void dasher_app_settings_set_free_long(DasherAppSettings *pSelf, const gchar *szName, gint iValue) { #ifdef WITH_GCONF DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); gchar szFullName[256]; strncpy(szFullName, "/apps/dasher4/", 256); strncat(szFullName, szName, 255 - strlen(szFullName)); GError *pGConfError = NULL; gconf_client_set_int(pPrivate->pGConfClient, szFullName, iValue, &pGConfError); #endif } const gchar *dasher_app_settings_get_string(DasherAppSettings *pSelf, int iParameter) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); if( iParameter < END_OF_SPS ) { if(pPrivate->bWidgetSet) return gtk_dasher_control_get_parameter_string(GTK_DASHER_CONTROL(pDasherWidget), iParameter); else return false; } else return app_stringparamtable[ iParameter - FIRST_APP_SP ].value; } void dasher_app_settings_set_string(DasherAppSettings *pSelf, int iParameter, const gchar *szValue) { DasherAppSettingsPrivate *pPrivate = (DasherAppSettingsPrivate *)(pSelf->private_data); if( iParameter < END_OF_SPS ) { if(pPrivate->bWidgetSet) gtk_dasher_control_set_parameter_string(GTK_DASHER_CONTROL(pDasherWidget), iParameter, szValue); } else { if(!strcmp(dasher_app_settings_get_string(pSelf, iParameter), szValue)) return; // Don't attempt to change to the existing value // pre_parameter_notification(0, iParameter, 0); delete[] app_stringparamtable[ iParameter - FIRST_APP_SP ].value; gchar *szNew; szNew = new gchar[strlen(szValue) + 1]; strcpy(szNew, szValue); app_stringparamtable[ iParameter - FIRST_APP_SP ].value = szNew; #ifdef WITH_GCONF if(app_stringparamtable[ iParameter - FIRST_APP_SP ].persistent) { gchar szName[256]; strncpy(szName, "/apps/dasher4/", 256); strncat(szName, app_stringparamtable[ iParameter - FIRST_APP_SP ].regName, 255 - strlen( szName )); GError *pGConfError = NULL; gconf_client_set_string(pPrivate->pGConfClient, szName, szValue, &pGConfError); } #endif // TODO: Use real signals to achieve this parameter_notification(0, iParameter, 0); } } int dasher_app_settings_get_count(DasherAppSettings *pSelf) { return END_OF_APP_SPS; } int dasher_app_settings_get_parameter_type(DasherAppSettings *pSelf, int iParameter) { if(iParameter < END_OF_BPS) return DASHER_TYPE_BOOL; else if(iParameter < END_OF_LPS) return DASHER_TYPE_LONG; else if(iParameter < END_OF_SPS) return DASHER_TYPE_STRING; else if(iParameter < END_OF_APP_BPS) return DASHER_TYPE_BOOL; else if(iParameter < END_OF_APP_LPS) return DASHER_TYPE_LONG; else return DASHER_TYPE_STRING; } const gchar *dasher_app_settings_get_reg_name(DasherAppSettings *pSelf, int iParameter) { if(iParameter < END_OF_BPS) return boolparamtable[iParameter - FIRST_BP].regName; else if(iParameter < END_OF_LPS) return longparamtable[iParameter - FIRST_LP].regName; else if(iParameter < END_OF_SPS) return stringparamtable[iParameter - FIRST_SP].regName; else if(iParameter < END_OF_APP_BPS) return app_boolparamtable[iParameter - FIRST_APP_BP].regName; else if(iParameter < END_OF_APP_LPS) return app_longparamtable[iParameter - FIRST_APP_LP].regName; else return app_stringparamtable[iParameter - FIRST_APP_SP].regName; } const gchar *dasher_app_settings_get_human_name(DasherAppSettings *pSelf, int iParameter) { if(iParameter < END_OF_BPS) return boolparamtable[iParameter - FIRST_BP].humanReadable; else if(iParameter < END_OF_LPS) return longparamtable[iParameter - FIRST_LP].humanReadable; else if(iParameter < END_OF_SPS) return stringparamtable[iParameter - FIRST_SP].humanReadable; else if(iParameter < END_OF_APP_BPS) return app_boolparamtable[iParameter - FIRST_APP_BP].humanReadable; else if(iParameter < END_OF_APP_LPS) return app_longparamtable[iParameter - FIRST_APP_LP].humanReadable; else return app_stringparamtable[iParameter - FIRST_APP_SP].humanReadable; } bool dasher_app_settings_have_advanced(DasherAppSettings *pSelf) { return(g_find_program_in_path("gconf-editor") != NULL); } void dasher_app_settings_launch_advanced(DasherAppSettings *pSelf) { gchar *szArgs[3]; szArgs[0] = "gconf-editor"; szArgs[1] = "/apps/dasher4"; szArgs[2] = NULL; GError *pError; if(!g_spawn_async(NULL, szArgs, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &pError)) { g_warning("Could not launch gconf-editor: %s", pError->message); } } void dasher_app_settings_set_widget(DasherAppSettings *pSelf, GtkWidget *pWidget) { pDasherWidget = pWidget; } GArray *dasher_app_settings_get_allowed_values(DasherAppSettings *pSelf, int iParameter) { return gtk_dasher_control_get_allowed_values(GTK_DASHER_CONTROL(pDasherWidget), iParameter); } gboolean dasher_app_settings_get_module_settings(DasherAppSettings *pSelf, const gchar *szValue, SModuleSettings **pSettings, gint *iCount) { return gtk_dasher_control_get_module_settings(GTK_DASHER_CONTROL(pDasherWidget), szValue, pSettings, iCount); } // Set the option szKey to szValue. Return NULL if everything worked, a // (literal) error string for unrecognized or illegal values. const gchar * dasher_app_settings_cl_set(DasherAppSettings *pSelf, const gchar *szKey, const gchar *szValue) { for(int i(0); i < NUM_OF_APP_BPS; ++i ) { if(!strcmp(app_boolparamtable[i].regName, szKey)) { if(!strcmp(szValue, "1") || !strcmp(szValue, _("true"))) dasher_app_settings_set_bool(pSelf, app_boolparamtable[i].key, true); else if(!strcmp(szValue, "0") || !strcmp(szValue, _("false"))) dasher_app_settings_set_bool(pSelf, app_boolparamtable[i].key, false); else return _("boolean value must be specified as 'true' or 'false'."); return 0; } } for(int i(0); i < NUM_OF_APP_LPS; ++i ) { if(!strcmp(app_longparamtable[i].regName, szKey)) { dasher_app_settings_set_long(pSelf, app_longparamtable[i].key, atoi(szValue)); return 0; } } for(int i(0); i < NUM_OF_APP_SPS; ++i ) { if(!strcmp(app_stringparamtable[i].regName, szKey)) { dasher_app_settings_set_string(pSelf, app_stringparamtable[i].key, szValue); return 0; } } return gtk_dasher_control_cl_set(GTK_DASHER_CONTROL(pDasherWidget), szKey, szValue); } void option_help() { g_print("\n"); g_print("%-30s %-12s %s\n", _("Boolean parameters"), _("Default"), _("Description")); g_print("%-30s %-12s %s\n", "------------------------------", "------------", "------------------------------"); for(unsigned int i=0; i < sizeof(app_boolparamtable)/sizeof(app_boolparamtable[0]); ++i) { g_print("%-30s %-12s %s\n", app_boolparamtable[i].regName, (app_boolparamtable[i].bDefaultValue ? _("true") : _("false")), app_boolparamtable[i].humanReadable); } for(unsigned int i = 0; i < sizeof(boolparamtable)/sizeof(boolparamtable[0]); i++) { g_print("%-30s %-12s %s\n", boolparamtable[i].regName, (boolparamtable[i].defaultValue ? _("true") : _("false")), boolparamtable[i].humanReadable); } g_print("\n"); g_print("%-30s %-12s %s\n", _("Integer parameters"), _("Default"), _("Description")); g_print("%-30s %-12s %s\n", "------------------------------", "------------", "------------------------------"); for(unsigned int i=0; i < sizeof(app_longparamtable)/sizeof(app_longparamtable[0]); ++i) { g_print("%-30s %12li %s\n", app_longparamtable[i].regName, app_longparamtable[i].iDefaultValue, app_longparamtable[i].humanReadable); } for(unsigned int i = 0; i < sizeof(longparamtable)/sizeof(longparamtable[0]); i++) { g_print("%-30s %12li %s\n", longparamtable[i].regName, longparamtable[i].defaultValue, longparamtable[i].humanReadable); } g_print("\n"); g_print("%-30s %-12s %s\n", _("String parameters"), _("Default"), _("Description")); g_print("%-30s %-12s %s\n", "------------------------------", "------------", "------------------------------"); for(unsigned int i=0; i < sizeof(app_stringparamtable)/sizeof(app_stringparamtable[0]); ++i) { g_print("%-30s %-12s %s\n", app_stringparamtable[i].regName, app_stringparamtable[i].szDefaultValue, app_stringparamtable[i].humanReadable); } for(unsigned int i = 0; i < sizeof(stringparamtable)/sizeof(stringparamtable[0]); i++) { g_print("%-30s %-12s %s\n", stringparamtable[i].regName, stringparamtable[i].defaultValue, stringparamtable[i].humanReadable); } } diff --git a/Src/Gtk2/DasherAppSettings.h b/Src/Gtk2/DasherAppSettings.h index 2c5740a..2e92cf1 100644 --- a/Src/Gtk2/DasherAppSettings.h +++ b/Src/Gtk2/DasherAppSettings.h @@ -1,79 +1,79 @@ #ifndef __dasher_app_settings_h__ #define __dasher_app_settings_h__ #include <glib.h> #include <glib-object.h> #include "../DasherCore/Parameters.h" #include "../Common/AppSettingsHeader.h" #include "GtkDasherControl.h" // Define first int value of the first element of each type. // Useful for offsetting into specific arrays, // since each setting is a unique int, but all 3 arrays start at 0 #define FIRST_APP_BP END_OF_SPS #define FIRST_APP_LP END_OF_APP_BPS #define FIRST_APP_SP END_OF_APP_LPS // Define the number of each type of setting #define NUM_OF_APP_BPS (END_OF_APP_BPS - END_OF_SPS) #define NUM_OF_APP_LPS (END_OF_APP_LPS - END_OF_APP_BPS) #define NUM_OF_APP_SPS (END_OF_APP_SPS - END_OF_APP_LPS) enum { DASHER_TYPE_BOOL, DASHER_TYPE_LONG, DASHER_TYPE_STRING }; G_BEGIN_DECLS #define TYPE_DASHER_APP_SETTINGS (dasher_app_settings_get_type()) #define DASHER_APP_SETTINGS(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), TYPE_DASHER_APP_SETTINGS, DasherAppSettings )) #define DASHER_APP_SETTINGS_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TYPE_DASHER_APP_SETTINGS, DasherAppSettingsClass )) #define IS_DASHER_APP_SETTINGS(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), TYPE_DASHER_APP_SETTINGS)) #define IS_DASHER_APP_SETTINGS_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TYPE_DASHER_APP_SETTINGS)) #define DASHER_APP_SETTINGS_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TYPE_DASHER_APP_SETTINGS, DasherAppSettingsClass)) typedef struct _DasherAppSettings DasherAppSettings; typedef struct _DasherAppSettingsClass DasherAppSettingsClass; struct _DasherAppSettings { GObject parent; gpointer private_data; }; struct _DasherAppSettingsClass { GObjectClass parent_class; }; DasherAppSettings *dasher_app_settings_new(int argc, char **argv); GType dasher_app_settings_get_type(); void dasher_app_settings_reset(DasherAppSettings *pSelf, int iParameter); void dasher_app_settings_set_widget(DasherAppSettings *pSelf, GtkDasherControl *pWidget); bool dasher_app_settings_get_bool(DasherAppSettings *pSelf, int iParameter); void dasher_app_settings_set_bool(DasherAppSettings *pSelf, int iParameter, bool bValue); gint dasher_app_settings_get_long(DasherAppSettings *pSelf, int iParameter); void dasher_app_settings_set_long(DasherAppSettings *pSelf, int iParameter, gint iValue); gboolean dasher_app_settings_get_free_long(DasherAppSettings *pSelf, const gchar *szName, gint &iValue); void dasher_app_settings_set_free_long(DasherAppSettings *pSelf, const gchar *szName, gint iValue); const gchar *dasher_app_settings_get_string(DasherAppSettings *pSelf, int iParameter); void dasher_app_settings_set_string(DasherAppSettings *pSelf, int iParameter, const gchar *szValue); int dasher_app_settings_get_count(DasherAppSettings *pSelf); +GArray *dasher_app_settings_get_allowed_values(DasherAppSettings *pSelf, int iParameter); int dasher_app_settings_get_parameter_type(DasherAppSettings *pSelf, int iParameter); const gchar *dasher_app_settings_get_reg_name(DasherAppSettings *pSelf, int iParameter); const gchar *dasher_app_settings_get_human_name(DasherAppSettings *pSelf, int iParameter); bool dasher_app_settings_have_advanced(DasherAppSettings *pSelf); void dasher_app_settings_launch_advanced(DasherAppSettings *pSelf); -GArray *dasher_app_settings_get_allowed_values(DasherAppSettings *pSelf, int iParameter); gboolean dasher_app_settings_get_module_settings(DasherAppSettings *pSelf, const gchar *szValue, SModuleSettings **pSettings, gint *iCount); const gchar * dasher_app_settings_cl_set(DasherAppSettings *pSelf, const gchar *szKey, const gchar *szValue); void option_help(); G_END_DECLS #endif diff --git a/Src/Gtk2/DasherControl.cpp b/Src/Gtk2/DasherControl.cpp index e743238..a8f96f3 100644 --- a/Src/Gtk2/DasherControl.cpp +++ b/Src/Gtk2/DasherControl.cpp @@ -1,612 +1,613 @@ #include "../Common/Common.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <iostream> #include "DasherControl.h" #include "Timer.h" #include "../DasherCore/Event.h" #include "../DasherCore/ModuleManager.h" #include <fcntl.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <sys/stat.h> #include <unistd.h> using namespace std; // 'Private' methods (only used in this file) extern "C" gint key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data); extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data); extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data); extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData); extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data); static bool g_iTimeoutID = 0; // CDasherControl class definitions CDasherControl::CDasherControl(GtkVBox *pVBox, GtkDasherControl *pDasherControl) { m_pPangoCache = NULL; m_pScreen = NULL; m_pDasherControl = pDasherControl; m_pVBox = GTK_WIDGET(pVBox); Realize(); // m_pKeyboardHelper = new CKeyboardHelper(this); // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); } void CDasherControl::CreateModules() { CDasherInterfaceBase::CreateModules(); //create default set first // Create locally cached copies of the mouse input objects, as we // need to pass coordinates to them from the timer callback m_pMouseInput = (CDasherMouseInput *) RegisterModule(new CDasherMouseInput(m_pEventHandler, m_pSettingsStore)); SetDefaultInputDevice(m_pMouseInput); m_p1DMouseInput = (CDasher1DMouseInput *)RegisterModule(new CDasher1DMouseInput(m_pEventHandler, m_pSettingsStore)); RegisterModule(new CSocketInput(m_pEventHandler, m_pSettingsStore)); #ifdef JOYSTICK RegisterModule(new CDasherJoystickInput(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CDasherJoystickInputDiscrete(m_pEventHandler, m_pSettingsStore, this)); #endif #ifdef TILT RegisterModule(new CDasherTiltInput(m_pEventHandler, m_pSettingsStore, this)); #endif } void CDasherControl::SetupUI() { m_pCanvas = gtk_drawing_area_new(); #if GTK_CHECK_VERSION (2,18,0) gtk_widget_set_can_focus(m_pCanvas, TRUE); #else GTK_WIDGET_SET_FLAGS(m_pCanvas, GTK_CAN_FOCUS); #endif gtk_widget_set_double_buffered(m_pCanvas, FALSE); GtkWidget *pFrame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(pFrame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(pFrame), m_pCanvas); gtk_box_pack_start(GTK_BOX(m_pVBox), pFrame, TRUE, TRUE, 0); gtk_widget_show_all(GTK_WIDGET(m_pVBox)); // Connect callbacks - note that we need to implement the callbacks // as "C" style functions and pass this as user data so they can // call the object g_signal_connect(m_pCanvas, "button_press_event", G_CALLBACK(button_press_event), this); g_signal_connect(m_pCanvas, "button_release_event", G_CALLBACK(button_press_event), this); g_signal_connect_after(m_pCanvas, "realize", G_CALLBACK(realize_canvas), this); g_signal_connect(m_pCanvas, "configure_event", G_CALLBACK(canvas_configure_event), this); g_signal_connect(m_pCanvas, "destroy", G_CALLBACK(canvas_destroy_event), this); - + g_signal_connect(m_pCanvas, "key-release-event", G_CALLBACK(key_release_event), this); g_signal_connect(m_pCanvas, "key_press_event", G_CALLBACK(key_press_event), this); g_signal_connect(m_pCanvas, "focus_in_event", G_CALLBACK(canvas_focus_event), this); g_signal_connect(m_pCanvas, "expose_event", G_CALLBACK(canvas_expose_event), this); + //g_signal_connect(m_pDasher) // Create the Pango cache // TODO: Use system defaults? if(GetStringParameter(SP_DASHER_FONT) == "") SetStringParameter(SP_DASHER_FONT, "Sans 10"); m_pPangoCache = new CPangoCache(GetStringParameter(SP_DASHER_FONT)); } void CDasherControl::SetupPaths() { char *home_dir; char *user_data_dir; const char *system_data_dir; home_dir = getenv("HOME"); user_data_dir = new char[strlen(home_dir) + 10]; sprintf(user_data_dir, "%s/.dasher/", home_dir); mkdir(user_data_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // PROGDATA is provided by the makefile system_data_dir = PROGDATA "/"; SetStringParameter(SP_SYSTEM_LOC, system_data_dir); SetStringParameter(SP_USER_LOC, user_data_dir); delete[] user_data_dir; } void CDasherControl::CreateSettingsStore() { m_pSettingsStore = new CGnomeSettingsStore(m_pEventHandler); } void CDasherControl::ScanAlphabetFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *alphabetglob; alphabetglob = g_pattern_spec_new("alphabet*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(alphabetglob); } void CDasherControl::ScanColourFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *colourglob; colourglob = g_pattern_spec_new("colour*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(colourglob); } CDasherControl::~CDasherControl() { if(m_pMouseInput) { m_pMouseInput = NULL; } if(m_p1DMouseInput) { m_p1DMouseInput = NULL; } if(m_pPangoCache) { delete m_pPangoCache; m_pPangoCache = NULL; } // if(m_pKeyboardHelper) { // delete m_pKeyboardHelper; // m_pKeyboardHelper = 0; // } } bool CDasherControl::FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent) { if((pEvent->type == GDK_FOCUS_CHANGE) && (pEvent->in)) { GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); gboolean *returnType; focusEvent->type = GDK_FOCUS_CHANGE; focusEvent->window = (GdkWindow *) m_pDasherControl; focusEvent->send_event = FALSE; focusEvent->in = TRUE; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "focus_in_event", GTK_WIDGET(m_pDasherControl), focusEvent, NULL, &returnType); } return true; } void CDasherControl::SetFocus() { gtk_widget_grab_focus(m_pCanvas); } void CDasherControl::GameMessageOut(int message, const void* messagedata) { gtk_dasher_control_game_messageout(m_pDasherControl, message, messagedata); } GArray *CDasherControl::GetAllowedValues(int iParameter) { // Glib version of the STL based core function GArray *pRetVal(g_array_new(false, false, sizeof(gchar *))); std::vector < std::string > vList; GetPermittedValues(iParameter, vList); for(std::vector < std::string >::iterator it(vList.begin()); it != vList.end(); ++it) { // For internal glib reasons we need to make a variable and then // pass - we can't use the iterator directly const char *pTemp(it->c_str()); char *pTempNew = new char[strlen(pTemp) + 1]; strcpy(pTempNew, pTemp); g_array_append_val(pRetVal, pTempNew); } return pRetVal; } void CDasherControl::RealizeCanvas(GtkWidget *pWidget) { // TODO: Pointless function - call directly from C callback. #ifdef DEBUG std::cout << "RealizeCanvas()" << std::endl; #endif OnUIRealised(); } void CDasherControl::StartTimer() { // Start the timer loops as everything is set up. // Aim for 40 frames per second, computers are getting faster. if(g_iTimeoutID == 0) { g_iTimeoutID = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 25, timer_callback, this, NULL); // TODO: Reimplement this (or at least reimplement some kind of status reporting) //g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 5000, long_timer_callback, this, NULL); } } void CDasherControl::ShutdownTimer() { // TODO: Figure out how to implement this - at the moment it's done // through a return value from the timer callback, but it would be // nicer to prevent any further calls as soon as the shutdown signal // has been receieved. } int CDasherControl::CanvasConfigureEvent() { GtkAllocation a; #if GTK_CHECK_VERSION (2,18,0) gtk_widget_get_allocation(m_pCanvas, &a); #else a.width = m_pCanvas->allocation.width; a.height = m_pCanvas->allocation.height; #endif if(m_pScreen != NULL) delete m_pScreen; m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache, a.width, a.height); ChangeScreen(m_pScreen); return 0; } void CDasherControl::ExternalEventHandler(Dasher::CEvent *pEvent) { // Convert events coming from the core to Glib signals. if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); HandleParameterNotification(pEvt->m_iParameter); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_changed", pEvt->m_iParameter); } else if(pEvent->m_iEventType == EV_EDIT) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { // Insert event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_insert", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 2) { // Delete event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 10) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_convert"); } else if(pEditEvent->m_iEditType == 11) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_protect"); } } else if(pEvent->m_iEventType == EV_EDIT_CONTEXT) { CEditContextEvent *pEditContextEvent(static_cast < CEditContextEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_context_request", pEditContextEvent->m_iOffset, pEditContextEvent->m_iLength); } else if(pEvent->m_iEventType == EV_START) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_start"); } else if(pEvent->m_iEventType == EV_STOP) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_stop"); } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast < CControlEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_control", pControlEvent->m_iID); } else if(pEvent->m_iEventType == EV_LOCK) { CLockEvent *pLockEvent(static_cast<CLockEvent *>(pEvent)); DasherLockInfo sInfo; sInfo.szMessage = pLockEvent->m_strMessage.c_str(); sInfo.bLock = pLockEvent->m_bLock; sInfo.iPercent = pLockEvent->m_iPercent; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_lock_info", &sInfo); } else if(pEvent->m_iEventType == EV_MESSAGE) { CMessageEvent *pMessageEvent(static_cast<CMessageEvent *>(pEvent)); DasherMessageInfo sInfo; sInfo.szMessage = pMessageEvent->m_strMessage.c_str(); sInfo.iID = pMessageEvent->m_iID; sInfo.iType = pMessageEvent->m_iType; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_message", &sInfo); } else if(pEvent->m_iEventType == EV_COMMAND) { CCommandEvent *pCommandEvent(static_cast<CCommandEvent *>(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_command", pCommandEvent->m_strCommand.c_str()); } }; void CDasherControl::WriteTrainFile(const std::string &strNewText) { if(strNewText.length() == 0) return; std::string strFilename(GetStringParameter(SP_USER_LOC) + GetStringParameter(SP_TRAIN_FILE)); int fd=open(strFilename.c_str(),O_CREAT|O_WRONLY|O_APPEND,S_IRUSR|S_IWUSR); write(fd,strNewText.c_str(),strNewText.length()); close(fd); } // TODO: Sort these methods out void CDasherControl::ExternalKeyDown(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyDown(get_time(), iButtonID); // } KeyDown(get_time(), iKeyVal); } void CDasherControl::ExternalKeyUp(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyUp(get_time(), iButtonID); // } KeyUp(get_time(), iKeyVal); } void CDasherControl::HandleParameterNotification(int iParameter) { switch(iParameter) { case SP_DASHER_FONT: if(m_pPangoCache) { m_pPangoCache->ChangeFont(GetStringParameter(SP_DASHER_FONT)); ScheduleRedraw(); } break; case BP_GLOBAL_KEYBOARD: // TODO: reimplement // if(m_pKeyboardHelper) // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); break; } } int CDasherControl::TimerEvent() { int x, y; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_pointer(gtk_widget_get_window(m_pCanvas), &x, &y, NULL); #else gdk_window_get_pointer(m_pCanvas->window, &x, &y, NULL); #endif m_pMouseInput->SetCoordinates(x, y); gdk_window_get_pointer(gdk_get_default_root_window(), &x, &y, NULL); int iRootWidth; int iRootHeight; gdk_drawable_get_size(gdk_get_default_root_window(), &iRootWidth, &iRootHeight); if(GetLongParameter(LP_YSCALE) < 10) SetLongParameter(LP_YSCALE, 10); y = (y - iRootHeight / 2); m_p1DMouseInput->SetCoordinates(y, GetLongParameter(LP_YSCALE)); NewFrame(get_time(), false); // Update our UserLog object about the current mouse position CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { // We want current canvas and window coordinates so normalization // is done properly with respect to the canvas. GdkRectangle sWindowRect; GdkRectangle sCanvasRect; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_frame_extents(gtk_widget_get_window(m_pCanvas), &sWindowRect); #else gdk_window_get_frame_extents(m_pCanvas->window, &sWindowRect); #endif pUserLog->AddWindowSize(sWindowRect.y, sWindowRect.x, sWindowRect.y + sWindowRect.height, sWindowRect.x + sWindowRect.width); if (m_pScreen != NULL) { if (m_pScreen->GetCanvasSize(&sCanvasRect)) pUserLog->AddCanvasSize(sCanvasRect.y, sCanvasRect.x, sCanvasRect.y + sCanvasRect.height, sCanvasRect.x + sCanvasRect.width); } int iMouseX = 0; int iMouseY = 0; gdk_window_get_pointer(NULL, &iMouseX, &iMouseY, NULL); // TODO: This sort of thing shouldn't be in specialised methods, move into base class somewhere pUserLog->AddMouseLocationNormalized(iMouseX, iMouseY, true, GetNats()); } return 1; // See CVS for code which used to be here } int CDasherControl::LongTimerEvent() { // std::cout << "Framerate: " << GetFramerate() << std::endl; // std::cout << "Render count: " << GetRenderCount() << std::endl; return 1; } gboolean CDasherControl::ExposeEvent() { NewFrame(get_time(), true); return 0; } gboolean CDasherControl::ButtonPressEvent(GdkEventButton *event) { // Take the focus if we click on the canvas // GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); // gboolean *returnType; // focusEvent->type = GDK_FOCUS_CHANGE; // focusEvent->window = (GdkWindow *) m_pCanvas; // focusEvent->send_event = FALSE; // focusEvent->in = TRUE; // gtk_widget_grab_focus(GTK_WIDGET(m_pCanvas)); // g_signal_emit_by_name(GTK_OBJECT(m_pCanvas), "focus_in_event", GTK_WIDGET(m_pCanvas), focusEvent, NULL, &returnType); // No - don't take the focus - give it to the text area instead if(event->type == GDK_BUTTON_PRESS) HandleClickDown(get_time(), (int)event->x, (int)event->y); else if(event->type == GDK_BUTTON_RELEASE) HandleClickUp(get_time(), (int)event->x, (int)event->y); return false; } gint CDasherControl::KeyReleaseEvent(GdkEventKey *event) { // TODO: This is seriously flawed - the semantics of of X11 Keyboard // events mean the there's no guarantee that key up/down events will // be received in pairs. if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) { // if(event->state & GDK_CONTROL_MASK) // SetLongParameter(LP_BOOSTFACTOR, 25); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) { // if(event->state & GDK_SHIFT_MASK) // SetLongParameter(LP_BOOSTFACTOR, 175); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyUp(get_time(), iKeyVal); // } } return 0; } gint CDasherControl::KeyPressEvent(GdkEventKey *event) { // if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) // SetLongParameter(LP_BOOSTFACTOR, 175); // else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) // SetLongParameter(LP_BOOSTFACTOR, 25); // else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyDown(get_time(), iKeyVal); // } // } return 0; } void CDasherControl::CanvasDestroyEvent() { // Delete the screen if(m_pScreen != NULL) { delete m_pScreen; m_pScreen = NULL; } } // Tell the logging object that a new user trial is starting. void CDasherControl::UserLogNewTrial() { CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { pUserLog->NewTrial(); } } int CDasherControl::GetFileSize(const std::string &strFileName) { struct stat sStatInfo; if(!stat(strFileName.c_str(), &sStatInfo)) return sStatInfo.st_size; else return 0; } // "C" style callbacks - these are here just because it's not possible // (or at least not easy) to connect a callback directly to a C++ // method, so we pass a pointer to th object in the user_data field // and use a wrapper function. Please do not put any functional code // here. extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data) { static_cast < CDasherControl * >(user_data)->RealizeCanvas(widget); } extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) { return static_cast < CDasherControl * >(data)->ButtonPressEvent(event); } extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { return static_cast < CDasherControl * >(data)->KeyPressEvent(event); } extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { return static_cast < CDasherControl * >(data)->CanvasConfigureEvent(); } extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData) { static_cast<CDasherControl*>(pUserData)->CanvasDestroyEvent(); diff --git a/Src/Gtk2/dasher_editor_internal.cpp b/Src/Gtk2/dasher_editor_internal.cpp index 3d576ac..306dd2b 100644 --- a/Src/Gtk2/dasher_editor_internal.cpp +++ b/Src/Gtk2/dasher_editor_internal.cpp @@ -1,1435 +1,1438 @@ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> - #include <glib/gi18n.h> #ifdef HAVE_GIO #include <gio/gio.h> #endif #include <gtk/gtk.h> #ifdef WITH_MAEMO #include "dasher_action_keyboard_maemo.h" #else #include "dasher_action_keyboard.h" #endif #ifndef WITH_MAEMO #include "dasher_action_script.h" #endif #ifdef GNOME_SPEECH #include "dasher_action_speech.h" #endif #include "dasher_editor_internal.h" #include "dasher_external_buffer.h" #include "dasher_internal_buffer.h" #include "dasher_lock_dialogue.h" #include "dasher_main.h" -//#include "game_mode_helper.h" // TODO: Maybe reimplement something along the lines of the following, which used to be in edit.cc // void set_mark() { // GtkTextIter oBufferEnd; // GtkTextIter oBufferStart; // gtk_text_buffer_get_bounds( the_text_buffer, &oBufferStart, &oBufferEnd); // gtk_text_buffer_create_mark(the_text_buffer, "new_start", &oBufferEnd, true); // } // const gchar *get_new_text() { // GtkTextIter oNewStart; // GtkTextIter oNewEnd; // GtkTextIter oDummy; // gtk_text_buffer_get_bounds( the_text_buffer, &oDummy, &oNewEnd); // gtk_text_buffer_get_iter_at_mark( the_text_buffer, &oNewStart, gtk_text_buffer_get_mark(the_text_buffer, "new_start")); // return gtk_text_buffer_get_text( the_text_buffer, &oNewStart, &oNewEnd, false ); // } // --- #define ACTION_STATE_SHOW 1 #define ACTION_STATE_CONTROL 2 #define ACTION_STATE_AUTO 4 typedef struct _EditorAction EditorAction; struct _EditorAction { DasherAction *pAction; EditorAction *pNext; EditorAction *pPrevious; gint iControlID; gint iID; // TODO: does this need to be separate from iControlID? gboolean bShow; gboolean bControl; gboolean bAuto; gint iNSub; }; typedef struct _DasherEditorInternalPrivate DasherEditorInternalPrivate; struct _DasherEditorInternalPrivate { DasherMain *pDasherMain; GtkTextView *pTextView; GtkTextBuffer *pBuffer; GtkVBox *pActionPane; GtkClipboard *pTextClipboard; GtkClipboard *pPrimarySelection; GtkTable *pGameGroup; GtkLabel *pGameInfoLabel; EditorAction *pActionRing; EditorAction *pActionIter; gboolean bActionIterStarted; gint iNextActionID; IDasherBufferSet *pBufferSet; IDasherBufferSet *pExternalBuffer; // GameModeHelper *pGameModeHelper; GtkTextMark *pNewMark; DasherAppSettings *pAppSettings; gchar *szFilename; gboolean bFileModified; // TODO: Make this work properly, export to main for quit etc }; #define DASHER_EDITOR_INTERNAL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), DASHER_TYPE_EDITOR_INTERNAL, DasherEditorInternalPrivate)) /* Signals */ enum { FILENAME_CHANGED, BUFFER_CHANGED, CONTEXT_CHANGED, SIGNAL_NUM }; //static guint dasher_editor_internal_signals[SIGNAL_NUM]; static DasherEditorInternal *g_pEditor; G_DEFINE_TYPE(DasherEditorInternal, dasher_editor_internal, DASHER_TYPE_EDITOR); static void dasher_editor_internal_finalize(GObject *pObject); static void dasher_editor_internal_handle_font(DasherEditor *pSelf, const gchar *szFont); gboolean dasher_editor_internal_command(DasherEditor *pSelf, const gchar *szCommand); void dasher_editor_internal_initialise(DasherEditor *pSelf, DasherAppSettings *pAppSettings, DasherMain *pDasherMain, GtkBuilder *pXML, const gchar *szFullPath); /* Private methods */ static void dasher_editor_internal_select_all(DasherEditor *pSelf); static void dasher_editor_internal_setup_actions(DasherEditor *pSelf); static void dasher_editor_internal_add_action(DasherEditor *pSelf, DasherAction *pNewAction); static EditorAction *dasher_editor_internal_get_action_by_id(DasherEditor *pSelf, int iID); static void dasher_editor_internal_rebuild_action_pane(DasherEditor *pSelf); //static void dasher_editor_internal_display_message(DasherEditor *pSelf, DasherMessageInfo *pMessageInfo); static void dasher_editor_internal_check_activity(DasherEditor *pSelf, EditorAction *pAction); static void dasher_editor_internal_action_save_state(DasherEditor *pSelf, EditorAction *pAction); static void dasher_editor_internal_command_new(DasherEditor *pSelf); static void dasher_editor_internal_command_open(DasherEditor *pSelf); static void dasher_editor_internal_command_save(DasherEditor *pSelf, gboolean bPrompt, gboolean bAppend); #ifdef HAVE_GIO static void dasher_editor_internal_gvfs_print_error(DasherEditor *pSelf, GError *error, const char *myfilename); static GFileOutputStream *append_or_replace_file(GFile *file, bool append, GError **error); static gboolean dasher_editor_internal_gvfs_open_file(DasherEditor *pSelf, const char *filename, gchar ** buffer, gsize *size); static gboolean dasher_editor_internal_gvfs_save_file(DasherEditor *pSelf, const char *filename, gchar * buffer, gsize length, bool append); #else static gboolean dasher_editor_internal_unix_vfs_open_file(DasherEditor *pSelf, const char *filename, gchar ** buffer, gsize *size); static gboolean dasher_editor_internal_unix_vfs_save_file(DasherEditor *pSelf, const char *filename, gchar * buffer, gsize length, bool append); #endif static void dasher_editor_internal_set_filename(DasherEditor *pSelf, const gchar *szFilename); // TODO: Should these be public? static void dasher_editor_internal_convert(DasherEditor *pSelf); static void dasher_editor_internal_protect(DasherEditor *pSelf); static void dasher_editor_internal_new_buffer(DasherEditor *pSelf, const gchar *szFilename); static void dasher_editor_internal_generate_filename(DasherEditor *pSelf); static void dasher_editor_internal_open(DasherEditor *pSelf, const gchar *szFilename); static bool dasher_editor_internal_save_as(DasherEditor *pSelf, const gchar *szFilename, bool bAppend); static void dasher_editor_internal_create_buffer(DasherEditor *pSelf); static void dasher_editor_internal_clear(DasherEditor *pSelf, gboolean bStore); static void dasher_editor_internal_clipboard(DasherEditor *pSelf, clipboard_action act); /* To be obsoleted by movement to GTK buffers */ void dasher_editor_internal_output(DasherEditor *pSelf, const gchar *szText, int iOffset); void dasher_editor_internal_delete(DasherEditor *pSelf, int iLength, int iOffset); const gchar *dasher_editor_internal_get_context(DasherEditor *pSelf, int iOffset, int iLength); gint dasher_editor_internal_get_offset(DasherEditor *pSelf); /* Events proagated from main */ void dasher_editor_internal_handle_stop(DasherEditor *pSelf); void dasher_editor_internal_handle_start(DasherEditor *pSelf); void dasher_editor_internal_handle_control(DasherEditor *pSelf, int iNodeID); /* Action related methods - TODO: a lot of this should be moved to dasher_main (eg action on stop etc) - that way we get a better level of abstraction, and can incorporate commands from other modules too. Actions should only be externally visible as a list of string commands*/ void dasher_editor_internal_action_button(DasherEditor *pSelf, DasherAction *pAction); void dasher_editor_internal_actions_start(DasherEditor *pSelf); bool dasher_editor_internal_actions_more(DasherEditor *pSelf); void dasher_editor_internal_actions_get_next(DasherEditor *pSelf, const gchar **szName, gint *iID, gboolean *bShow, gboolean *bControl, gboolean *bAuto); void dasher_editor_internal_action_set_show(DasherEditor *pSelf, int iActionID, bool bValue); void dasher_editor_internal_action_set_control(DasherEditor *pSelf, int iActionID, bool bValue); void dasher_editor_internal_action_set_auto(DasherEditor *pSelf, int iActionID, bool bValue); void dasher_editor_internal_grab_focus(DasherEditor *pSelf); /* TODO: Tutorial editor should be a separate class */ //void dasher_editor_internal_start_tutorial(DasherEditor *pSelf); /* Todo: possibly tidy up the need to have this public (quit in dasher_main possibly too connected) */ gboolean dasher_editor_internal_file_changed(DasherEditor *pSelf); const gchar *dasher_editor_internal_get_filename(DasherEditor *pSelf); const gchar *dasher_editor_internal_get_all_text(DasherEditor *pSelf); const gchar *dasher_editor_internal_get_new_text(DasherEditor *pSelf); static void dasher_editor_internal_handle_parameter_change(DasherEditor *pSelf, gint iParameter); // Private methods not in class extern "C" void delete_children_callback(GtkWidget *pWidget, gpointer pUserData); extern "C" void main_window_realized(DasherMain *pMain, gpointer pUserData); extern "C" void action_button_callback(GtkWidget *pWidget, gpointer pUserData); extern "C" void context_changed_handler(GObject *pSource, gpointer pUserData); extern "C" void buffer_changed_handler(GObject *pSource, gpointer pUserData); extern "C" void handle_stop_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" void on_message(GtkDasherControl *pDasherControl, gpointer pMessageInfo, gpointer pUserData); extern "C" void on_command(GtkDasherControl *pDasherControl, gchar *szCommand, gpointer pUserData); extern "C" void handle_request_settings(GtkDasherControl * pDasherControl, gpointer data); extern "C" void gtk2_edit_delete_callback(GtkDasherControl *pDasherControl, const gchar *szText, int iOffset, gpointer user_data); extern "C" void gtk2_edit_output_callback(GtkDasherControl *pDasherControl, const gchar *szText, int iOffset, gpointer user_data); extern "C" void convert_cb(GtkDasherControl *pDasherControl, gpointer pUserData); extern "C" void protect_cb(GtkDasherControl *pDasherControl, gpointer pUserData); static void dasher_editor_internal_class_init(DasherEditorInternalClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherEditorInternalPrivate)); GObjectClass *pObjectClass = (GObjectClass *) pClass; pObjectClass->finalize = dasher_editor_internal_finalize; DasherEditorClass *pParentClass = (DasherEditorClass *)pClass; pParentClass->initialise = dasher_editor_internal_initialise; pParentClass->command = dasher_editor_internal_command; pParentClass->output = dasher_editor_internal_output; pParentClass->delete_text = dasher_editor_internal_delete; pParentClass->get_context = dasher_editor_internal_get_context; pParentClass->get_offset = dasher_editor_internal_get_offset; pParentClass->handle_stop = dasher_editor_internal_handle_stop; pParentClass->handle_start = dasher_editor_internal_handle_start; pParentClass->handle_control = dasher_editor_internal_handle_control; pParentClass->action_button = dasher_editor_internal_action_button; pParentClass->actions_start = dasher_editor_internal_actions_start; pParentClass->actions_more = dasher_editor_internal_actions_more; pParentClass->actions_get_next = dasher_editor_internal_actions_get_next; pParentClass->action_set_show = dasher_editor_internal_action_set_show; pParentClass->action_set_control = dasher_editor_internal_action_set_control; pParentClass->action_set_auto = dasher_editor_internal_action_set_auto; pParentClass->grab_focus = dasher_editor_internal_grab_focus; pParentClass->file_changed = dasher_editor_internal_file_changed; pParentClass->get_filename = dasher_editor_internal_get_filename; pParentClass->get_all_text = dasher_editor_internal_get_all_text; pParentClass->get_new_text = dasher_editor_internal_get_new_text; pParentClass->handle_parameter_change = dasher_editor_internal_handle_parameter_change; } static void dasher_editor_internal_init(DasherEditorInternal *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); pPrivate->pTextView = GTK_TEXT_VIEW(gtk_text_view_new()); gtk_text_view_set_wrap_mode(pPrivate->pTextView, GTK_WRAP_WORD); pPrivate->pBuffer = gtk_text_view_get_buffer(pPrivate->pTextView); pPrivate->pBufferSet = NULL; pPrivate->pExternalBuffer = NULL; pPrivate->szFilename = NULL; pPrivate->pTextClipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); pPrivate->pPrimarySelection = gtk_clipboard_get(GDK_SELECTION_PRIMARY); pPrivate->pActionRing = NULL; pPrivate->iNextActionID = 0; // pPrivate->pGameModeHelper = NULL; GtkTextIter oStartIter; gtk_text_buffer_get_start_iter(pPrivate->pBuffer, &oStartIter); pPrivate->pNewMark = gtk_text_buffer_create_mark(pPrivate->pBuffer, NULL, &oStartIter, TRUE); pPrivate->bFileModified = FALSE; GtkWidget *pScrolledWindow = gtk_scrolled_window_new(NULL, NULL); gtk_container_add(GTK_CONTAINER(pScrolledWindow), GTK_WIDGET(pPrivate->pTextView)); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(pScrolledWindow), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(pScrolledWindow), GTK_SHADOW_IN); gtk_box_pack_start(GTK_BOX(&(pSelf->parent.box)), pScrolledWindow, true, true, 0); gtk_widget_show_all(GTK_WIDGET(&(pSelf->parent.box))); } static void dasher_editor_internal_finalize(GObject *pObject) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pObject); EditorAction *pCurrentAction = pPrivate->pActionRing; if(pCurrentAction) { bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; dasher_action_deactivate(pCurrentAction->pAction); g_object_unref(G_OBJECT(pCurrentAction->pAction)); pCurrentAction = pCurrentAction->pNext; } } if(pPrivate->pBufferSet) g_object_unref(G_OBJECT(pPrivate->pBufferSet)); if(pPrivate->szFilename) g_free(pPrivate->szFilename); } /* Public methods */ DasherEditorInternal* dasher_editor_internal_new(void) { return DASHER_EDITOR_INTERNAL(g_object_new(DASHER_TYPE_EDITOR_INTERNAL, NULL)); } void dasher_editor_internal_initialise(DasherEditor *pSelf, DasherAppSettings *pAppSettings, DasherMain *pDasherMain, GtkBuilder *pXML, const gchar *szFullPath) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); pPrivate->pAppSettings = pAppSettings; pPrivate->pDasherMain = pDasherMain; dasher_editor_internal_handle_font(pSelf, dasher_app_settings_get_string(pPrivate->pAppSettings, APP_SP_EDIT_FONT)); GtkVBox *pActionPane = GTK_VBOX(gtk_builder_get_object(pXML, "vbox39")); pPrivate->pActionPane = pActionPane; // TODO: is this still needed? dasher_editor_internal_create_buffer(pSelf); dasher_editor_internal_setup_actions(pSelf); // TODO: see note in command_new method if(szFullPath) dasher_editor_internal_open(pSelf, szFullPath); else { dasher_editor_internal_generate_filename(pSelf); dasher_editor_internal_clear(pSelf, false); } // pPrivate->pGameModeHelper = GAME_MODE_HELPER(game_mode_helper_new(pXML, (void*)pSelf)); } static void dasher_editor_internal_clipboard(DasherEditor *pSelf, clipboard_action act) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkTextIter *start = new GtkTextIter; GtkTextIter *end = new GtkTextIter; gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), start, 0); gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), end, -1); gchar *the_text = gtk_text_buffer_get_text(pPrivate->pBuffer, start, end, TRUE); switch (act) { case CLIPBOARD_CUT: gtk_text_buffer_cut_clipboard(pPrivate->pBuffer, pPrivate->pTextClipboard, TRUE); break; case CLIPBOARD_COPY: gtk_text_buffer_copy_clipboard(pPrivate->pBuffer, pPrivate->pTextClipboard); break; case CLIPBOARD_PASTE: gtk_text_buffer_paste_clipboard(pPrivate->pBuffer, pPrivate->pTextClipboard, NULL, TRUE); break; case CLIPBOARD_COPYALL: gtk_clipboard_set_text(pPrivate->pTextClipboard, the_text, strlen(the_text)); gtk_clipboard_set_text(pPrivate->pPrimarySelection, the_text, strlen(the_text)); break; case CLIPBOARD_SELECTALL: dasher_editor_internal_select_all(pSelf); break; case CLIPBOARD_CLEAR: gtk_text_buffer_set_text(pPrivate->pBuffer, "", 0); break; } g_free(the_text); delete start; delete end; } void dasher_editor_internal_cleartext(DasherEditorInternal *pSelf) { dasher_editor_internal_clear((DasherEditor *)pSelf, true); } void dasher_editor_internal_handle_stop(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); // See if anything is set to auto: EditorAction *pCurrentAction = pPrivate->pActionRing; if(pCurrentAction) { bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; if(pCurrentAction->bAuto) dasher_action_execute(pCurrentAction->pAction, DASHER_EDITOR(pSelf), -1); pCurrentAction = pCurrentAction->pNext; } } } void dasher_editor_internal_handle_start(DasherEditor *pSelf) { // The edit box keeps track of where we started // TODO: This should be filtered through the buffer, rather than directly to the edit box // set_mark(); } /* TODO: This is obsolete - sort this out when commands are reconsidered */ void dasher_editor_internal_handle_control(DasherEditor *pSelf, int iNodeID) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(iNodeID == Dasher::CControlManager::CTL_USER + 1) dasher_editor_internal_clear(pSelf, false); // Clear node is a special case (it shouldn't be) else { EditorAction *pCurrentAction = pPrivate->pActionRing; bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; if((iNodeID >= pCurrentAction->iControlID) && (iNodeID <= pCurrentAction->iControlID + pCurrentAction->iNSub)) { dasher_action_execute(pCurrentAction->pAction, DASHER_EDITOR(pSelf), iNodeID - pCurrentAction->iControlID - 1); // dasher_editor_internal_clear(pSelf, true); } pCurrentAction = pCurrentAction->pNext; } } // TODO: Think about changing signals so we don't need to do this translation struct SControlMap { int iEvent; int iDir; int iDist; bool bDelete; }; static struct SControlMap sMap[] = { {Dasher::CControlManager::CTL_MOVE_FORWARD_CHAR, EDIT_FORWARDS, EDIT_CHAR, false}, {Dasher::CControlManager::CTL_MOVE_FORWARD_WORD, EDIT_FORWARDS, EDIT_WORD, false}, {Dasher::CControlManager::CTL_MOVE_FORWARD_LINE, EDIT_FORWARDS, EDIT_LINE, false}, {Dasher::CControlManager::CTL_MOVE_FORWARD_FILE, EDIT_FORWARDS, EDIT_FILE, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_CHAR, EDIT_BACKWARDS, EDIT_CHAR, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_WORD, EDIT_BACKWARDS, EDIT_WORD, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_LINE, EDIT_BACKWARDS, EDIT_LINE, false}, {Dasher::CControlManager::CTL_MOVE_BACKWARD_FILE, EDIT_BACKWARDS, EDIT_FILE, false}, {Dasher::CControlManager::CTL_DELETE_FORWARD_CHAR, EDIT_FORWARDS, EDIT_CHAR, true}, {Dasher::CControlManager::CTL_DELETE_FORWARD_WORD, EDIT_FORWARDS, EDIT_WORD, true}, {Dasher::CControlManager::CTL_DELETE_FORWARD_LINE, EDIT_FORWARDS, EDIT_LINE, true}, {Dasher::CControlManager::CTL_DELETE_FORWARD_FILE, EDIT_FORWARDS, EDIT_FILE, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_CHAR, EDIT_BACKWARDS, EDIT_CHAR, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_WORD, EDIT_BACKWARDS, EDIT_WORD, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_LINE, EDIT_BACKWARDS, EDIT_LINE, true}, {Dasher::CControlManager::CTL_DELETE_BACKWARD_FILE, EDIT_BACKWARDS, EDIT_FILE, true} }; if(pPrivate->pBufferSet) { for(unsigned int i(0); i < sizeof(sMap)/sizeof(struct SControlMap); ++i) { if(sMap[i].iEvent == iNodeID) { if(sMap[i].bDelete) idasher_buffer_set_edit_delete(pPrivate->pBufferSet, sMap[i].iDir, sMap[i].iDist); else idasher_buffer_set_edit_move(pPrivate->pBufferSet, sMap[i].iDir, sMap[i].iDist); } } } } void dasher_editor_internal_action_button(DasherEditor *pSelf, DasherAction *pAction) { if(pAction) { dasher_action_execute(pAction, DASHER_EDITOR(pSelf), -1); dasher_editor_internal_clear(pSelf, true); } else { // Clear button dasher_editor_internal_clear(pSelf, false); } } static void dasher_editor_internal_clear(DasherEditor *pSelf, gboolean bStore) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(IS_DASHER_INTERNAL_BUFFER(pPrivate->pBufferSet)) dasher_internal_buffer_clear(DASHER_INTERNAL_BUFFER(pPrivate->pBufferSet)); } void dasher_editor_internal_actions_start(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); pPrivate->bActionIterStarted = false; pPrivate->pActionIter = pPrivate->pActionRing; } bool dasher_editor_internal_actions_more(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return(!pPrivate->bActionIterStarted || (pPrivate->pActionIter != pPrivate->pActionRing)); } void dasher_editor_internal_actions_get_next(DasherEditor *pSelf, const gchar **szName, gint *iID, gboolean *bShow, gboolean *bControl, gboolean *bAuto) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); *szName = dasher_action_get_name(pPrivate->pActionIter->pAction); *iID = pPrivate->pActionIter->iID; *bShow = pPrivate->pActionIter->bShow; *bControl = pPrivate->pActionIter->bControl; *bAuto = pPrivate->pActionIter->bAuto; pPrivate->pActionIter = pPrivate->pActionIter->pNext; pPrivate->bActionIterStarted = true; } void dasher_editor_internal_action_set_show(DasherEditor *pSelf, int iActionID, bool bValue) { EditorAction *pAction; pAction = dasher_editor_internal_get_action_by_id(pSelf, iActionID); if(pAction) { pAction->bShow = bValue; dasher_editor_internal_check_activity(pSelf, pAction); dasher_editor_internal_rebuild_action_pane(pSelf); dasher_editor_internal_action_save_state(pSelf, pAction); } } void dasher_editor_internal_action_set_control(DasherEditor *pSelf, int iActionID, bool bValue) { // TODO: Need to actually change behaviour in resonse to these calls // TODO: Reimplement // EditorAction *pAction; // pAction = dasher_editor_internal_get_action_by_id(pSelf, iActionID); // if(pAction) { // pAction->bControl = bValue; // dasher_editor_internal_check_activity(pSelf, pAction); // if(bValue) // gtk_dasher_control_connect_node(GTK_DASHER_CONTROL(pDasherWidget), pAction->iControlID, Dasher::CControlManager::CTL_USER, -2); // else // gtk_dasher_control_disconnect_node(GTK_DASHER_CONTROL(pDasherWidget), pAction->iControlID, Dasher::CControlManager::CTL_USER); // dasher_editor_internal_action_save_state(pSelf, pAction); // } } void dasher_editor_internal_action_set_auto(DasherEditor *pSelf, int iActionID, bool bValue) { EditorAction *pAction; pAction = dasher_editor_internal_get_action_by_id(pSelf, iActionID); if(pAction) { pAction->bAuto = bValue; dasher_editor_internal_check_activity(pSelf, pAction); dasher_editor_internal_action_save_state(pSelf, pAction); } } void dasher_editor_internal_grab_focus(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(pPrivate->pTextView) gtk_widget_grab_focus(GTK_WIDGET(pPrivate->pTextView)); } static void dasher_editor_internal_create_buffer(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); /* Make an external buffer anyway, for keyboard command */ /* TODO: Review this */ if(!(pPrivate->pExternalBuffer)) pPrivate->pExternalBuffer = IDASHER_BUFFER_SET(dasher_external_buffer_new()); if(!(pPrivate->pBufferSet)) pPrivate->pBufferSet = IDASHER_BUFFER_SET(dasher_internal_buffer_new(pPrivate->pTextView)); // TODO: Fix this g_signal_connect(G_OBJECT(pPrivate->pBufferSet), "offset_changed", G_CALLBACK(context_changed_handler), pSelf); g_signal_connect(G_OBJECT(pPrivate->pBufferSet), "buffer_changed", G_CALLBACK(buffer_changed_handler), pSelf); } void dasher_editor_internal_output(DasherEditor *pSelf, const gchar *szText, int iOffset) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); // TODO: tidy this up, actionlookup by name, more flexible // definition of space // Python scripting? if(!strcmp(szText, " ")) { gboolean bActionIterStarted = false; EditorAction *pActionIter = pPrivate->pActionRing; while((pActionIter != pPrivate->pActionRing) || !bActionIterStarted) { bActionIterStarted = true; if(!strcmp(dasher_action_get_name(pActionIter->pAction), "Speak")) { dasher_action_preview(pActionIter->pAction, DASHER_EDITOR(pSelf)); } pActionIter = pActionIter->pNext; } } if(pPrivate->pBufferSet) idasher_buffer_set_insert(pPrivate->pBufferSet, szText, iOffset); // if(pPrivate->pGameModeHelper) // game_mode_helper_output(pPrivate->pGameModeHelper, szText); pPrivate->bFileModified = TRUE; } void dasher_editor_internal_delete(DasherEditor *pSelf, int iLength, int iOffset) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(pPrivate->pBufferSet) idasher_buffer_set_delete(pPrivate->pBufferSet, iLength, iOffset); // if(pPrivate->pGameModeHelper) // game_mode_helper_delete(pPrivate->pGameModeHelper, iLength); pPrivate->bFileModified = TRUE; } const gchar * dasher_editor_internal_get_context(DasherEditor *pSelf, int iOffset, int iLength) { // TODO: Check where this function is used DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); const gchar *szContext; if(pPrivate->pBufferSet) szContext = idasher_buffer_set_get_context(pPrivate->pBufferSet, iOffset, iLength); else szContext = ""; // TODO: reimplement // if(szContext && (strlen(szContext) > 0)) // gtk_dasher_control_set_context( GTK_DASHER_CONTROL(pDasherWidget), szContext ); return szContext; } gint dasher_editor_internal_get_offset(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return idasher_buffer_set_get_offset(pPrivate->pBufferSet); } static void dasher_editor_internal_generate_filename(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); gchar *szNewFilename = NULL; if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_TIME_STAMP )) { // Build a filename based on the current time and date tm *t_struct; time_t ctime; char cwd[1000]; char tbuffer[200]; ctime = time(NULL); t_struct = localtime(&ctime); getcwd(cwd, 1000); snprintf(tbuffer, 200, "dasher-%04d%02d%02d-%02d%02d.txt", (t_struct->tm_year + 1900), (t_struct->tm_mon + 1), t_struct->tm_mday, t_struct->tm_hour, t_struct->tm_min); szNewFilename = g_build_path("/", cwd, tbuffer, NULL); } dasher_editor_internal_set_filename(pSelf, szNewFilename); g_free(szNewFilename); } static void dasher_editor_internal_open(DasherEditor *pSelf, const gchar *szFilename) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); gsize size; gchar *buffer; #ifdef HAVE_GIO if(!dasher_editor_internal_gvfs_open_file(pSelf, szFilename, &buffer, &size)) { return; } #else if(!dasher_editor_internal_unix_vfs_open_file(pSelf, szFilename, &buffer, &size)) { return; } #endif // FIXME - REIMPLEMENT (shouldn't happen through core) // dasher_clear(); if(size != 0) { // Don't attempt to insert new text if the file is empty as it makes // GTK cry if(!g_utf8_validate(buffer, size, NULL)) { // PRLW: size as gssize = signed int // It's not UTF8, so we do the best we can... // If there are zero bytes in the file then we have a problem - // for now, just assert that we can't load these files. for(gsize i = 0; i < size; ++i) if(buffer[i] == 0) { // GtkWidget *pErrorBox = gtk_message_dialog_new(GTK_WINDOW(window), // GTK_DIALOG_MODAL, // GTK_MESSAGE_ERROR, // GTK_BUTTONS_OK, // "Could not open the file \"%s\". Please note that Dasher cannot load files containing binary data, which may be the cause of this error.\n", // myfilename); GtkWidget *pErrorBox = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open the file \"%s\". Please note that Dasher cannot load files containing binary data, which may be the cause of this error.\n", szFilename); gtk_dialog_run(GTK_DIALOG(pErrorBox)); gtk_widget_destroy(pErrorBox); return; } pPrivate->bFileModified = TRUE; gsize iNewSize; gchar *buffer2 = g_strdup(g_locale_to_utf8(buffer, size, NULL, &iNewSize, NULL)); // TODO: This function probably needs more thought // const gchar *pEnd; //gboolean bValid = g_utf8_validate(buffer2, -1, &pEnd); g_free(buffer); buffer = buffer2; size = iNewSize; } gtk_text_buffer_insert_at_cursor(GTK_TEXT_BUFFER(pPrivate->pBuffer), buffer, size); gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(pPrivate->pTextView), gtk_text_buffer_get_insert(GTK_TEXT_BUFFER(pPrivate->pBuffer))); } dasher_editor_internal_set_filename(pSelf, szFilename); } static bool dasher_editor_internal_save_as(DasherEditor *pSelf, const gchar *szFilename, bool bAppend) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); unsigned long long length; gchar *inbuffer, *outbuffer = NULL; // gsize bytes_read, bytes_written; gsize bytes_written; // GError *error = NULL; GtkTextIter *start, *end; // GIConv cd; start = new GtkTextIter; end = new GtkTextIter; gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), start, 0); gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), end, -1); inbuffer = gtk_text_iter_get_slice(start, end); // g_message("String %s", inbuffer); //length = gtk_text_iter_get_offset(end) - gtk_text_iter_get_offset(start); //length = gtk_text_buffer_get_byte_count(GTK_TEXT_BUFFER(the_text_buffer)); // I'm pretty certain that this is null terminated, but not 100% length = strlen(inbuffer); // g_message("Length is %d", length); outbuffer = (char *)malloc((length + 1) * sizeof(gchar)); memcpy((void *)outbuffer, (void *)inbuffer, length * sizeof(gchar)); outbuffer[length] = 0; g_free(inbuffer); inbuffer = outbuffer; outbuffer = NULL; // switch (fileencoding) { // case Dasher::Opts::UserDefault: // case Dasher::Opts::AlphabetDefault: // //FIXME - need to call GetAlphabetType and do appropriate stuff regarding // //the character set. Arguably we should always be saving in either UTF-8 or // //the user's locale (which may, of course, be UTF-8) because otherwise // //we're going to read in rubbish, and we shouldn't be encouraging weird // //codepage madness any further // //FIXME - error handling // outbuffer = g_locale_from_utf8(inbuffer, -1, &bytes_read, &bytes_written, &error); // if(outbuffer == NULL) { // // We can't represent the text in the current locale, so fall back to // // UTF-8 // outbuffer = inbuffer; // bytes_written = length; // } // case Dasher::Opts::UTF8: // outbuffer = inbuffer; // bytes_written = length; // break; // // Does /anyone/ want to save text files in UTF16? // // (in any case, my opinions regarding encouragement of data formats with // // endianness damage are almost certainly unprintable) // case Dasher::Opts::UTF16LE: // cd = g_iconv_open("UTF16LE", "UTF8"); // outbuffer = g_convert_with_iconv(inbuffer, -1, cd, &bytes_read, &bytes_written, &error); // break; // case Dasher::Opts::UTF16BE: // cd = g_iconv_open("UTF16BE", "UTF8"); // outbuffer = g_convert_with_iconv(inbuffer, -1, cd, &bytes_read, &bytes_written, &error); // break; // default: outbuffer = inbuffer; bytes_written = length; // } #ifdef HAVE_GIO if(!dasher_editor_internal_gvfs_save_file(pSelf, szFilename, outbuffer, bytes_written, bAppend)) { return false; } #else if(!dasher_editor_internal_unix_vfs_save_file(pSelf, szFilename, outbuffer, bytes_written, bAppend)) { return false; } #endif pPrivate->bFileModified = FALSE; dasher_editor_internal_set_filename(pSelf, szFilename); return true; } // void // dasher_editor_internal_start_tutorial(DasherEditor *pSelf) { // DasherEditorInternalPrivate *pPrivate = (DasherEditorInternalPrivate *)(pSelf->private_data); // // TODO: reimplement // // pPrivate->pGameModeHelper = GAME_MODE_HELPER(game_mode_helper_new(GTK_DASHER_CONTROL(pDasherWidget))); // } gboolean dasher_editor_internal_command(DasherEditor *pSelf, const gchar *szCommand) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); if(!strcmp(szCommand, "action_new")) { //select_new_file dasher_editor_internal_command_new(pSelf); return TRUE; } if(!strcmp(szCommand, "action_open")) { //select open file dasher_editor_internal_command_open(pSelf); return TRUE; } if(!strcmp(szCommand, "action_save")) { //save_file dasher_editor_internal_command_save(pSelf, FALSE, FALSE); return TRUE; } if(!strcmp(szCommand, "action_saveas")) { // select_save_file_as dasher_editor_internal_command_save(pSelf, TRUE, FALSE); return TRUE; } if(!strcmp(szCommand, "action_append")) { // select_append_file dasher_editor_internal_command_save(pSelf, TRUE, TRUE); return TRUE; } if(!strcmp(szCommand, "action_cut")) { // clipboard_cut dasher_editor_internal_clipboard(pSelf, CLIPBOARD_CUT); return TRUE; } if(!strcmp(szCommand, "action_copy")) { // clipboard_copy dasher_editor_internal_clipboard(pSelf, CLIPBOARD_COPY); return TRUE; } if(!strcmp(szCommand, "action_copyall")) { // clipboard_copyall dasher_editor_internal_clipboard(pSelf, CLIPBOARD_COPYALL); return TRUE; } if(!strcmp(szCommand, "action_paste")) { // clipboard_paste dasher_editor_internal_clipboard(pSelf, CLIPBOARD_PASTE); return TRUE; } // TODO: This isn't actually accessible from anywhere if(!strcmp(szCommand, "action_selectall")) { // clipboard_paste dasher_editor_internal_clipboard(pSelf, CLIPBOARD_SELECTALL); return TRUE; } + + if(!strcmp(szCommand, "action_toggle_game_mode")) { //toggle game mode + dasher_main_toggle_game_mode((DASHER_MAIN_GET_PRIVATE(pPrivate->pDasherMain))->pAppSettings); + return TRUE; + } /* TODO: We need a rethink here */ const gchar *szForwardCommand = NULL; gint iSubCommand = 0; if(!strcmp(szCommand, "speakall")) { szForwardCommand = "Speak"; iSubCommand = 0; } else if(!strcmp(szCommand, "speaklast")) { szForwardCommand = "Speak"; iSubCommand = 1; } else if(!strcmp(szCommand, "speakrepeat")) { szForwardCommand = "Speak"; iSubCommand = 2; } if(szForwardCommand) { gboolean bActionIterStarted = false; EditorAction *pActionIter = pPrivate->pActionRing; while((pActionIter != pPrivate->pActionRing) || !bActionIterStarted) { bActionIterStarted = true; if(!strcmp(dasher_action_get_name(pActionIter->pAction), szForwardCommand)) { dasher_action_execute(pActionIter->pAction, DASHER_EDITOR(pSelf), iSubCommand); return TRUE; } pActionIter = pActionIter->pNext; } return TRUE; } return FALSE; } void dasher_editor_internal_handle_font(DasherEditor *pSelf, const gchar *szFont) { if(strcmp(szFont, "")) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); PangoFontDescription *pFD = pango_font_description_from_string(szFont); gtk_widget_modify_font(GTK_WIDGET(pPrivate->pTextView), pFD); } } gboolean dasher_editor_internal_file_changed(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return pPrivate->bFileModified; } const gchar * dasher_editor_internal_get_filename(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); return pPrivate->szFilename; } // TODO: We shouldn't need to know about the buffer here - make this a method of the buffer set const gchar * dasher_editor_internal_get_all_text(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkTextIter oStart; GtkTextIter oEnd; gtk_text_buffer_get_start_iter(pPrivate->pBuffer, &oStart); gtk_text_buffer_get_end_iter(pPrivate->pBuffer, &oEnd); pPrivate->pNewMark = gtk_text_buffer_create_mark(pPrivate->pBuffer, NULL, &oEnd, TRUE); return gtk_text_buffer_get_text(pPrivate->pBuffer, &oStart, &oEnd, false ); } const gchar * dasher_editor_internal_get_new_text(DasherEditor *pSelf) { // TODO: Implement this properly DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkTextIter oStart; GtkTextIter oEnd; gtk_text_buffer_get_end_iter(pPrivate->pBuffer, &oEnd); gtk_text_buffer_get_iter_at_mark(pPrivate->pBuffer, &oStart, pPrivate->pNewMark); const gchar *szRetVal = gtk_text_buffer_get_text(pPrivate->pBuffer, &oStart, &oEnd, false ); pPrivate->pNewMark = gtk_text_buffer_create_mark(pPrivate->pBuffer, NULL, &oEnd, TRUE); return szRetVal; } /* Private methods */ static void dasher_editor_internal_select_all(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkTextIter *start, *end; start = new GtkTextIter; end = new GtkTextIter; gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), start, 0); gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(pPrivate->pBuffer), end, -1); GtkTextMark *selection = gtk_text_buffer_get_mark(pPrivate->pBuffer, "selection_bound"); GtkTextMark *cursor = gtk_text_buffer_get_mark(pPrivate->pBuffer, "insert"); gtk_text_buffer_move_mark(pPrivate->pBuffer, selection, start); gtk_text_buffer_move_mark(pPrivate->pBuffer, cursor, end); delete start; delete end; } static void dasher_editor_internal_setup_actions(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); // TODO: Activate and deactivate methods for actions // TODO: Clear shouldn't be a special case (include support for false in clear method) #ifdef GNOME_SPEECH dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_speech_new())); #endif dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_keyboard_new(pPrivate->pExternalBuffer))); #ifdef WITH_MAEMO dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_keyboard_maemo_new())); #else // dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_copy_new(pSelf))); GDir *pDirectory; G_CONST_RETURN gchar *szFilename; gchar *szUserScriptDir = new gchar[strlen(dasher_app_settings_get_string(pPrivate->pAppSettings, SP_USER_LOC))+9]; strcpy(szUserScriptDir, dasher_app_settings_get_string(pPrivate->pAppSettings, SP_USER_LOC)); strcat(szUserScriptDir, "scripts/"); pDirectory = g_dir_open(szUserScriptDir, 0, NULL); if(pDirectory) { while((szFilename = g_dir_read_name(pDirectory))) { dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_script_new(szUserScriptDir, szFilename))); } g_dir_close(pDirectory); } delete[] szUserScriptDir; gchar *szSystemScriptDir = new gchar[strlen(dasher_app_settings_get_string(pPrivate->pAppSettings, SP_SYSTEM_LOC))+9]; strcpy(szSystemScriptDir, dasher_app_settings_get_string(pPrivate->pAppSettings, SP_SYSTEM_LOC)); strcat(szSystemScriptDir, "scripts/"); pDirectory = g_dir_open(szSystemScriptDir, 0, NULL); if(pDirectory) { while((szFilename = g_dir_read_name(pDirectory))) { dasher_editor_internal_add_action(pSelf, DASHER_ACTION(dasher_action_script_new(szSystemScriptDir, szFilename))); } g_dir_close(pDirectory); } delete[] szSystemScriptDir; #endif // TODO: Reimplement // // TODO: This doesn't get re-called if the preferences change // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER, "Actions", -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER, Dasher::CControlManager::CTL_ROOT, -2); // int iControlOffset(1); // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, "Clear", -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, Dasher::CControlManager::CTL_USER, -2); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), -1, Dasher::CControlManager::CTL_USER + iControlOffset, -2); // ++iControlOffset; // EditorAction *pCurrentAction = pPrivate->pActionRing; // bool bStarted = false; // while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { // bStarted = true; // if(pCurrentAction->bControl) { // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, dasher_action_get_name(pCurrentAction->pAction), -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset, Dasher::CControlManager::CTL_USER, -2); // int iNSub(dasher_action_get_sub_count(pCurrentAction->pAction)); // if(iNSub == 0) { // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), -1, Dasher::CControlManager::CTL_USER + iControlOffset, -2); // } // else { // for(int i(0); i < iNSub; ++i) { // gtk_dasher_control_register_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset + i + 1, dasher_action_get_sub_name(pCurrentAction->pAction, i), -1 ); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), Dasher::CControlManager::CTL_USER + iControlOffset + i + 1, Dasher::CControlManager::CTL_USER + iControlOffset, -2); // gtk_dasher_control_connect_node( GTK_DASHER_CONTROL(pDasherWidget), -1, Dasher::CControlManager::CTL_USER + iControlOffset + i + 1, -2); // } // } // pCurrentAction->iControlID = Dasher::CControlManager::CTL_USER + iControlOffset; // pCurrentAction->iNSub = iNSub; // iControlOffset += iNSub + 1; // } // pCurrentAction = pCurrentAction->pNext; // } #ifndef WITH_MAEMOFULLSCREEN // dasher_editor_internal_rebuild_action_pane(pSelf); #endif } static void dasher_editor_internal_add_action(DasherEditor *pSelf, DasherAction *pNewAction) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); EditorAction *pNewEditorAction = new EditorAction; pNewEditorAction->pAction = pNewAction; pNewEditorAction->iID = pPrivate->iNextActionID; ++pPrivate->iNextActionID; gchar szRegistryName[256]; strncpy(szRegistryName, "Action_", 256); strncat(szRegistryName, dasher_action_get_name(pNewEditorAction->pAction), 255 - strlen(szRegistryName)); for(unsigned int i(0); i < strlen(szRegistryName); ++i) if(szRegistryName[i] == ' ') szRegistryName[i] = '_'; gint iState; if(!dasher_app_settings_get_free_long(pPrivate->pAppSettings, szRegistryName, iState)) { if(!strcmp(dasher_action_get_name(pNewEditorAction->pAction), "Speak")) iState = 0; else iState = ACTION_STATE_SHOW | ACTION_STATE_CONTROL; dasher_app_settings_set_free_long(pPrivate->pAppSettings, szRegistryName, iState); } pNewEditorAction->bShow = iState & ACTION_STATE_SHOW; pNewEditorAction->bControl = iState & ACTION_STATE_CONTROL; pNewEditorAction->bAuto = iState & ACTION_STATE_AUTO; dasher_editor_internal_check_activity(pSelf, pNewEditorAction); if(pPrivate->pActionRing) { pNewEditorAction->pNext = pPrivate->pActionRing; pNewEditorAction->pPrevious = pPrivate->pActionRing->pPrevious; pPrivate->pActionRing->pPrevious->pNext = pNewEditorAction; pPrivate->pActionRing->pPrevious = pNewEditorAction; } else { pNewEditorAction->pNext = pNewEditorAction; pNewEditorAction->pPrevious = pNewEditorAction; } pPrivate->pActionRing = pNewEditorAction; // TODO: Reimplement // if(iState & ACTION_STATE_SHOW) // gtk_dasher_control_add_action_button(GTK_DASHER_CONTROL(pDasherWidget), dasher_action_get_name(pNewEditorAction->pAction)); } static EditorAction * dasher_editor_internal_get_action_by_id(DasherEditor *pSelf, int iID){ DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); EditorAction *pCurrentAction = pPrivate->pActionRing; bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; if(pCurrentAction->iID == iID) return pCurrentAction; pCurrentAction = pCurrentAction->pNext; } return 0; } static void dasher_editor_internal_rebuild_action_pane(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); // Delete any existing widgets gtk_container_foreach(GTK_CONTAINER(pPrivate->pActionPane), delete_children_callback, 0); // Add the cancel button GtkButton *pNewButton = GTK_BUTTON(gtk_button_new_with_label("Clear")); gtk_widget_show(GTK_WIDGET(pNewButton)); void **pUserData = new void *[2]; pUserData[0] = (void *)pSelf; pUserData[1] = 0; g_signal_connect(G_OBJECT(pNewButton), "clicked", G_CALLBACK(action_button_callback), pUserData); #ifdef WITH_MAEMO // For Maemo we want the packing to expand gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), true, true, 0); #else gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), false, false, 0); #endif EditorAction *pCurrentAction = pPrivate->pActionRing; bool bStarted = false; while(!bStarted || (pCurrentAction != pPrivate->pActionRing)) { bStarted = true; if(pCurrentAction->bShow) { GtkButton *pNewButton = GTK_BUTTON(gtk_button_new_with_label(dasher_action_get_name(pCurrentAction->pAction))); gtk_widget_show(GTK_WIDGET(pNewButton)); pUserData = new void *[2]; pUserData[0] = (void *)pSelf; pUserData[1] = (void *)(pCurrentAction->pAction); g_signal_connect(G_OBJECT(pNewButton), "clicked", G_CALLBACK(action_button_callback), pUserData); #ifdef WITH_MAEMO // For Maemo we want the packing to expand gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), true, true, 0); #else gtk_box_pack_start(GTK_BOX(pPrivate->pActionPane), GTK_WIDGET(pNewButton), false, false, 0); #endif } pCurrentAction = pCurrentAction->pNext; } } // TODO: This shouldn't be a part of the editor //static void //dasher_editor_internal_display_message(DasherEditor *pSelf, DasherMessageInfo *pMessageInfo) { // GtkMessageDialog *pDialog = GTK_MESSAGE_DIALOG(gtk_message_dialog_new(0, GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, pMessageInfo->szMessage)); // gtk_dialog_run(GTK_DIALOG(pDialog)); // gtk_widget_destroy(GTK_WIDGET(pDialog)); //} static void dasher_editor_internal_check_activity(DasherEditor *pSelf, EditorAction *pAction) { gboolean bNeedActive(pAction->bShow || pAction->bControl || pAction->bAuto); gboolean bActive(dasher_action_get_active(pAction->pAction)); if(bNeedActive && !bActive) dasher_action_activate(pAction->pAction); else if(!bNeedActive && bActive) dasher_action_deactivate(pAction->pAction); } static void dasher_editor_internal_action_save_state(DasherEditor *pSelf, EditorAction *pAction) { gchar szRegistryName[256]; strncpy(szRegistryName, "Action_", 256); strncat(szRegistryName, dasher_action_get_name(pAction->pAction), 255 - strlen(szRegistryName)); for(unsigned int i(0); i < strlen(szRegistryName); ++i) if(szRegistryName[i] == ' ') szRegistryName[i] = '_'; gint iState = 0; if(pAction->bShow) iState += ACTION_STATE_SHOW; if(pAction->bControl) iState += ACTION_STATE_CONTROL; if(pAction->bAuto) iState += ACTION_STATE_AUTO; DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); dasher_app_settings_set_free_long(pPrivate->pAppSettings, szRegistryName, iState); } static void dasher_editor_internal_command_new(DasherEditor *pSelf) { dasher_editor_internal_new_buffer(pSelf, NULL); } static void dasher_editor_internal_command_open(DasherEditor *pSelf) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); GtkWidget *pTopLevel = gtk_widget_get_toplevel(GTK_WIDGET(pPrivate->pTextView)); GtkWidget *filesel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pTopLevel), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef HAVE_GIO gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(filesel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) { #ifdef HAVE_GIO char *filename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(filesel)); #else char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel)); #endif dasher_editor_internal_new_buffer(pSelf, filename); g_free(filename); } gtk_widget_destroy(filesel); } static void dasher_editor_internal_command_save(DasherEditor *pSelf, gboolean bPrompt, gboolean bAppend) { DasherEditorInternalPrivate *pPrivate = DASHER_EDITOR_INTERNAL_GET_PRIVATE(pSelf); gchar *szFilename = NULL; // Hmm... this makes no sense - surely this always evaluates to true? if(bPrompt || !szFilename) { GtkWidget *pTopLevel = gtk_widget_get_toplevel(GTK_WIDGET(pPrivate->pTextView)); GtkWidget *filesel = gtk_file_chooser_dialog_new(_("Select File"), GTK_WINDOW(pTopLevel), GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); #ifdef HAVE_GIO gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(filesel), FALSE); #endif if(gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) { #ifdef HAVE_GIO szFilename = gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(filesel)); #else szFilename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel)); #endif } else { gtk_widget_destroy(filesel); return; } gtk_widget_destroy(filesel); } else { szFilename = g_strdup(pPrivate->szFilename); } dasher_editor_internal_save_as(pSelf, szFilename, bAppend); g_free(szFilename); } #ifdef HAVE_GIO static void dasher_editor_internal_gvfs_print_error(DasherEditor *pSelf, GError *error, const char *myfilename) { // Turns a GVFS error into English GtkWidget *error_dialog; error_dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open the file \"%s\"\n%s\n", myfilename, error->message); gtk_dialog_set_default_response(GTK_DIALOG(error_dialog), GTK_RESPONSE_OK); gtk_window_set_resizable(GTK_WINDOW(error_dialog), FALSE); gtk_dialog_run(GTK_DIALOG(error_dialog)); gtk_widget_destroy(error_dialog); return; } static gboolean dasher_editor_internal_gvfs_open_file(DasherEditor *pSelf, const char *uri, gchar **buffer, gsize *size) { GFile *file; GFileInputStream *read_handle; GError *error; GFileInfo *info; gssize bytes_read; file = g_file_new_for_uri (uri); read_handle = g_file_read (file, NULL, &error); /* If URI didn't work, try path */ if (read_handle == NULL) { // PRLW: g_object_unref isn't actually stipulated by g_file_new_for_uri g_object_unref (file); file = g_file_new_for_path (uri); read_handle = g_file_read (file, NULL, &error); } if (read_handle == NULL) { dasher_editor_internal_gvfs_print_error (pSelf, error, uri); g_object_unref (file); return FALSE; } info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NONE, NULL, &error); if (info == NULL) { dasher_editor_internal_gvfs_print_error (pSelf, error, uri); g_input_stream_close (G_INPUT_STREAM(read_handle), NULL, &error); diff --git a/Src/Gtk2/dasher_main.cpp b/Src/Gtk2/dasher_main.cpp index c25396f..0d330df 100644 --- a/Src/Gtk2/dasher_main.cpp +++ b/Src/Gtk2/dasher_main.cpp @@ -1,625 +1,578 @@ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <gdk/gdk.h> #include <gdk/gdkx.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #ifdef WITH_MAEMOFULLSCREEN #include <hildon-widgets/hildon-program.h> #endif #include <unistd.h> #include "GtkDasherControl.h" -#include "KeyboardHelper.h" -#include "Preferences.h" #include "dasher_lock_dialogue.h" #ifdef WITH_MAEMO #include "dasher_maemo_helper.h" #endif #include "dasher_main.h" -#include "DasherAppSettings.h" #include "dasher_editor_internal.h" #include "dasher_editor_external.h" /* Static instance of singleton, USE SPARINGLY */ static DasherMain *g_pDasherMain = NULL; // TODO: The following global variable makes control mode editing work // - this needs to be sorted out properly. static gboolean g_bSend = true; -struct _DasherMainPrivate { - GtkBuilder *pXML; - GtkBuilder *pPrefXML; - - // Child objects owned here - DasherAppSettings *pAppSettings; - DasherPreferencesDialogue *pPreferencesDialogue; - DasherEditor *pEditor; - - CKeyboardHelper *pKeyboardHelper; - - // Various widgets which need to be cached: - // GtkWidget *pBufferView; - GtkPaned *pDivider; - GtkWindow *pMainWindow; - GtkWidget *pToolbar; - GtkSpinButton *pSpeedBox; - GtkWidget *pAlphabetCombo; - GtkWidget *pStatusControl; - GtkWidget *pDasherWidget; - - GtkListStore *pAlphabetList; - GtkAccelGroup *pAccel; - gulong iAlphabetComboHandler; - - // Widgets used for maemo -#ifdef WITH_MAEMO - DasherMaemoHelper *pMaemoHelper; -#ifdef WITH_MAEMOFULLSCREEN - HildonProgram *pProgram; - HildonWindow *pHWindow; -#endif -#endif - - // Properties of the main window - int iWidth; - int iHeight; - bool bWidgetsInitialised; -}; - -typedef struct _DasherMainPrivate DasherMainPrivate; - -// TODO: Make sure this is actually used -#define DASHER_MAIN_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), DASHER_TYPE_MAIN, DasherMainPrivate)) - enum { REALIZED, SIGNAL_NUM }; static guint dasher_main_signals[SIGNAL_NUM] = { 0 }; G_DEFINE_TYPE(DasherMain, dasher_main, G_TYPE_OBJECT); static void dasher_main_finalize(GObject *pObject); /* Private member functions */ static void dasher_main_setup_window_state(DasherMain *pSelf); static void dasher_main_setup_window_style(DasherMain *pSelf); static void dasher_main_setup_internal_layout(DasherMain *pSelf); static void dasher_main_set_window_title(DasherMain *pSelf); /* ... Table based menu/toolbar commands */ static void dasher_main_command_import(DasherMain *pSelf); static void dasher_main_command_quit(DasherMain *pSelf); static void dasher_main_command_preferences(DasherMain *pSelf); static void dasher_main_command_preferences_alphabet(DasherMain *pSelf); static void dasher_main_command_tutorial(DasherMain *pSelf); static void dasher_main_command_help(DasherMain *pSelf); static void dasher_main_command_about(DasherMain *pSelf); /* c.f. WRAP_CPP_CB below */ extern "C" void dasher_main_cb_import(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_quit(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_preferences(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_help(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_about(GtkAction*, DasherMain*); extern "C" void dasher_main_cb_editor(GtkAction*, DasherMain*); +extern "C" void dasher_main_cb_toggle_game_mode(GtkAction*, DasherMain*); static gboolean dasher_main_speed_changed(DasherMain *pSelf); static void dasher_main_alphabet_combo_changed(DasherMain *pSelf); // TODO: populate speed slider static void dasher_main_populate_alphabet_combo(DasherMain *pSelf); /* TODO: order these in file */ static GtkBuilder *dasher_main_open_gui_xml(DasherMain *, const char *); static void dasher_main_load_interface(DasherMain *pSelf); static void dasher_main_create_preferences(DasherMain *pSelf); static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter); static void dasher_main_load_state(DasherMain *pSelf); static void dasher_main_save_state(DasherMain *pSelf); static void dasher_main_setup_window(DasherMain *pSelf); static void dasher_main_populate_controls(DasherMain *pSelf); static void dasher_main_connect_control(DasherMain *pSelf); static gboolean dasher_main_command(DasherMain *pSelf, const gchar *szCommand); static gint dasher_main_lookup_key(DasherMain *pSelf, guint iKeyVal); /* TODO: Various functions which haven't yet been rationalised */ gboolean grab_focus(); /* ... Message handling from main window widgets */ extern "C" void speed_changed(GtkWidget *pWidget, gpointer user_data); extern "C" void alphabet_combo_changed(GtkWidget *pWidget, gpointer pUserData); extern "C" void dasher_main_cb_filename_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_buffer_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" void dasher_main_cb_context_changed(DasherEditor *pEditor, gpointer pUserData); extern "C" gboolean dasher_main_cb_window_close(GtkWidget *pWidget, gpointer pUserData); extern "C" void parameter_notification(GtkDasherControl *pDasherControl, gint iParameter, gpointer data); /* ... Focus management and event forwarding */ extern "C" bool focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" bool edit_focus_in_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gboolean take_real_focus(GtkWidget *widget, GdkEventFocus *event, gpointer user_data); extern "C" gboolean edit_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean edit_key_release(GtkWidget *widget, GdkEventKey *event, gpointer user_data); /* ... Temporary test/debug functions */ extern "C" gboolean test_focus_handler(GtkWidget *pWidget, GtkDirectionType iDirection, gpointer *pUserData); extern "C" void handle_context_request(GtkDasherControl * pDasherControl, gint iOffset, gint iLength, gpointer data); extern "C" void handle_control_event(GtkDasherControl *pDasherControl, gint iEvent, gpointer data); extern "C" void handle_start_event(GtkDasherControl *pDasherControl, gpointer data); extern "C" gint dasher_main_key_snooper(GtkWidget *pWidget, GdkEventKey *pEvent, gpointer pUserData); /* Boilerplate code */ static void dasher_main_class_init(DasherMainClass *pClass) { g_type_class_add_private(pClass, sizeof(DasherMainPrivate)); dasher_main_signals[REALIZED] = g_signal_new("realized", G_TYPE_FROM_CLASS(pClass), (GSignalFlags)(G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION), G_STRUCT_OFFSET(DasherMainClass, realized), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); GObjectClass *pObjectClass = (GObjectClass *)pClass; pObjectClass->finalize = dasher_main_finalize; } static void dasher_main_init(DasherMain *pDasherMain) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); pPrivate->pAppSettings = NULL; pPrivate->pEditor = NULL; pPrivate->pPreferencesDialogue = NULL; pPrivate->pKeyboardHelper = new CKeyboardHelper(NULL); pPrivate->bWidgetsInitialised = false; } static void dasher_main_finalize(GObject *pObject) { DasherMain *pDasherMain = DASHER_MAIN(pObject); DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); dasher_main_save_state(pDasherMain); /* TODO: Does unref really do the right thing - check the whole ref counting situation */ // if(pPrivate->pEditor) // g_object_unref(pPrivate->pEditor); if(pPrivate->pPreferencesDialogue) g_object_unref(pPrivate->pPreferencesDialogue); if(pPrivate->pAppSettings) g_object_unref(pPrivate->pAppSettings); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); /* TODO: Do we need to take down anything else? */ } /* Public methods */ DasherMain * dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine) { if(g_pDasherMain) return g_pDasherMain; else { DasherMain *pDasherMain = (DasherMain *)(g_object_new(dasher_main_get_type(), NULL)); g_pDasherMain = pDasherMain; DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pDasherMain); /* Create the app settings object */ pPrivate->pAppSettings = dasher_app_settings_new(*argc, *argv); /* Load the user interface from the GUI file */ if(pCommandLine && pCommandLine->szAppStyle) { if(!strcmp(pCommandLine->szAppStyle, "traditional")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } else if(!strcmp(pCommandLine->szAppStyle, "compose")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_COMPOSE); } else if(!strcmp(pCommandLine->szAppStyle, "direct")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_DIRECT); } else if(!strcmp(pCommandLine->szAppStyle, "fullscreen")) { dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_FULLSCREEN); } else { g_critical("Application style %s is not supported", pCommandLine->szAppStyle); return 0; } } else { // By default use traditional mode dasher_app_settings_set_long(pPrivate->pAppSettings, APP_LP_STYLE, APP_STYLE_TRAD); } dasher_main_load_interface(pDasherMain); dasher_app_settings_set_widget(pPrivate->pAppSettings, GTK_DASHER_CONTROL(pPrivate->pDasherWidget)); /* TODO: This parsing code should really be tidied up */ if(pCommandLine && pCommandLine->szOptions) { gchar **pszOptionTerms; pszOptionTerms = g_strsplit(pCommandLine->szOptions, ",", 0); gchar **pszCurrent = pszOptionTerms; while(*pszCurrent) { gchar *szJoin = g_strrstr(*pszCurrent, "="); // Note to translators: This message will be output for command line errors when the "=" in --options=foo is missing. const gchar *errorMessage = _("option setting is missing \"=\"."); if(szJoin) { int iLength = szJoin - *pszCurrent; gchar *szKey = g_new(gchar, iLength + 1); memcpy(szKey, *pszCurrent, iLength); szKey[iLength] = '\0'; errorMessage = dasher_app_settings_cl_set(pPrivate->pAppSettings, szKey, szJoin + 1); g_free(szKey); } if (errorMessage) { // Note to translators: This string will be output when --options= specifies an unknown option. g_critical("%s: '%s', %s", _("Invalid option string specified"), *pszCurrent, errorMessage); return 0; } ++pszCurrent; } g_strfreev(pszOptionTerms); } /* --- */ dasher_editor_initialise(pPrivate->pEditor, pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, NULL); dasher_main_setup_window(pDasherMain); /* Create the editor */ gchar *szFullPath = NULL; if(pCommandLine) { if(pCommandLine->szFilename) { if(!g_path_is_absolute(pCommandLine->szFilename)) { char *cwd; cwd = (char *)malloc(1024 * sizeof(char)); getcwd(cwd, 1024); szFullPath = g_build_path("/", cwd, pCommandLine->szFilename, NULL); } else { szFullPath = g_strdup(pCommandLine->szFilename); } } } // TODO: Fix this // pPrivate->pEditor = GTK_EDITOR( // dasher_editor_initialise(pPrivate->pAppSettings, pDasherMain, pPrivate->pXML, szFullPath); g_free(szFullPath); // TODO: Were these really needed? // g_signal_connect(pPrivate->pEditor, "filename_changed", G_CALLBACK(dasher_main_cb_filename_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "buffer_changed", G_CALLBACK(dasher_main_cb_buffer_changed), pDasherMain); // g_signal_connect(pPrivate->pEditor, "context_changed", G_CALLBACK(dasher_main_cb_context_changed), pDasherMain); /* Create the preferences window */ dasher_main_create_preferences(pDasherMain); /* Create the lock dialogue (to be removed in future versions) */ #ifndef WITH_MAEMO dasher_lock_dialogue_new(pPrivate->pXML, pPrivate->pMainWindow); #else dasher_lock_dialogue_new(pPrivate->pXML, 0); #endif g_object_unref(pPrivate->pXML); pPrivate->pXML = 0; g_object_unref(pPrivate->pPrefXML); pPrivate->pPrefXML = 0; /* Set up various bits and pieces */ dasher_main_set_window_title(pDasherMain); dasher_main_populate_controls(pDasherMain); dasher_main_connect_control(pDasherMain); gtk_key_snooper_install(dasher_main_key_snooper, pDasherMain); return pDasherMain; } } static GtkBuilder * dasher_main_open_gui_xml(DasherMain *pSelf, const char *szGUIFilename) { GError *e = NULL; GtkBuilder *xml = gtk_builder_new(); g_message("Opening GUI file: %s", szGUIFilename); if (!gtk_builder_add_from_file(xml, szGUIFilename, &e)) { g_message("Can't find GUI file: %s. Dasher is unlikely to be correctly " "installed. (%s)", szGUIFilename, e->message); exit(1); } gtk_builder_connect_signals(xml, pSelf); return xml; } #define WRAP_CPP_CB(item) \ extern "C" void \ dasher_main_cb_##item(GtkAction *obj, DasherMain *p)\ {\ dasher_main_command_##item(p);\ } /* XXX PRLW: There is mention of "tutorial", but no function, (and * preferences_alphabet isn't called externally.) * editor passes on the action strings to dasher_editor_command which * land in dasher_editor_internal. */ WRAP_CPP_CB(import) WRAP_CPP_CB(quit) WRAP_CPP_CB(preferences) WRAP_CPP_CB(help) WRAP_CPP_CB(about) extern "C" void dasher_main_cb_editor(GtkAction *obj, DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); DASHER_ASSERT(pPrivate->pEditor != NULL); const gchar *action = gtk_action_get_name(obj); dasher_editor_command(pPrivate->pEditor, action); } static void dasher_main_load_interface(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); const char *szGUIFilename = NULL; const char *szPrefGUIFilename = NULL; #if WITH_MAEMO #ifdef WITH_MAEMOFULLSCREEN szGUIFilename = PROGDATA "/dashermaemofullscreen.ui"; #else szGUIFilename = PROGDATA "/dashermaemo.ui"; #endif szPrefGUIFilename = PROGDATA "/dashermaemo.preferences.ui"; #else switch(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE)) { case APP_STYLE_TRAD: szGUIFilename = PROGDATA "/dasher.traditional.ui"; break; case APP_STYLE_COMPOSE: szGUIFilename = PROGDATA "/dasher.compose.ui"; break; case APP_STYLE_DIRECT: szGUIFilename = PROGDATA "/dasher.direct.ui"; break; case APP_STYLE_FULLSCREEN: szGUIFilename = PROGDATA "/dasher.fullscreen.ui"; break; default: g_error("Inconsistent application style specified."); } szPrefGUIFilename = PROGDATA "/dasher.preferences.ui"; #endif if(!szGUIFilename) { g_error("Failure to determine GUI filename"); } pPrivate->pXML = dasher_main_open_gui_xml(pSelf, szGUIFilename); pPrivate->pPrefXML = dasher_main_open_gui_xml(pSelf, szPrefGUIFilename); #ifndef HAVE_GTK_SHOW_URI GtkAction *helpact = GTK_ACTION(gtk_builder_get_object(pPrivate->pXML, "action_help")); gtk_action_set_sensitive(helpact, false); gtk_action_set_visible(helpact, false); #endif // Save the details of some of the widgets for later // pPrivate->pActionPane = gtk_builder_get_object(pPrivate->pXML, "vbox39"); // pPrivate->pBufferView = gtk_builder_get_object(pPrivate->pXML, "the_text_view"); pPrivate->pDivider = GTK_PANED(gtk_builder_get_object(pPrivate->pXML, "main_divider")); // pPrivate->pEditPane = gtk_builder_get_object(pPrivate->pXML, "vbox40"); pPrivate->pMainWindow = GTK_WINDOW(gtk_builder_get_object(pPrivate->pXML, "window")); pPrivate->pToolbar = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "toolbar")); // pPrivate->pMenuBar = gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"); pPrivate->pDasherWidget = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "DasherControl")); #ifndef WITH_MAEMO pPrivate->pSpeedBox = GTK_SPIN_BUTTON(gtk_builder_get_object(pPrivate->pXML, "spinbutton1")); pPrivate->pAlphabetCombo = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "combobox1")); pPrivate->pStatusControl = GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "hbox8")); pPrivate->pAlphabetList = gtk_list_store_new(1, G_TYPE_STRING); gtk_combo_box_set_model(GTK_COMBO_BOX(pPrivate->pAlphabetCombo), GTK_TREE_MODEL(pPrivate->pAlphabetList)); GtkCellRenderer *pRenderer; pRenderer = gtk_cell_renderer_text_new(); g_object_set(G_OBJECT(pRenderer), "ellipsize", PANGO_ELLIPSIZE_END, NULL); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(pPrivate->pAlphabetCombo), pRenderer, "text", 0, NULL); // gtk_widget_add_events(pPrivate->pDragHandle, GDK_POINTER_MOTION_MASK); #else #ifdef WITH_MAEMOFULLSCREEN // TODO: This is horrible - no need to get it from the glade file if we're not going to use it pPrivate->pProgram = HILDON_PROGRAM(hildon_program_get_instance()); // hildon_app_set_title(pPrivate->pApp, "Dasher"); pPrivate->pHWindow = HILDON_WINDOW(hildon_window_new()); hildon_program_add_window(pPrivate->pProgram, pPrivate->pHWindow); gtk_widget_reparent(pPrivate->pInnerFrame, GTK_WIDGET(pPrivate->pHWindow)); // gtk_paned_set_position(GTK_PANED(window), 100); /* Do menu setup */ GtkMenu *main_menu; GtkWidget *file_menu; GtkWidget *file_menu_item; GtkWidget *options_menu; GtkWidget *options_menu_item; GtkWidget *help_menu; GtkWidget *help_menu_item; // main_menu = hildon_appview_get_menu(appview); main_menu = GTK_MENU(gtk_menu_new()); file_menu = gtk_builder_get_object(pPrivate->pXML, "file_menu"); options_menu = gtk_builder_get_object(pPrivate->pXML, "options1_menu"); help_menu = gtk_builder_get_object(pPrivate->pXML, "help_menu"); file_menu_item = gtk_menu_item_new_with_label ("File"); options_menu_item = gtk_menu_item_new_with_label ("Options"); help_menu_item = gtk_menu_item_new_with_label ("Help"); g_object_ref(file_menu); g_object_ref(options_menu); g_object_ref(help_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "file_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "options1")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(gtk_builder_get_object(pPrivate->pXML, "help_menu")), NULL); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_menu_item),file_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(options_menu_item),options_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(help_menu_item),help_menu); gtk_menu_shell_append((GtkMenuShell *)main_menu, file_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, options_menu_item); gtk_menu_shell_append((GtkMenuShell *)main_menu, help_menu_item); g_object_unref(file_menu); g_object_unref(options_menu); g_object_unref(help_menu); hildon_program_set_common_menu(pPrivate->pProgram, main_menu); gtk_widget_show_all( GTK_WIDGET( main_menu ) ); // /* And toolbar */ // GtkWidget *toolbar; // toolbar = gtk_builder_get_object(pPrivate->pXML, "toolbar"); // g_print("Got %p\n",toolbar); // gtk_widget_reparent (toolbar, appview->vbox); gtk_widget_show_all(GTK_WIDGET(pPrivate->pHWindow)); gtk_widget_destroy(GTK_WIDGET(pPrivate->pMainWindow)); pPrivate->pMainWindow = pPrivate->pHWindow; g_signal_connect(G_OBJECT(pPrivate->pHWindow), "delete_event", G_CALLBACK(ask_save_before_exit), NULL); #endif // Maemo fullscreen #endif // Maemo // pPrivate->bHidden = false; // pPrivate->bGrabbed = false; // pPrivate->iPosition = 100; // FIXME - make this persistant // TODO: Specify callbacks in glade file // TODO: Rationalise focus // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "button-release-event", G_CALLBACK(take_real_focus), NULL); // g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-press-event", G_CALLBACK(edit_key_press), NULL); //g_signal_connect(G_OBJECT(pPrivate->pBufferView), "key-release-event", G_CALLBACK(edit_key_release), NULL); pPrivate->iAlphabetComboHandler = g_signal_connect(G_OBJECT(pPrivate->pAlphabetCombo), "changed", G_CALLBACK(alphabet_combo_changed), NULL); // dasher_main_build_context_menu(pSelf); // Create a Maemo helper if necessary #if defined WITH_MAEMO && !defined WITH_MAEMOFULLSCREEN pPrivate->pMaemoHelper = dasher_maemo_helper_new(pPrivate->pMainWindow); #endif // Set up any non-registry-dependent options #ifdef WITH_GPE gtk_window_set_decorated(pPrivate->pMainWindow, false); #endif // Hide any widgets which aren't appropriate for this mode // XXX PRLW: chances are these aren't defined in direct.ui anyway => we are // hiding non-existent widgets. if(dasher_app_settings_get_long(pPrivate->pAppSettings, APP_LP_STYLE) == APP_STYLE_DIRECT) { gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "dasher_menu_bar"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_new"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_open"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_save"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_saveas"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem1"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_cut"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_copy"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "tb_command_paste"))); gtk_widget_hide(GTK_WIDGET(gtk_builder_get_object(pPrivate->pXML, "separatortoolitem2"))); } pPrivate->pEditor = DASHER_EDITOR(gtk_builder_get_object(pPrivate->pXML, "DasherEditor")); // TODO: szFullPath pPrivate->bWidgetsInitialised = true; } static void dasher_main_create_preferences(DasherMain *pSelf) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); pPrivate->pPreferencesDialogue = dasher_preferences_dialogue_new(pPrivate->pPrefXML, pPrivate->pEditor, pPrivate->pAppSettings, pPrivate->pMainWindow); } // DasherEditor * // dasher_main_get_editor(DasherMain *pSelf) { // DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); // return pPrivate->pEditor; // } static void dasher_main_handle_parameter_change(DasherMain *pSelf, int iParameter) { DasherMainPrivate *pPrivate = DASHER_MAIN_GET_PRIVATE(pSelf); switch( iParameter ) { case APP_BP_SHOW_TOOLBAR: if( dasher_app_settings_get_bool(pPrivate->pAppSettings, APP_BP_SHOW_TOOLBAR)) gtk_widget_show(pPrivate->pToolbar); else gtk_widget_hide(pPrivate->pToolbar); break; case BP_SHOW_SLIDER: // TODO: Shouldn't be a core parmeter if( dasher_app_settings_get_bool(pPrivate->pAppSettings, BP_SHOW_SLIDER)) gtk_widget_show(pPrivate->pStatusControl); else gtk_widget_hide(pPrivate->pStatusControl); break; diff --git a/Src/Gtk2/dasher_main.h b/Src/Gtk2/dasher_main.h index 29927f8..e6a0106 100644 --- a/Src/Gtk2/dasher_main.h +++ b/Src/Gtk2/dasher_main.h @@ -1,43 +1,94 @@ #ifndef __dasher_main_h__ #define __dasher_main_h__ #include <glib.h> #include <glib-object.h> +#include "Preferences.h" +#include "KeyboardHelper.h" +#include "DasherAppSettings.h" G_BEGIN_DECLS #define DASHER_TYPE_MAIN (dasher_main_get_type()) #define DASHER_MAIN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), DASHER_TYPE_MAIN, DasherMain )) #define DASHER_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), DASHER_TYPE_MAIN, DasherMainClass )) #define DASHER_IS_MAIN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), DASHER_TYPE_MAIN)) #define DASHER_IS_MAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), DASHER_TYPE_MAIN)) #define DASHER_MAIN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), DASHER_TYPE_MAIN, DasherMainClass)) +// TODO: Make sure this is actually used +#define DASHER_MAIN_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), DASHER_TYPE_MAIN, DasherMainPrivate)) typedef struct _DasherMain DasherMain; typedef struct _DasherMainClass DasherMainClass; struct _DasherMain { GObject parent; }; struct _DasherMainClass { GObjectClass parent_class; void (*realized)(DasherMain *pDasherMain); }; +struct _DasherMainPrivate { + GtkBuilder *pXML; + GtkBuilder *pPrefXML; + + // Child objects owned here + DasherAppSettings *pAppSettings; + DasherPreferencesDialogue *pPreferencesDialogue; + DasherEditor *pEditor; + + CKeyboardHelper *pKeyboardHelper; + + // Various widgets which need to be cached: + // GtkWidget *pBufferView; + GtkPaned *pDivider; + GtkWindow *pMainWindow; + GtkWidget *pToolbar; + GtkSpinButton *pSpeedBox; + GtkWidget *pAlphabetCombo; + GtkWidget *pStatusControl; + GtkWidget *pDasherWidget; + + GtkListStore *pAlphabetList; + GtkAccelGroup *pAccel; + gulong iAlphabetComboHandler; + + // Widgets used for maemo +#ifdef WITH_MAEMO + DasherMaemoHelper *pMaemoHelper; +#ifdef WITH_MAEMOFULLSCREEN + HildonProgram *pProgram; + HildonWindow *pHWindow; +#endif +#endif + + // Properties of the main window + int iWidth; + int iHeight; + bool bWidgetsInitialised; +}; + +typedef struct _DasherMainPrivate DasherMainPrivate; typedef struct _SCommandLine SCommandLine; struct _SCommandLine { gchar *szFilename; gchar *szAppStyle; gchar *szOptions; }; DasherMain *dasher_main_new(int *argc, char ***argv, SCommandLine *pCommandLine); GType dasher_main_get_type(); //DasherEditorInternal *dasher_main_get_editor(DasherMain *pSelf); void dasher_main_show(DasherMain *pSelf); + +static void dasher_main_toggle_game_mode(DasherAppSettings* pAppSettings) { + dasher_app_settings_set_bool(pAppSettings, BP_GAME_MODE, true); +} + G_END_DECLS #endif
rgee/HFOSS-Dasher
b7bfd6d58c70ece42a40aa9fe2dd137f06717f75
Added test game mode data to version control.
diff --git a/Src/DasherCore/test_text.txt b/Src/DasherCore/test_text.txt new file mode 100644 index 0000000..7e94834 --- /dev/null +++ b/Src/DasherCore/test_text.txt @@ -0,0 +1,79 @@ +I'm_a_senior at Cesar Chavez high in San Francisco's sunny Mission district, and that makes me one of the most surveilled people in the world. My name is Marcus Yallow, but back when this story starts, I was going by w1n5t0n. Pronounced "Winston." + +*Not* pronounced "Double-you-one-enn-five-tee-zero-enn" -- unless you're a clueless disciplinary officer who's far enough behind the curve that you still call the Internet "the information superhighway." + +I know just such a clueless person, and his name is Fred Benson, one of three vice-principals at Cesar Chavez. He's a sucking chest wound of a human being. But if you're going to have a jailer, better a clueless one than one who's really on the ball. + +"Marcus Yallow," he said over the PA one Friday morning. The PA isn't very good to begin with, and when you combine that with Benson's habitual mumble, you get something that sounds more like someone struggling to digest a bad burrito than a school announcement. But human beings are good at picking their names out of audio confusion -- it's a survival trait. + +I grabbed my bag and folded my laptop three-quarters shut -- I didn't want to blow my downloads -- and got ready for the inevitable. + +"Report to the administration office immediately." + +My social studies teacher, Ms Galvez, rolled her eyes at me and I rolled my eyes back at her. The Man was always coming down on me, just because I go through school firewalls like wet kleenex, spoof the gait-recognition software, and nuke the snitch chips they track us with. Galvez is a good type, anyway, never holds that against me (especially when I'm helping get with her webmail so she can talk to her brother who's stationed in Iraq). + +My boy Darryl gave me a smack on the ass as I walked past. I've known Darryl since we were still in diapers and escaping from play-school, and I've been getting him into and out of trouble the whole time. I raised my arms over my head like a prizefighter and made my exit from Social Studies and began the perp-walk to the office. + +I was halfway there when my phone went. That was another no-no -- phones are muy prohibido at Chavez High -- but why should that stop me? I ducked into the toilet and shut myself in the middle stall (the furthest stall is always grossest because so many people head straight for it, hoping to escape the smell and the squick -- the smart money and good hygiene is down the middle). I checked the phone -- my home PC had sent it an email to tell it that there was something new up on Harajuku Fun Madness, which happens to be the best game ever invented. + +I grinned. Spending Fridays at school was teh suck anyway, and I was glad of the excuse to make my escape. + +I ambled the rest of the way to Benson's office and tossed him a wave as I sailed through the door. + +"If it isn't Double-you-one-enn-five-tee-zero-enn," he said. Fredrick Benson -- Social Security number 545-03-2343, date of birth August 15 1962, mother's maiden name Di Bona, hometown Petaluma -- is a lot taller than me. I'm a runty 5'8", while he stands 6'7", and his college basketball days are far enough behind him that his chest muscles have turned into saggy man-boobs that were painfully obvious through his freebie dot-com polo-shirts. He always looks like he's about to slam-dunk your ass, and he's really into raising his voice for dramatic effect. Both these start to lose their efficacy with repeated application. + +"Sorry, nope," I said. "I never heard of this R2D2 character of yours." + +"W1n5t0n," he said, spelling it out again. He gave me a hairy eyeball and waited for me to wilt. Of course it was my handle, and had been for years. It was the identity I used when I was posting on message-boards where I was making my contributions to the field of applied security research. You know, like sneaking out of school and disabling the minder-tracer on my phone. But he didn't know that this was my handle. Only a small number of people did, and I trusted them all to the end of the earth. + +"Um, not ringing any bells," I said. I'd done some pretty cool stuff around school using that handle -- I was very proud of my work on snitch-tag killers -- and if he could link the two identities, I'd be in trouble. No one at school ever called me w1n5t0n or even Winston. Not even my pals. It was Marcus or nothing. + +Benson settled down behind his desk and tapped his class-ring nervously on his blotter. He did this whenever things started to go bad for him. Poker players call stuff like this a "tell" -- something that let you know what was going on in the other guy's head. I knew Benson's tells backwards and forwards. + +"Marcus, I hope you realize how serious this is." + +"I will just as soon as you explain what this is, sir." I always say "sir" to authority figures when I'm messing with them. It's my own tell. + +He shook his head at me and looked down, another tell. Any second now, he was going to start shouting at me. "Listen, kiddo! It's time you came to grips with the fact that we know about what you've been doing, and that we're not going to be lenient about it. You're going to be lucky if you're not expelled before this meeting is through. Do you want to graduate?" + +"Mr Benson, you still haven't explained what the problem is --" + +He slammed his hand down on the desk and then pointed his finger at me. "The *problem*, Mr Yallow, is that you've been engaged in criminal conspiracy to subvert this school's security system, and you have supplied security countermeasures to your fellow students. You know that we expelled Graciella Uriarte last week for using one of your devices." Uriarte had gotten a bad rap. She'd bought a radio-jammer from a head-shop near the 16th Street BART station and it had set off the countermeasures in the school hallway. Not my doing, but I felt for her. + +"And you think I'm involved in that?" + +"We have reliable intelligence indicating that you are w1n5t0n" -- again, he spelled it out, and I began to wonder if he hadn't figured out that the 1 was an I and the 5 was an S. "We know that this w1n5t0n character is responsible for the theft of last year's standardized tests." That actually hadn't been me, but it was a sweet hack, and it was kind of flattering to hear it attributed to me. "And therefore liable for several years in prison unless you cooperate with me." + +"You have 'reliable intelligence'? I'd like to see it." + +He glowered at me. "Your attitude isn't going to help you." + +"If there's evidence, sir, I think you should call the police and turn it over to them. It sounds like this is a very serious matter, and I wouldn't want to stand in the way of a proper investigation by the duly constituted authorities." + +"You want me to call the police." + +"And my parents, I think. That would be for the best." + +We stared at each other across the desk. He'd clearly expected me to fold the second he dropped the bomb on me. I don't fold. I have a trick for staring down people like Benson. I look slightly to the left of their heads, and think about the lyrics to old Irish folk songs, the kinds with three hundred verses. It makes me look perfectly composed and unworried. + +*And the wing was on the bird and the bird was on the egg and the egg was in the nest and the nest was on the leaf and the leaf was on the twig and the twig was on the branch and the branch was on the limb and the limb was in the tree and the tree was in the bog -- the bog down in the valley-oh! High-ho the rattlin' bog, the bog down in the valley-oh --* + +"You can return to class now," he said. "I'll call on you once the police are ready to speak to you." + +"Are you going to call them now?" + +"The procedure for calling in the police is complicated. I'd hoped that we could settle this fairly and quickly, but since you insist --" + +"I can wait while you call them is all," I said. "I don't mind." + +He tapped his ring again and I braced for the blast. + +"*Go!*" he yelled. "Get the hell out of my office, you miserable little --" + +I got out, keeping my expression neutral. He wasn't going to call the cops. If he'd had enough evidence to go to the police with, he would have called them in the first place. He hated my guts. I figured he'd heard some unverified gossip and hoped to spook me into confirming it. + +I moved down the corridor lightly and sprightly, keeping my gait even and measured for the gait-recognition cameras. These had been installed only a year before, and I loved them for their sheer idiocy. Beforehand, we'd had face-recognition cameras covering nearly every public space in school, but a court ruled that was unconstitutional. So Benson and a lot of other paranoid school administrators had spent our textbook dollars on these idiot cameras that were supposed to be able to tell one person's walk from another. Yeah, right. + +I got back to class and sat down again, Ms Galvez warmly welcoming me back. I unpacked the school's standard-issue machine and got back into classroom mode. The SchoolBooks were the snitchiest technology of them all, logging every keystroke, watching all the network traffic for suspicious keywords, counting every click, keeping track of every fleeting thought you put out over the net. We'd gotten them in my junior year, and it only took a couple months for the shininess to wear off. Once people figured out that these "free" laptops worked for the man -- and showed a never-ending parade of obnoxious ads to boot -- they suddenly started to feel very heavy and burdensome. + +Cracking my SchoolBook had been easy. The crack was online within a month of the machine showing up, and there was nothing to it -- just download a DVD image, burn it, stick it in the SchoolBook, and boot it while holding down a bunch of different keys at the same time. The DVD did the rest, installing a whole bunch of hidden programs on the machine, programs that would stay hidden even when the Board of Ed did its daily remote integrity checks of the machines. Every now and again I had to get an update for the software to get around the Board's latest tests, but it was a small price to pay to get a little control over the box.
rgee/HFOSS-Dasher
31487c713ecd533406c1541cb8a048202da851f8
Removed all traces of EV_Textdraw as we no longer use it.
diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index 3fe96f7..97708f4 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,731 +1,728 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove, CDasherNode* pNode) { // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } if((pNode != NULL) && (pNode->GetFlag(NF_GAME) == true)) { m_pEventHandler->InsertEvent(new CGameNodeDrawEvent(pNode, this, newleft2, newtop2)); } - // Tell other listeners that text has been drawn and provide some information - // about the draw call. - //m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplayText,this, newleft2, newtop2, Size)); // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (y1 <= iDasherMaxY && y2 >= iDasherMinY) { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) { //node should be rendered! RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); return true; } } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); const std::string &sDisplayText(pRender->getDisplayText()); if( sDisplayText.size() > 0 ) { if(pRender->GetFlag(NF_GAME)) { DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove(), pRender); } else { DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); } } pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->getColour(), -1, Nodes1, 0); //also allow it to be expanded, it's big enough. policy.pushNode(pRender, y1, y2, true, dMaxCost); return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; int temp_parentcolor = pRender->getColour(); const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } if (!pRender->onlyChildRendered) { //render all children... for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); i != pRender->GetChildren().end(); i++) { id++; CDasherNode *pChild = *i; myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth+1)) { if (lasty<newy1) { //if child has been drawn then the interval between him and the //last drawn child should be drawn too. //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } lasty = newy2; } } // Finish off the drawing process // if(iDepth == 1) { // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. if(lasty<y2) { RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } } // Draw the outline if(pRender->getColour() != -1) {//-1 = invisible RenderNodeOutlineFast(pRender->getColour(), y1, y2, mostleft, pRender->getDisplayText(), pRender->bShove()); } // } } bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index bd20cd8..2e5a2ee 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,209 +1,166 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; - class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; class CDasherNode; } enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW, - EV_GAME_NODE_DRAWN + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_GAME_NODE_DRAWN }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { public: CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) : m_pNode(pNode), m_pView(pView), m_iX(iX), m_iY(iY) { m_iEventType = EV_GAME_NODE_DRAWN; }; CDasherNode* m_pNode; screenint m_iX, m_iY; CDasherView* m_pView; }; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; -/** - * An event that signals text has been drawn. Useful for determining its location - * because that information is only available at draw time. - */ -class Dasher::CTextDrawEvent : public Dasher::CEvent { -public: - CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) - :m_sDisplayText(sDisplayText), - m_pDasherView(pView), - m_iX(iX), - m_iY(iY), - m_iSize(iSize) - { - m_iEventType = EV_TEXTDRAW; - }; - /** - * The text that has been drawn. - */ - std::string m_sDisplayText; - - /** - * The dasher view that emitted this event. - */ - CDasherView* m_pDasherView; - - /** - * The X position (in screen coordinates) of the center of the box surrounding the text. - */ - screenint m_iX; - - /** - * The Y position (in screen coordinates) of the center of the box surrounding the text. - */ - screenint m_iY; - - /** - * The size of the text. Useful for determining the boundaries of the text "box" - */ - int m_iSize; -}; - class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 5ec8c88..c9fb4b1 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,167 +1,167 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ /** * This class handles the dispatch and management of events throughout Dasher. * Any class that derives from CDasherComponent can subscribe to events. These * events are enumerated in Event.h. All CDasherComponents are automatically * registered for their selected events on construction. * * Components SHOULD specify exactly which events they're interested in * instead of omitting this information. This allows the event management * system to make optimal use of time in dispatching events. (i.e. cuts * down on unused event dispatching) */ class Dasher::CEventHandler { public: - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(11), m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. * * @warning If this is called from an Event Handler, (i.e. While events * are being processed) the event is enqueued to be dispatched * and NOT immediately dispatched. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for all events. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; /** * Dispatch all the events in the event queue, and take * care of all the pending additions/deletions to m_vSpecificListeners * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and * m_vPendSpecificUnreg */ void ProcessEventQueue(); /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 08f50bb..c47adfa 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,157 +1,140 @@ #include "GameModule.h" using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ -const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_TEXTDRAW, EV_GAME_NODE_DRAWN}; +const int Dasher::CGameModule::vEvents[2] = {EV_EDIT, EV_GAME_NODE_DRAWN}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; - /* - case EV_TEXTDRAW: - { - CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); - // Check whether the text that was drawn is the current target character. - if(CharacterFound(evt)) { - //the x and y coordinates (in Dasher coords) of the target node - evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); - - } - } - break; - */ default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } -bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { - return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); -} - bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index b22868f..4e9afa8 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,229 +1,225 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); - /** - * @see CharacterFound - */ - bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ - static const int vEvents[3]; + static const int vEvents[2]; }; } #endif
rgee/HFOSS-Dasher
0f5e7f5714bb54b1bf34dd3f878526c71d22d28c
Fixed bugs introduced by merge with game node tagging branch
diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index c8f16f5..5ec8c88 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,168 +1,167 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ /** * This class handles the dispatch and management of events throughout Dasher. * Any class that derives from CDasherComponent can subscribe to events. These * events are enumerated in Event.h. All CDasherComponents are automatically * registered for their selected events on construction. * * Components SHOULD specify exactly which events they're interested in * instead of omitting this information. This allows the event management * system to make optimal use of time in dispatching events. (i.e. cuts * down on unused event dispatching) */ class Dasher::CEventHandler { -<<<<<<< HEAD public: CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. * * @warning If this is called from an Event Handler, (i.e. While events * are being processed) the event is enqueued to be dispatched * and NOT immediately dispatched. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for all events. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; /** * Dispatch all the events in the event queue, and take * care of all the pending additions/deletions to m_vSpecificListeners * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and * m_vPendSpecificUnreg */ void ProcessEventQueue(); /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 368331b..08f50bb 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,157 +1,157 @@ #include "GameModule.h" using namespace Dasher; /** * Static members of non-integral type must be initialized outside of * class definitions. */ -const int Dasher::CGameModule::vEvents[2] = {EV_EDIT, EV_TEXTDRAW}; +const int Dasher::CGameModule::vEvents[3] = {EV_EDIT, EV_TEXTDRAW, EV_GAME_NODE_DRAWN}; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; /* case EV_TEXTDRAW: { CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; */ default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 4946594..b22868f 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,229 +1,229 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: /** * Constructor * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param pInterface A pointer to a Dasher interface * @param iID The ID of this module. * @param szName The name of this module * @param pWordGenerator A pointer to the word generator */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; /** * The events this class listens for */ - static const int vEvents[2]; + static const int vEvents[3]; }; } #endif
rgee/HFOSS-Dasher
4ec0021896fff7cb988fdd827bf37c077bbd5ffa
FIXED GAME NODE TAGGING. Now searching from the node under the crosshair instead of relying on the root, which can be inconsistent and isn't guaranteed to be 1 above the level we're trying to search.
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index b424abc..4bef83f 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,823 +1,823 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; // Search from the current root. - m_Root->GameSearchChildren(m_strGameTarget); + Get_node_under_crosshair()->GameSearchChildren(m_strGameTarget); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. //GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); //if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) if(pNode->GetFlag(NF_GAME)) { /*std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); }*/ - pNode->GameSearchChildren(m_strGameTarget); + Get_node_under_crosshair()->GameSearchChildren(m_strGameTarget); } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); }
rgee/HFOSS-Dasher
c1143d07ef5aaa6a81fb2701eba4c4b79ec84f2e
Made it so that the collection of events a component or module listens for is now a class-level constant. Before, they could vary by instance AND the caller of the constructor had to know what events the object needs...very poor design that managed to sneak in a while ago.
diff --git a/Src/DasherCore/DasherComponent.h b/Src/DasherCore/DasherComponent.h index 86b19a3..d3e6dab 100644 --- a/Src/DasherCore/DasherComponent.h +++ b/Src/DasherCore/DasherComponent.h @@ -1,48 +1,54 @@ #ifndef __dashercomponent_h__ #define __dashercomponent_h__ #include <vector> #include "SettingsStore.h" namespace Dasher { class CEvent; class CEventHandler; class CDasherComponent; }; /// \ingroup Core /// @{ class Dasher::CDasherComponent { public: + + /** + * Constructor that registers this component for ALL Dasher events + * @param pEventHandler A pointer to the event handler + * @param pSettingsStore A pointer to the settings store + */ CDasherComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore); /** - * Constructor to register for specific events. + * Constructor that allows for subscription to specific Dasher events. * @param pEventHandler A pointer to the event handler * @param pSettingsStore A pointer to the settings store * @param vEvents A vector of integers where each integer is an event type */ CDasherComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore, std::vector<int> vEvents); virtual ~CDasherComponent(); void InsertEvent(Dasher::CEvent * pEvent); virtual void HandleEvent(Dasher::CEvent * pEvent) {}; bool GetBoolParameter(int iParameter) const; void SetBoolParameter(int iParameter, bool bValue) const; long GetLongParameter(int iParameter) const; void SetLongParameter(int iParameter, long lValue) const; std::string GetStringParameter(int iParameter) const; void SetStringParameter(int iParameter, const std::string & sValue) const; ParameterType GetParameterType(int iParameter) const; std::string GetParameterName(int iParameter) const; protected: Dasher::CEventHandler *m_pEventHandler; CSettingsStore *m_pSettingsStore; }; /// @} #endif diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 0b6e807..6ceef74 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -450,716 +450,715 @@ void CDasherInterfaceBase::Pause() { m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h - int GameEvents[] = {EV_EDIT, EV_TEXTDRAW}; RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"), - std::vector<int>(GameEvents, GameEvents + sizeof(GameEvents) / sizeof(int)), new CFileWordGenerator("test_text.txt"))); + new CFileWordGenerator("test_text.txt"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 2f7513d..5ec8c88 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,156 +1,167 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ +/** + * This class handles the dispatch and management of events throughout Dasher. + * Any class that derives from CDasherComponent can subscribe to events. These + * events are enumerated in Event.h. All CDasherComponents are automatically + * registered for their selected events on construction. + * + * Components SHOULD specify exactly which events they're interested in + * instead of omitting this information. This allows the event management + * system to make optimal use of time in dispatching events. (i.e. cuts + * down on unused event dispatching) + */ class Dasher::CEventHandler { public: CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. * * @warning If this is called from an Event Handler, (i.e. While events * are being processed) the event is enqueued to be dispatched * and NOT immediately dispatched. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for all events. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; /** * Dispatch all the events in the event queue, and take * care of all the pending additions/deletions to m_vSpecificListeners * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and * m_vPendSpecificUnreg */ void ProcessEventQueue(); /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 39d533f..ef6222e 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,137 +1,143 @@ #include "GameModule.h" using namespace Dasher; +/** + * Static members of non-integral type must be initialized outside of + * class definitions. + */ +const int Dasher::CGameModule::vEvents[2] = {EV_EDIT, EV_TEXTDRAW}; + void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index a7d1680..e0cb98b 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,208 +1,226 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size - * m_iTargetChunkSize is gotten from the word generator and displayed. + * m_iTargetChunkSize is retrieved from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: + /** + * Constructor + * @param pEventHandler A pointer to the event handler + * @param pSettingsStore A pointer to the settings store + * @param pInterface A pointer to a Dasher interface + * @param iID The ID of this module. + * @param szName The name of this module + * @param pWordGenerator A pointer to the word generator + */ CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, - std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) + CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), - CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) + CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, + std::vector<int>(vEvents, vEvents + sizeof(vEvents) / sizeof(int))) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { - }; + } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; + + /** + * The events this class listens for + */ + static const int vEvents[2]; }; -} + +} + + #endif
rgee/HFOSS-Dasher
eee5bc391e756bc787b02816b75dfacf21b314f5
Performed slight optimizations on Event Manager. Made typedefs private.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index d1bed94..36b414a 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,130 +1,122 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif #include <sstream> void CEventHandler::InsertEvent(CEvent *pEvent) { //put the event at the end of the queue EnqueueEvent(pEvent); //if we are already dispatching events, don't do it again //this is necessary to keep recursive calls from removing //events from the queue while we iterate over it if(m_bIsDispatching) { return; } else { ProcessEventQueue(); } } void CEventHandler::ProcessEventQueue() { //iterate over the event queue until it's empty while(!m_qEventQueue.empty()) { CEvent *currEvent = m_qEventQueue.front(); m_qEventQueue.pop(); m_pInterface->InterfaceEventHandler(currEvent); - m_pInterface->ExternalEventHandler(currEvent); + m_pInterface->ExternalEventHandler(currEvent); //entering the dispatching loop - no longer safe to modify m_vSpecificListeners m_bIsDispatching = true; //dispatch the event at the front of the queue to all registered listeners for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[currEvent->m_iEventType - 1].begin(); it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); ++it) { (*it)->HandleEvent(currEvent); } //done dispatching this event - safe to modify m_vSpecificListeners m_bIsDispatching = false; //register all listeners that have been waiting to be added for(EvtListenerCollection::iterator it = m_vPendingSpecificReg.begin(); it != m_vPendingSpecificReg.end(); ++it) RegisterListener((*it).first, (*it).second); //unregister all that have been waiting to be removed for(EvtListenerCollection::iterator it = m_vPendingSpecificUnreg.begin(); it != m_vPendingSpecificUnreg.end(); ++it) UnregisterListener((*it).first, (*it).second); m_vPendingSpecificUnreg.clear(); m_vPendingSpecificReg.clear(); } } void CEventHandler::EnqueueEvent(CEvent *pEvent) { m_qEventQueue.push(pEvent); } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { - - // Only try to add a new listener if it doesn't already exist in the Listener map - if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { - - if(!m_bIsDispatching) { - m_vSpecificListeners[iEventType - 1].push_back(pListener); - } - else { - // Add the listener to the pending set if events are being dispatched - m_vPendingSpecificReg.push_back(std::make_pair(pListener, iEventType)); - } - } - else { - // Can't add the same listener twice + if(m_bIsDispatching) { + // Add the listener to the pending set if events are being dispatched + m_vPendingSpecificReg.push_back(std::make_pair(pListener, iEventType)); + } // Only try to add a new listener if it doesn't already exist in the Listener map + else if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { + m_vSpecificListeners[iEventType - 1].push_back(pListener); } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { RegisterListener(pListener, curEvtType); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { if(!m_bIsDispatching) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType - 1].begin(); it != m_vSpecificListeners[iEventType - 1].end(); ++it) { if((*it) == pListener) { m_vSpecificListeners[iEventType - 1].erase(it); break; } } } else { m_vPendingSpecificUnreg.push_back(std::make_pair(pListener, iEventType)); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { UnregisterListener(pListener, curEvtType); } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 8311997..2f7513d 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,155 +1,156 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { - -public: - - /** - * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable - * @brief A 2d vector of Dasher Components where each sub-vector corresponds - * to a specific event. The contents of the sub-vectors are the components - * that subscribe to this event. - */ - typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; - - /** - * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection - * @brief A collection whose elements represent 1 to 1 associations between - * Dasher Components and Dasher core event types - */ - typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; +public: CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { - m_bIsDispatching = false; - - // Initialize the event listener container (and queue) so we can add elements without - // checking if the sub-vectors actually exist or not. - for(int i = 0; i < m_iNUM_EVENTS; i++) { - m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); - } + m_bIsDispatching = false; + + // Initialize the event listener container (and queue) so we can add elements without + // checking if the sub-vectors actually exist or not. + for(int i = 0; i < m_iNUM_EVENTS; i++) { + m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); + } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. + * + * @warning If this is called from an Event Handler, (i.e. While events + * are being processed) the event is enqueued to be dispatched + * and NOT immediately dispatched. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); - /** - * Register a listener for ALL events. To specify one, pass it - * as a second parameter. + /** + * Register a listener for all events. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h - * that represents the event to which you'd like to subscribe. + * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h - * that represents the event to which you'd like to unsubscribe. + * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); - /** + /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: + /** + * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable + * @brief A 2d vector of Dasher Components where each sub-vector corresponds + * to a specific event. The contents of the sub-vectors are the components + * that subscribe to this event. + */ + typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; + + /** + * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection + * @brief A collection whose elements represent 1 to 1 associations between + * Dasher Components and Dasher core event types + */ + typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; /** * Dispatch all the events in the event queue, and take * care of all the pending additions/deletions to m_vSpecificListeners * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and * m_vPendSpecificUnreg */ void ProcessEventQueue(); /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif
rgee/HFOSS-Dasher
f0e79db2d2ac4a9a7563f5a7ad5bc94a2ce4c2cd
Added include guards to old mock objects. Added mock object for FileWordGenerator. File word tests are NOT building yet.
diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index a229fb7..fffef4a 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,114 +1,113 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> #include <stdexcept> using namespace std; #include "WordGeneratorBase.h" -#include "DasherInterfaceBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE * kept open for the lifetime of this object and the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all * at once. */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string sPath, int iRegen) : m_sPath(sPath), CWordGeneratorBase(iRegen) { Generate(); } CFileWordGenerator(std::string sPath) : m_sPath(sPath), CWordGeneratorBase() { Generate(); } virtual ~CFileWordGenerator() { m_sFileHandle.close(); } /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string if there are no more * words. * @throw Throws an exception if the file cannot be read. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter. Returns the file name and extension, without * any slashes. * @return The actual name of the file being read from */ std::string GetFilename(); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * The generator function. Reads words from the specified file. * @return True if generating the new buffer was successful, * false if we've reached the end of the file. * @throw Throws an exception if the file cannot be read. */ bool Generate(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Src/TestPlatform/Makefile.am b/Src/TestPlatform/Makefile.am deleted file mode 100644 index e69de29..0000000 diff --git a/Src/TestPlatform/MockFileWordGenerator.cpp b/Src/TestPlatform/MockFileWordGenerator.cpp new file mode 100644 index 0000000..87c55ea --- /dev/null +++ b/Src/TestPlatform/MockFileWordGenerator.cpp @@ -0,0 +1,54 @@ + #include "MockFileWordGenerator.h" + + +bool MockFileWordGenerator::Generate() { + if(!m_sFileHandle.is_open()) { + m_sFileHandle.open(m_sPath.c_str()); + } + if(m_sFileHandle.fail()) { + throw std::runtime_error("File: " + m_sPath + " cannot be read."); + } + + m_uiPos = 0; + m_sGeneratedString.clear(); + + if(m_sFileHandle.eof()) { + return false; + } else if(m_sFileHandle.good()) { + std::getline(m_sFileHandle, m_sGeneratedString); + return true; + } else { + return false; + } +} + +std::string MockFileWordGenerator::GetPath() { + return m_sPath; +} +std::string MockFileWordGenerator::GetFilename() { + return m_sPath.substr(m_sPath.rfind("/")+1); +} + +std::string MockFileWordGenerator::GetNextWord() { + if(m_uiPos >= m_sGeneratedString.length()) { + // Attempt to reload the buffer. + if(!Generate()) return ""; + } + + size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); + std::string result; + + // If there are no space characters. + if(found != string::npos) + { + result = m_sGeneratedString.substr(m_uiPos, found); + + m_uiPos += (found + 1); + } else { + result = m_sGeneratedString.substr(m_uiPos); + }; + + return result; +} + + diff --git a/Src/TestPlatform/MockFileWordGenerator.h b/Src/TestPlatform/MockFileWordGenerator.h new file mode 100644 index 0000000..1179440 --- /dev/null +++ b/Src/TestPlatform/MockFileWordGenerator.h @@ -0,0 +1,116 @@ +#ifndef __MockFileWordGenerator_h__ +#define __MockFileWordGenerator_h__ + +#include "../DasherCore/WordGeneratorBase.h" +#include <string> +#include <iostream> +#include <fstream> +#include <stdexcept> +using namespace std; + +// MOCK OBJECT FOR TESTING + +/** + * This class implements the Word Generator interface. This means + * that after construction, your primary method of retrieving words + * will be calling GetNextWord(). For specifics on Word Generators, + * see CWordGeneratorBase. + * + * This class specifically reads words from a given file. Files ARE + * kept open for the lifetime of this object and the size of the file + * should not pose an issue. + * + * However, if you read in a file that has unreasonably long lines, + * the behavior is undefined as you may cause the file to be read in all + * at once. + */ +class MockFileWordGenerator : public CWordGeneratorBase { +public: + MockFileWordGenerator(std::string sPath, int iRegen) + : m_sPath(sPath), + CWordGeneratorBase(iRegen) { + Generate(); + } + + MockFileWordGenerator(std::string sPath) + : m_sPath(sPath), + CWordGeneratorBase() { + Generate(); + } + + virtual ~MockFileWordGenerator() { + m_sFileHandle.close(); + } + + /** + * Returns the next word that was read + * @return The next word in the word generator model if there is one. + * Otherwise, returns an empty string if there are no more + * words. + * @throw Throws an exception if the file cannot be read. + */ + virtual std::string GetNextWord(); + + + /** + * File path getter + * @return The path to the file this generator reads from. + */ + std::string GetPath(); + + /** + * File name getter. Returns the file name and extension, without + * any slashes. + * @return The actual name of the file being read from + */ + std::string GetFilename(); + + + std::string GetWholeBuffer() { return m_sGeneratedString; } + std::ifstream& GetFileHandle() { return m_sFileHandle; } + size_t GetStringPosition() { return m_uiPos; } + + +private: +/* --------------------------------------------------------------------- + * Private Methods + * --------------------------------------------------------------------- + */ + + /** + * The generator function. Reads words from the specified file. + * @return True if generating the new buffer was successful, + * false if we've reached the end of the file. + * @throw Throws an exception if the file cannot be read. + */ + bool Generate(); + + +/* --------------------------------------------------------------------- + * Member Variables + * --------------------------------------------------------------------- + */ + + /** + * The string that has been generated. + */ + std::string m_sGeneratedString; + + /** + * The path to the file this generator reads from. + */ + std::string m_sPath; + + /** + * The position we're currently reading from in the string. + */ + size_t m_uiPos; + + /** + * The input stream that acts as the handle to the underlying file. + */ + ifstream m_sFileHandle; +}; + + +#endif diff --git a/Src/TestPlatform/MockInterfaceBase.h b/Src/TestPlatform/MockInterfaceBase.h index dcc6683..ebb8391 100644 --- a/Src/TestPlatform/MockInterfaceBase.h +++ b/Src/TestPlatform/MockInterfaceBase.h @@ -1,34 +1,39 @@ +#ifndef __MockInterfaceBase_h__ +#define __MockInterfaceBase_h__ + #include "../DasherCore/DasherInterfaceBase.h" using namespace Dasher; /** * A useless, but concrete implementation of CDasherInterfaceBase * used for unit testing purposes. Allows us to instantiate * CDasherInterfaceBase without delving into platform specific code. */ class CMockInterfaceBase : public CDasherInterfaceBase { - - public: - - CMockInterfaceBase() : CDasherInterfaceBase() {}; - - void CreateModules() {}; - - void SetupPaths() {}; - - void ScanAlphabetFiles(std::vector<std::string> &vFileList) {}; - - void ScanColourFiles(std::vector<std::string> &vFileList) {}; - - void SetupUI() {}; - - void CreateSettingsStore() {}; - - int GetFileSize(const std::string &strFileName) { return 0; }; - - void StartTimer() {}; - - void ShutdownTimer() {}; - + + public: + + CMockInterfaceBase() : CDasherInterfaceBase() {}; + + void CreateModules() {}; + + void SetupPaths() {}; + + void ScanAlphabetFiles(std::vector<std::string> &vFileList) {}; + + void ScanColourFiles(std::vector<std::string> &vFileList) {}; + + void SetupUI() {}; + + void CreateSettingsStore() {}; + + int GetFileSize(const std::string &strFileName) { return 0; }; + + void StartTimer() {}; + + void ShutdownTimer() {}; + }; + +#endif diff --git a/Src/TestPlatform/MockSettingsStore.h b/Src/TestPlatform/MockSettingsStore.h index 33cc0d2..6346a57 100644 --- a/Src/TestPlatform/MockSettingsStore.h +++ b/Src/TestPlatform/MockSettingsStore.h @@ -1,25 +1,30 @@ +#ifndef __MockSettingsStore_h__ +#define __MockSettingsStore_h__ + #include "../DasherCore/SettingsStore.h" using namespace Dasher; /** * A useless, but concrete implementation of CSettingsStore. * used for unit testing purposes. Allows us to instantiate * CSettingsStore without using platform specific code. */ class CMockSettingsStore : public CSettingsStore { - public: - - CMockSettingsStore(Dasher::CEventHandler * pEventHandler) : CSettingsStore(pEventHandler) {} - - bool LoadSetting(const std::string & Key, bool * Value) { return true; } - - bool LoadSetting(const std::string & Key, long * Value) { return true; } - - void SaveSetting(const std::string & Key, bool Value) {} - - void SaveSetting(const std::string & Key, long Value) {} - - void SaveSetting(const std::string & Key, const std::string & Value) {} + public: + + CMockSettingsStore(Dasher::CEventHandler * pEventHandler) : CSettingsStore(pEventHandler) {} + + bool LoadSetting(const std::string & Key, bool * Value) { return true; } + + bool LoadSetting(const std::string & Key, long * Value) { return true; } + + void SaveSetting(const std::string & Key, bool Value) {} + + void SaveSetting(const std::string & Key, long Value) {} + + void SaveSetting(const std::string & Key, const std::string & Value) {} }; + +#endif diff --git a/Testing/dasher_tests/WordGenTest.cpp b/Testing/dasher_tests/WordGenTest.cpp index a16df4d..eaa8c5f 100644 --- a/Testing/dasher_tests/WordGenTest.cpp +++ b/Testing/dasher_tests/WordGenTest.cpp @@ -1,69 +1,69 @@ #include "gtest/gtest.h" -#include "../../Src/DasherCore/FileWordGenerator.h" +#include "../../Src/TestPlatform/MockFileWordGenerator.h" using namespace Dasher; /* * Test fixture */ class WordGenTest : public ::testing::Test { public: WordGenTest() { - fullGen = new CFileWordGenerator("test_data/word_gen_full_data.txt"); - singleLineGen = new CFileWordGenerator("test_data/word_gen_single_line.txt"); + fullGen = new MockFileWordGenerator("test_data/word_gen_full_data.txt"); + singleLineGen = new MockFileWordGenerator("test_data/word_gen_single_line.txt"); } protected: - CFileWordGenerator* fullGen; - CFileWordGenerator* singleLineGen; + MockFileWordGenerator* fullGen; + MockFileWordGenerator* singleLineGen; }; /* * Tests whether the word fullGenerator opens a file * correctly. */ TEST_F(WordGenTest, FileOpensCorrectly) { bool opened = fullGen->GetFileHandle().is_open(); bool good = fullGen->GetFileHandle().good(); ASSERT_EQ(opened, true); ASSERT_EQ(good, true); } /* * Tests whether the file name getter returns expected results. */ TEST_F(WordGenTest, FilenameExtraction) { ASSERT_EQ("word_gen_full_data.txt", fullGen->GetFilename()); } /* * Tests if retrieving the next word returns expected results. */ TEST_F(WordGenTest, WordIteration) { ASSERT_EQ("I'm", fullGen->GetNextWord()); ASSERT_EQ("a", fullGen->GetNextWord()); } /* * Tests if the word generator actually grabs the right amount of data * from the stream */ TEST_F(WordGenTest, GetBuffer) { std::ifstream fin; std::string buffer; fin.open("test_data/word_gen_single_line.txt"); std::getline(fin, buffer); ASSERT_EQ(buffer, singleLineGen->GetWholeBuffer()); } /* This test /should/ determine whether we return the right value when * we reach the end of a file...Not sure what's causing this to fail now */ TEST_F(WordGenTest, EndsAtEOF) { for(int i = 0; i < 1000; i++) singleLineGen->GetNextWord(); ASSERT_EQ("", singleLineGen->GetNextWord()); }
rgee/HFOSS-Dasher
daebef18448f3324859e480d3af54fef0164c044
Of course, forgot to actually add the changed files on that last commit
diff --git a/Data/GUI/dasher.compose.ui b/Data/GUI/dasher.compose.ui index 247baa4..8791aa5 100644 --- a/Data/GUI/dasher.compose.ui +++ b/Data/GUI/dasher.compose.ui @@ -1,546 +1,539 @@ <?xml version="1.0"?> <!--*- mode: xml -*--> <interface> <object class="GtkAdjustment" id="adjustment1"> <property name="upper">8</property> <property name="lower">0.1</property> <property name="page_increment">1</property> <property name="step_increment">0.1</property> <property name="page_size">0</property> <property name="value">1</property> </object> <object class="GtkUIManager" id="uimanager1"> <child> <object class="GtkActionGroup" id="actiongroup1"> <child> <object class="GtkAction" id="menuitem4"> <property name="name">menuitem4</property> <property name="label" translatable="yes">_File</property> </object> </child> <child> <object class="GtkAction" id="menunew"> <property name="stock_id">gtk-new</property> <property name="name">menunew</property> <signal handler="select_new_file" name="activate"/> </object> </child> - <child> - <object class="GtkAction" id="menuopen"> - <property name="stock_id">gtk-open</property> - <property name="name">menuopen</property> - <signal handler="select_open_file" name="activate"/> - </object> - </child> <child> <object class="GtkAction" id="menusave"> <property name="stock_id">gtk-save</property> <property name="name">menusave</property> <signal handler="save_file" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menusaveas"> <property name="stock_id">gtk-save-as</property> <property name="name">menusaveas</property> <signal handler="select_save_file_as" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menuappend"> <property name="name">menuappend</property> <property name="label" translatable="yes">A_ppend to file</property> <signal handler="select_append_file" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menuimport"> <property name="name">menuimport</property> <property name="label" translatable="yes">_Import Training Text</property> <signal handler="select_import_file" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menuquit"> <property name="stock_id">gtk-quit</property> <property name="name">menuquit</property> <signal handler="ask_save_before_exit" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menuitem5"> <property name="name">menuitem5</property> <property name="label" translatable="yes">_Edit</property> </object> </child> <child> <object class="GtkAction" id="menucut"> <property name="stock_id">gtk-cut</property> <property name="name">menucut</property> <signal handler="clipboard_cut" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menucopy"> <property name="stock_id">gtk-copy</property> <property name="name">menucopy</property> <signal handler="clipboard_copy" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menucopyall"> <property name="name">menucopyall</property> <property name="label" translatable="yes">Copy _All</property> <signal handler="clipboard_copy_all" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menupaste"> <property name="stock_id">gtk-paste</property> <property name="name">menupaste</property> <signal handler="clipboard_paste" name="activate"/> </object> </child> <child> <object class="GtkAction" id="menupreferences"> <property name="stock_id">gtk-preferences</property> <property name="name">menupreferences</property> <property name="label" translatable="yes">Pr_eferences</property> <signal handler="preferences_display" name="activate"/> </object> <accelerator key="S" modifiers="GDK_CONTROL_MASK | GDK_SHIFT_MASK"/> </child> <child> <object class="GtkAction" id="menuitem7"> <property name="name">menuitem7</property> <property name="label" translatable="yes">_Help</property> </object> </child> <child> <object class="GtkAction" id="menututorial"> <property name="name">menututorial</property> <property name="label" translatable="yes">Dasher _Tutorial</property> <signal handler="on_menututorial_activate" name="activate"/> </object> </child> <child> <object class="GtkAction" id="help_contents"> <property name="stock_id">gtk-help</property> <property name="name">help_contents</property> <property name="label" translatable="yes">_Contents</property> <signal handler="show_help" name="activate"/> </object> <accelerator key="F1" modifiers="0"/> </child> <child> <object class="GtkAction" id="menuabout"> <property name="stock_id">gtk-about</property> <property name="name">menuabout</property> <property name="label" translatable="yes">_About</property> <signal handler="about_dasher" name="activate"/> </object> </child> </object> </child> <ui> <menubar name="dasher_menu_bar"> <menu action="menuitem4"> <menuitem action="menunew"/> <menuitem action="menuopen"/> <menuitem action="menusave"/> <menuitem action="menusaveas"/> <menuitem action="menuappend"/> <separator/> <menuitem action="menuimport"/> <menuitem action="menuquit"/> </menu> <menu action="menuitem5"> <menuitem action="menucut"/> <menuitem action="menucopy"/> <menuitem action="menucopyall"/> <menuitem action="menupaste"/> <separator/> <menuitem action="menupreferences"/> </menu> <menu action="menuitem7"> <menuitem action="menututorial"/> <separator/> <menuitem action="help_contents"/> <menuitem action="menuabout"/> </menu> </menubar> </ui> </object> <object class="GtkWindow" id="window"> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="events">GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">Dasher</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_NONE</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">False</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <signal handler="ask_save_before_exit" name="delete_event"/> <signal handler="on_window_map" name="map"/> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkMenuBar" constructor="uimanager1" id="dasher_menu_bar"> <property name="visible">True</property> <property name="pack_direction">GTK_PACK_DIRECTION_LTR</property> <property name="child_pack_direction">GTK_PACK_DIRECTION_LTR</property> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkToolbar" id="toolbar"> <property name="orientation">GTK_ORIENTATION_HORIZONTAL</property> <property name="toolbar_style">GTK_TOOLBAR_ICONS</property> <property name="tooltips">True</property> <property name="show_arrow">True</property> <child> <object class="GtkToolButton" id="New"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">New file</property> <property name="stock_id">gtk-new</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> <property name="is_important">False</property> <signal handler="select_new_file" name="clicked"/> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="Open"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Open file</property> <property name="stock_id">gtk-open</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> <property name="is_important">False</property> <signal handler="select_open_file" name="clicked"/> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="Save"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Save file</property> <property name="stock_id">gtk-save</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> <property name="is_important">False</property> <signal handler="save_file" name="clicked"/> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="SaveAs"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Save file as</property> <property name="stock_id">gtk-save-as</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> <property name="is_important">False</property> <signal handler="select_save_file_as" name="clicked"/> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkSeparatorToolItem" id="separatortoolitem1"> <property name="visible">True</property> <property name="draw">True</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> </object> <packing> <property name="expand">False</property> <property name="homogeneous">False</property> </packing> </child> <child> <object class="GtkToolButton" id="Cut"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Cut</property> <property name="stock_id">gtk-cut</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> <property name="is_important">False</property> <signal handler="clipboard_cut" name="clicked"/> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="Copy"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Copy</property> <property name="stock_id">gtk-copy</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> <property name="is_important">False</property> <signal handler="clipboard_copy" name="clicked"/> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> <child> <object class="GtkToolButton" id="Paste"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Paste</property> <property name="stock_id">gtk-paste</property> <property name="visible_horizontal">True</property> <property name="visible_vertical">True</property> <property name="is_important">False</property> <signal handler="clipboard_paste" name="clicked"/> </object> <packing> <property name="expand">False</property> <property name="homogeneous">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkHBox" id="hbox7"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkVBox" id="SideMenu"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <signal handler="sidemenu_press" name="button_press_event"/> <signal handler="sidemenu_release" name="button_release_event"/> <child> <object class="GtkButton" id="button32"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="relief">GTK_RELIEF_NORMAL</property> <property name="focus_on_click">True</property> <signal handler="sidemenu_press" name="button_press_event"/> <signal handler="sidemenu_release" name="button_release_event"/> <signal handler="sidemenu_motion" name="motion_notify_event"/> <child> <object class="GtkImage" id="image9"> <property name="visible">True</property> <property name="stock">gtk-preferences</property> <property name="icon_size">4</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">0</property> <property name="ypad">0</property> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkButton" id="button31"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="relief">GTK_RELIEF_NORMAL</property> <property name="focus_on_click">True</property> <signal handler="sidemenu_press" name="button_press_event"/> <signal handler="sidemenu_release" name="button_release_event"/> <signal handler="sidemenu_motion" name="motion_notify_event"/> <child> <placeholder/> </child> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkButton" id="button33"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="relief">GTK_RELIEF_NORMAL</property> <property name="focus_on_click">True</property> <signal handler="toggle_hidden" name="clicked"/> <child> <object class="GtkArrow" id="hide_arrow"> <property name="visible">True</property> <property name="arrow_type">GTK_ARROW_RIGHT</property> <property name="shadow_type">GTK_SHADOW_OUT</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">0</property> <property name="ypad">0</property> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkVBox" id="vbox45"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkAlignment" id="alignment42"> <property name="visible">True</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xscale">1</property> <property name="yscale">1</property> <property name="top_padding">0</property> <property name="bottom_padding">0</property> <property name="left_padding">0</property> <property name="right_padding">0</property> <child> <object class="GtkHPaned" id="hpaned1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <object class="Custom" id="DasherControl"> <property name="width_request">200</property> <property name="height_request">200</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="creation_function">create_dasher_control</property> <property name="int1">0</property> <property name="int2">0</property> <signal handler="parameter_notification" name="dasher_changed"/> <signal handler="handle_start_event" name="dasher_start"/> <signal handler="handle_stop_event" name="dasher_stop"/> <signal handler="handle_control_event" name="dasher_control"/> <signal handler="gtk2_edit_output_callback" name="dasher_edit_insert"/> <signal handler="gtk2_edit_delete_callback" name="dasher_edit_delete"/> <signal handler="handle_context_request" name="dasher_context_request"/> <signal handler="handle_request_settings" name="dasher_request_settings"/> <signal handler="focus_in_event" name="focus_in_event"/> <signal handler="on_lock_info" name="dasher_lock_info"/> <signal handler="on_message" name="dasher_message"/> <signal handler="convert_cb" name="dasher_edit_convert"/> <signal handler="protect_cb" name="dasher_edit_protect"/> <signal handler="on_command" name="dasher_command"/> </object> <packing> <property name="shrink">True</property> <property name="resize">True</property> </packing> </child> <child> <object class="GtkHBox" id="vbox40"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkScrolledWindow" id="scrolledwindow5"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="vscrollbar_policy">GTK_POLICY_AUTOMATIC</property> <property name="shadow_type">GTK_SHADOW_IN</property> <property name="window_placement">GTK_CORNER_TOP_LEFT</property> <child> <object class="GtkTextView" id="the_text_view"> <property name="visible">True</property> <property name="can_default">True</property> <property name="can_focus">True</property> <property name="events">GDK_BUTTON_PRESS_MASK | GDK_KEY_PRESS_MASK</property> <property name="editable">True</property> <property name="overwrite">False</property> <property name="accepts_tab">True</property> <property name="justification">GTK_JUSTIFY_LEFT</property> <property name="wrap_mode">GTK_WRAP_WORD</property> <property name="cursor_visible">True</property> <property name="pixels_above_lines">0</property> <property name="pixels_below_lines">0</property> <property name="pixels_inside_wrap">0</property> <property name="left_margin">0</property> <property name="right_margin">0</property> <property name="indent">0</property> <signal handler="edit_focus_in_event" name="focus_in_event"/> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkVBox" id="vbox39"> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <placeholder/> </child> <child> <placeholder/> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">True</property> </packing> </child> </object> <packing> <property name="shrink">True</property> <property name="resize">True</property> </packing> </child> </object> </child> </object> diff --git a/Data/GUI/dasher.traditional.ui b/Data/GUI/dasher.traditional.ui index 58ec38b..8a2378a 100644 --- a/Data/GUI/dasher.traditional.ui +++ b/Data/GUI/dasher.traditional.ui @@ -1,452 +1,461 @@ <?xml version="1.0"?> <!--*- mode: xml -*--> <interface> <object class="GtkAdjustment" id="adjustment1"> <property name="upper">8</property> <property name="lower">0.1</property> <property name="page_increment">1</property> <property name="step_increment">0.1</property> <property name="page_size">0</property> <property name="value">1</property> </object> <object class="GtkUIManager" id="uimanager1"> <child> <object class="GtkActionGroup" id="actiongroup1"> <child> <object class="GtkAction" id="file_menu"> <property name="label" translatable="yes">_File</property> </object> </child> <child> <object class="GtkAction" id="action_new"> <property name="stock_id">gtk-new</property> <property name="tooltip" translatable="yes">New file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_open"> <property name="stock_id">gtk-open</property> <property name="tooltip" translatable="yes">Open file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_save"> <property name="stock_id">gtk-save</property> <property name="tooltip" translatable="yes">Save file</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_saveas"> <property name="stock_id">gtk-save-as</property> <property name="tooltip" translatable="yes">Save file as</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_append"> <property name="name">action_append</property> <property name="label" translatable="yes">A_ppend to file…</property> </object> </child> <child> <object class="GtkAction" id="action_import"> <property name="label" translatable="yes">_Import Training Text…</property> <signal name="activate" handler="dasher_main_cb_import"/> </object> </child> <child> <object class="GtkAction" id="action_quit"> <property name="stock_id">gtk-quit</property> <property name="tooltip" translatable="yes">Quit</property> <signal name="activate" handler="dasher_main_cb_quit"/> </object> </child> <child> <object class="GtkAction" id="edit_menu"> <property name="label" translatable="yes">_Edit</property> </object> </child> <child> <object class="GtkAction" id="action_cut"> <property name="stock_id">gtk-cut</property> <property name="tooltip" translatable="yes">Cut</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copy"> <property name="stock_id">gtk-copy</property> <property name="tooltip" translatable="yes">Copy</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_copyall"> <property name="label" translatable="yes">Copy _All</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_paste"> <property name="stock_id">gtk-paste</property> <property name="tooltip" translatable="yes">Paste</property> <signal name="activate" handler="dasher_main_cb_editor"/> </object> </child> <child> <object class="GtkAction" id="action_preferences"> <property name="stock_id">gtk-preferences</property> <property name="label" translatable="yes">Pr_eferences…</property> <property name="tooltip" translatable="yes">Preferences</property> <signal name="activate" handler="dasher_main_cb_preferences"/> </object> <accelerator key="S" modifiers="GDK_CONTROL_MASK | GDK_SHIFT_MASK"/> </child> <child> <object class="GtkAction" id="help_menu"> <property name="label" translatable="yes">_Help</property> </object> </child> <child> <object class="GtkAction" id="action_help"> <property name="stock_id">gtk-help</property> <property name="label" translatable="yes">_Contents…</property> <property name="tooltip" translatable="yes">Help</property> <signal name="activate" handler="dasher_main_cb_help"/> </object> <accelerator key="F1" modifiers="0"/> </child> <child> <object class="GtkAction" id="action_about"> <property name="stock_id">gtk-about</property> <property name="label" translatable="yes">_About…</property> <signal name="activate" handler="dasher_main_cb_about"/> </object> </child> + <child> + <object class="GtkAction" id="action_toggle_game_mode"> + <property name="stock_id">action_toggle_game_mode</property> + <property name="tooltip" translatable="yes">_Enter Game Mode</property> + <propterty name = "label" translatable="yes">_Enter GameMode</property> + <signal name="activate" handler="dasher_main_cb_about"/> + </object> + </child> </object> </child> <ui> <menubar name="dasher_menu_bar"> <menu action="file_menu"> <menuitem action="action_new"/> <menuitem action="action_open"/> <menuitem action="action_save"/> <menuitem action="action_saveas"/> <menuitem action="action_append"/> + <menuitem action="action_toggle_game_mode"/> <separator/> <menuitem action="action_import"/> <menuitem action="action_quit"/> </menu> <menu action="edit_menu"> <menuitem action="action_cut"/> <menuitem action="action_copy"/> <menuitem action="action_copyall"/> <menuitem action="action_paste"/> <separator/> <menuitem action="action_preferences"/> </menu> <menu action="help_menu"> <menuitem action="action_help"/> <menuitem action="action_about"/> </menu> </menubar> <toolbar name="dasher_tool_bar"> <toolitem action="action_new"/> <toolitem action="action_open"/> <toolitem action="action_save"/> <toolitem action="action_saveas"/> <separator/> <toolitem action="action_cut"/> <toolitem action="action_copy"/> <toolitem action="action_paste"/> <separator/> <toolitem action="action_preferences"/> <toolitem action="action_help"/> <separator/> <toolitem action="action_quit"/> </toolbar> </ui> </object> <object class="GtkWindow" id="window"> <property name="can_focus">True</property> <property name="has_focus">True</property> <property name="events">GDK_BUTTON_RELEASE_MASK</property> <property name="title" translatable="yes">Dasher</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_NONE</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">False</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <signal handler="dasher_main_cb_window_close" name="delete_event"/> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkMenuBar" constructor="uimanager1" id="dasher_menu_bar"> <property name="visible">True</property> <property name="tooltip-text" translatable="yes">Quit</property> <property name="pack_direction">GTK_PACK_DIRECTION_LTR</property> <property name="child_pack_direction">GTK_PACK_DIRECTION_LTR</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkToolbar" constructor="uimanager1" id="dasher_tool_bar"> <property name="toolbar_style">GTK_TOOLBAR_ICONS</property> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkVPaned" id="main_divider"> <property name="visible">True</property> <property name="position">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="DasherEditorInternal" id="DasherEditor"> <property name="visible">True</property> <property name="can_focus">True</property> <signal handler="dasher_main_cb_filename_changed" name="filename_changed"/> <signal handler="dasher_main_cb_buffer_changed" name="buffer_changed"/> <signal handler="dasher_main_cb_context_changed" name="context_changed"/> </object> <packing> <property name="shrink">True</property> <property name="resize">False</property> </packing> </child> <child> <object class="GtkDasherControl" id="DasherControl"> <property name="width_request">200</property> <property name="height_request">200</property> <property name="visible">True</property> <signal handler="parameter_notification" name="dasher_changed"/> <signal handler="handle_start_event" name="dasher_start"/> <signal handler="handle_stop_event" name="dasher_stop"/> <signal handler="handle_control_event" name="dasher_control"/> <signal handler="gtk2_edit_output_callback" name="dasher_edit_insert"/> <signal handler="gtk2_edit_delete_callback" name="dasher_edit_delete"/> <signal handler="handle_context_request" name="dasher_context_request"/> <signal handler="handle_request_settings" name="dasher_request_settings"/> <signal handler="focus_in_event" name="focus_in_event"/> <signal handler="on_lock_info" name="dasher_lock_info"/> <signal handler="on_message" name="dasher_message"/> <signal handler="convert_cb" name="dasher_edit_convert"/> <signal handler="protect_cb" name="dasher_edit_protect"/> <signal handler="on_command" name="dasher_command"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="shrink">True</property> <property name="resize">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> <child> <object class="GtkHBox" id="hbox8"> <property name="border_width">2</property> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">2</property> <signal handler="test_focus_handler" name="focus-in-event"/> <child> <object class="GtkLabel" id="label109"> <property name="visible">True</property> <property name="label" translatable="yes">Speed:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbutton1"> <property name="width_request">64</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="climb_rate">0.10000000149</property> <property name="digits">1</property> <property name="numeric">True</property> <property name="update_policy">GTK_UPDATE_IF_VALID</property> <property name="snap_to_ticks">False</property> <property name="wrap">False</property> <property name="adjustment">adjustment1</property> <signal handler="speed_changed" name="value-changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkLabel" id="label110"> <property name="visible">True</property> <property name="label" translatable="yes">Alphabet:</property> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">2</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkComboBox" id="combobox1"> <property name="width_request">32</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="add_tearoffs">False</property> <property name="focus_on_click">True</property> <signal handler="alphabet_combo_changed" name="changed"/> <signal handler="test_focus_handler" name="focus-in-event"/> </object> <packing> <property name="padding">0</property> <property name="expand">True</property> <property name="fill">True</property> </packing> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">True</property> </packing> </child> </object> </child> </object> <object class="GtkWindow" id="lock_window"> <property name="visible">True</property> <property name="title" translatable="yes">Please Wait…</property> <property name="type">GTK_WINDOW_TOPLEVEL</property> <property name="window_position">GTK_WIN_POS_CENTER_ON_PARENT</property> <property name="modal">False</property> <property name="resizable">True</property> <property name="destroy_with_parent">True</property> <property name="decorated">True</property> <property name="skip_taskbar_hint">False</property> <property name="skip_pager_hint">False</property> <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property> <property name="gravity">GDK_GRAVITY_NORTH_WEST</property> <property name="focus_on_map">True</property> <property name="urgency_hint">False</property> <child> <object class="GtkVBox" id="vbox43"> <property name="visible">True</property> <property name="homogeneous">False</property> <property name="spacing">0</property> <child> <object class="GtkLabel" id="lock_message"> <property name="visible">True</property> <property name="label"/> <property name="use_underline">False</property> <property name="use_markup">False</property> <property name="justify">GTK_JUSTIFY_LEFT</property> <property name="wrap">False</property> <property name="selectable">False</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xpad">0</property> <property name="ypad">0</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> <property name="width_chars">-1</property> <property name="single_line_mode">False</property> <property name="angle">0</property> </object> <packing> <property name="padding">8</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> <child> <object class="GtkAlignment" id="alignment38"> <property name="border_width">8</property> <property name="visible">True</property> <property name="xalign">0.5</property> <property name="yalign">0.5</property> <property name="xscale">1</property> <property name="yscale">1</property> <property name="top_padding">0</property> <property name="bottom_padding">0</property> <property name="left_padding">0</property> <property name="right_padding">0</property> <child> <object class="GtkProgressBar" id="lock_progress"> <property name="visible">True</property> <property name="orientation">GTK_PROGRESS_LEFT_TO_RIGHT</property> <property name="fraction">0</property> <property name="pulse_step">0.10000000149</property> <property name="ellipsize">PANGO_ELLIPSIZE_NONE</property> </object> </child> </object> <packing> <property name="padding">0</property> <property name="expand">False</property> <property name="fill">False</property> </packing> </child> </object> </child> </object> </interface> diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index 3869db1..8a467d5 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,111 +1,116 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. GTEST_DIR = ../gtest #Points to the root of Dasher's source code DASHER_CORE_DIR = ../../Src/DasherCore TEST_PLATFORM_DIR = ../../Src/TestPlatform # Where to find user code. USER_DIR = . # Where to find dasher object files DASHER_SANDBOX_DIR = ../../dasher-sandbox/Src DASHER_DIR = ../../Src # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include -I$(DASHER_DIR)/DasherCore # Flags passed to the C++ compiler. CXXFLAGS += -g # All tests produced by this Makefile. Remember to add new tests you # created to the list. TESTS = EventTest WordGenTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) +install : + +uninstall : + clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. A test should link with either gtest.a or # gtest_main.a, depending on whether it defines its own main() # function. #sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc #sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ # $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc #sample1_unittest : sample1.o sample1_unittest.o gtest_main.a # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ WordGenTest.o : $(USER_DIR)/WordGenTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/WordGenTest.cpp WordGenTest : WordGenTest.o \ gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ $(DASHER_CORE_DIR)/libdasherprefs.a \ $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@ EventTest.o : $(USER_DIR)/EventTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp EventTest : EventTest.o \ gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ $(DASHER_CORE_DIR)/libdasherprefs.a \ $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@ +
rgee/HFOSS-Dasher
855e9b8e29a10e038014161254725f2df343fd4e
Cleaned up the internals of FileWordGenerator. These were transparent changes.
diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index f65c7d3..2ab3d36 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,70 +1,56 @@ #include "FileWordGenerator.h" using namespace Dasher; bool CFileWordGenerator::Generate() { if(!m_sFileHandle.is_open()) { m_sFileHandle.open(m_sPath.c_str()); } if(m_sFileHandle.fail()) { - throw std::runtime_error(m_sPath + " does not exist"); + throw std::runtime_error("File: " + m_sPath + " cannot be read."); } m_uiPos = 0; m_sGeneratedString.clear(); + if(m_sFileHandle.eof()) { - m_sCurrentWord = ""; return false; } else if(m_sFileHandle.good()) { std::getline(m_sFileHandle, m_sGeneratedString); - FindNextWord(); return true; } else { return false; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")+1); } std::string CFileWordGenerator::GetNextWord() { - std::string result = m_sCurrentWord; - FindNextWord(); - - return result; -} - -void CFileWordGenerator::FindNextWord() { - std::string result; - - // We are at the end of the buffer. if(m_uiPos >= m_sGeneratedString.length()) { // Attempt to reload the buffer. - if(!Generate()) - { - // If file IO fails, set the current word to empty. - result = ""; - m_sCurrentWord = result; - return; - } + if(!Generate()) return ""; } size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); + std::string result; - // If there are no space characters. + // If there are no space characters. if(found != string::npos) { result = m_sGeneratedString.substr(m_uiPos, found); m_uiPos += (found + 1); } else { result = m_sGeneratedString.substr(m_uiPos); - } - m_sCurrentWord = result; + }; + + return result; } + diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index 9975959..a229fb7 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,135 +1,114 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> #include <stdexcept> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE * kept open for the lifetime of this object and the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all * at once. */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string sPath, int iRegen) : m_sPath(sPath), CWordGeneratorBase(iRegen) { Generate(); } CFileWordGenerator(std::string sPath) : m_sPath(sPath), CWordGeneratorBase() { Generate(); } virtual ~CFileWordGenerator() { m_sFileHandle.close(); } - - - /** * Returns the next word that was read * @return The next word in the word generator model if there is one. - * Otherwise, returns an empty string. + * Otherwise, returns an empty string if there are no more + * words. + * @throw Throws an exception if the file cannot be read. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter. Returns the file name and extension, without * any slashes. * @return The actual name of the file being read from */ std::string GetFilename(); + private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ - - /** - * Find the next word in the generated string buffer. - * This does NOT return that string, which is why this is not a public - * facing method. It only updates the current string to be presented. - * - * @warning Ensure that this is called whenever m_sGeneratedString is - * remade or whenever the current word is actually presented - * to a client. - */ - void FindNextWord(); - /** - * The generator function. In this implementation, it reads from a - * io has failed for some reason. - * file to produce strings.In this implementation, failure means file - */ - bool Generate(); + /** + * The generator function. Reads words from the specified file. + * @return True if generating the new buffer was successful, + * false if we've reached the end of the file. + * @throw Throws an exception if the file cannot be read. + */ + bool Generate(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ - /** - * The current word we're looking at. This is the next word that - * will be returned when GetNextWord is called. - */ - std::string m_sCurrentWord; - /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; - /** - * Flag for whether there are words left in this model. - */ - bool m_bWordsLeft; - /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h index 453bd70..4b9515b 100644 --- a/Src/DasherCore/WordGeneratorBase.h +++ b/Src/DasherCore/WordGeneratorBase.h @@ -1,66 +1,72 @@ #ifndef __WordGeneratorBase_h__ #define __WordGeneratorBase_h__ #include <string> using namespace std; namespace Dasher { /** * The base class for all word generators. Word generators encapsulate * logic for simply generating words based on implementation-specific * conditions. The benefit of this is that a generator can * easily be written that selects words based on a function of the current * value of the Sri Lankan rupee and the amount of twitter feeds regarding * the winter olympics, for example. * * * A typical use case for any class deriving from CWordGeneratorBase * would be the following: * 1) Construct the object (providing any implementation-specific params) - * - The words will be generated on construction. - * + * * * 2) To retrieve a word, simply call GetNextWord. This will continue * until the specific implementation determines that there are no * more words for any reason. When there are no more, GetNextWord * returns the empty string. + * + * Usage Example: + * CWordGeneratorBase gen = CWordGeneratorBase(params...); + * std::string word; + * while ((word = gen.GetNextWord()) != "") { + * Operate on the word + * } */ class CWordGeneratorBase { public: CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} CWordGeneratorBase() : m_iRegenTime(0), m_bWordsReady(false) {} virtual ~CWordGeneratorBase() { } /** * Gets a single word based on the generation rules. * @pre { Generate must have been called at least once. } * @return The next string from this generator */ virtual std::string GetNextWord() = 0; /** * -- NOT YET IMPLEMENTED -- * Gets the previous word in the generated string based on generation rules. * @pre { Generate must have been called at least once. } * @return The previous string from this generator */ //virtual std::string GetPreviousWord() = 0; protected: /** * The time in seconds after which a generator should regenerate. */ int m_iRegenTime; /** * A boolean representing whether the words have been generated yet. */ bool m_bWordsReady; }; } #endif
rgee/HFOSS-Dasher
3f59cc79bf96edae0b754e5a8655489c79609c9c
Generate is no longer required for WordGenerators. The constructor of FileWordGenerator now throws an exception if the file does not exist.
diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 22a7b3a..f65c7d3 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,67 +1,70 @@ #include "FileWordGenerator.h" using namespace Dasher; bool CFileWordGenerator::Generate() { - if(!m_sFileHandle.is_open()) + if(!m_sFileHandle.is_open()) { m_sFileHandle.open(m_sPath.c_str()); + } + if(m_sFileHandle.fail()) { + throw std::runtime_error(m_sPath + " does not exist"); + } - m_uiPos = 0; m_sGeneratedString.clear(); if(m_sFileHandle.eof()) { m_sCurrentWord = ""; return false; } else if(m_sFileHandle.good()) { std::getline(m_sFileHandle, m_sGeneratedString); FindNextWord(); return true; } else { return false; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")+1); } std::string CFileWordGenerator::GetNextWord() { std::string result = m_sCurrentWord; FindNextWord(); return result; } void CFileWordGenerator::FindNextWord() { std::string result; // We are at the end of the buffer. if(m_uiPos >= m_sGeneratedString.length()) { // Attempt to reload the buffer. if(!Generate()) { // If file IO fails, set the current word to empty. result = ""; m_sCurrentWord = result; return; } } size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); // If there are no space characters. if(found != string::npos) { result = m_sGeneratedString.substr(m_uiPos, found); m_uiPos += (found + 1); } else { result = m_sGeneratedString.substr(m_uiPos); } m_sCurrentWord = result; } diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index 974135a..9975959 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,137 +1,135 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> +#include <stdexcept> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE * kept open for the lifetime of this object and the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all * at once. */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string sPath, int iRegen) : m_sPath(sPath), - m_sCurrentWord(""), - CWordGeneratorBase(iRegen) - {Generate();} + CWordGeneratorBase(iRegen) { + Generate(); + } + CFileWordGenerator(std::string sPath) : m_sPath(sPath), - m_sCurrentWord(""), - CWordGeneratorBase(0) - {Generate();} + CWordGeneratorBase() { + Generate(); + } virtual ~CFileWordGenerator() { m_sFileHandle.close(); } - /** - * The generator function. In this implementation, it reads from a - * file to produce strings.In this implementation, failure means file - * io has failed for some reason. - * @see CWordGeneratorBase::Generate - */ - virtual bool Generate(); + /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter. Returns the file name and extension, without * any slashes. * @return The actual name of the file being read from */ std::string GetFilename(); - - - std::ifstream& GetFileHandle() { return m_sFileHandle; } - std::string GetWholeBuffer() { return m_sGeneratedString; } - size_t GetStringPosition() { return m_uiPos; } private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Find the next word in the generated string buffer. * This does NOT return that string, which is why this is not a public * facing method. It only updates the current string to be presented. * * @warning Ensure that this is called whenever m_sGeneratedString is * remade or whenever the current word is actually presented * to a client. */ void FindNextWord(); + + /** + * The generator function. In this implementation, it reads from a + * io has failed for some reason. + * file to produce strings.In this implementation, failure means file + */ + bool Generate(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * The current word we're looking at. This is the next word that * will be returned when GetNextWord is called. */ std::string m_sCurrentWord; /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * Flag for whether there are words left in this model. */ bool m_bWordsLeft; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h index c2e0bf5..453bd70 100644 --- a/Src/DasherCore/WordGeneratorBase.h +++ b/Src/DasherCore/WordGeneratorBase.h @@ -1,71 +1,66 @@ #ifndef __WordGeneratorBase_h__ #define __WordGeneratorBase_h__ #include <string> using namespace std; namespace Dasher { /** * The base class for all word generators. Word generators encapsulate * logic for simply generating words based on implementation-specific - * conditions. Currently, this is being used to wrap GameMode's simple - * text-file reading mechanism, but another generator can easily be - * written that selects words based on a function of the current value - * of the Sri Lankan rupee and the amount of twitter feeds regarding + * conditions. The benefit of this is that a generator can + * easily be written that selects words based on a function of the current + * value of the Sri Lankan rupee and the amount of twitter feeds regarding * the winter olympics, for example. * * * A typical use case for any class deriving from CWordGeneratorBase * would be the following: * 1) Construct the object (providing any implementation-specific params) * - The words will be generated on construction. * * 2) To retrieve a word, simply call GetNextWord. This will continue * until the specific implementation determines that there are no * more words for any reason. When there are no more, GetNextWord * returns the empty string. */ class CWordGeneratorBase { public: CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} + + CWordGeneratorBase() : m_iRegenTime(0), m_bWordsReady(false) + {} virtual ~CWordGeneratorBase() { } /** * Gets a single word based on the generation rules. * @pre { Generate must have been called at least once. } * @return The next string from this generator */ virtual std::string GetNextWord() = 0; /** * -- NOT YET IMPLEMENTED -- * Gets the previous word in the generated string based on generation rules. * @pre { Generate must have been called at least once. } * @return The previous string from this generator */ //virtual std::string GetPreviousWord() = 0; protected: - /** - * Generate the words based on the generation rules - * @return True if the generation succeeded, false if not. - * @warning The return value of this function should always be checked - * in case it's using files or other solutions that can fail. - */ - virtual bool Generate() = 0; /** * The time in seconds after which a generator should regenerate. */ int m_iRegenTime; /** * A boolean representing whether the words have been generated yet. */ bool m_bWordsReady; }; } #endif diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index 3869db1..d8844d2 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,111 +1,111 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. GTEST_DIR = ../gtest #Points to the root of Dasher's source code DASHER_CORE_DIR = ../../Src/DasherCore TEST_PLATFORM_DIR = ../../Src/TestPlatform # Where to find user code. USER_DIR = . # Where to find dasher object files DASHER_SANDBOX_DIR = ../../dasher-sandbox/Src DASHER_DIR = ../../Src # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include -I$(DASHER_DIR)/DasherCore # Flags passed to the C++ compiler. CXXFLAGS += -g # All tests produced by this Makefile. Remember to add new tests you # created to the list. -TESTS = EventTest WordGenTest +TESTS = EventTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. A test should link with either gtest.a or # gtest_main.a, depending on whether it defines its own main() # function. #sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc #sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ # $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc #sample1_unittest : sample1.o sample1_unittest.o gtest_main.a # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ WordGenTest.o : $(USER_DIR)/WordGenTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/WordGenTest.cpp WordGenTest : WordGenTest.o \ gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ $(DASHER_CORE_DIR)/libdasherprefs.a \ $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@ EventTest.o : $(USER_DIR)/EventTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp EventTest : EventTest.o \ gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ $(DASHER_CORE_DIR)/libdasherprefs.a \ $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@
rgee/HFOSS-Dasher
6d8cf4eaee6f5f976e1627b0f1f5d60a23914465
Cleaned up the mess from debugging the segfault and the node-tagging weirdness
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index c0c5bbd..b424abc 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,824 +1,823 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { - if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { - CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); - - m_strGameTarget = pTargetChangedEvent->m_strTargetText; - } CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { + + CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; + + // Search from the current root. + m_Root->GameSearchChildren(m_strGameTarget); } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. //GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); //if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) if(pNode->GetFlag(NF_GAME)) { /*std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); }*/ - pNode->GameSearchChildren(m_strGameTarget); } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 03cc58d..0321981 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,148 +1,151 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; + m_pEventHandler->InsertEvent( + new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) + ); } } break; // Removed a character (Stepped one node back) case 0: break; default: break; } break; } case EV_GAME_NODE_DRAWN: { CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } break; /* case EV_TEXTDRAW: { CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; */ default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } m_pEventHandler->InsertEvent( - new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) + new CGameTargetChangedEvent(m_sTargetString.substr(0, 1)) ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 59b9f87..c006974 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,213 +1,211 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" #include "EventHandler.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); - - } virtual ~CGameModule() { }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
001ebe58c09ae5a828c84ab1a0f5103611499827
FIXED THE RANDOM SEGFAULT! Watch your if-statement blocks. :P
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index d7f6db8..d1bed94 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,129 +1,130 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif #include <sstream> void CEventHandler::InsertEvent(CEvent *pEvent) { //put the event at the end of the queue EnqueueEvent(pEvent); //if we are already dispatching events, don't do it again //this is necessary to keep recursive calls from removing //events from the queue while we iterate over it if(m_bIsDispatching) { - return; + return; } else { ProcessEventQueue(); } } void CEventHandler::ProcessEventQueue() { - + //iterate over the event queue until it's empty while(!m_qEventQueue.empty()) { - CEvent *currEvent = m_qEventQueue.front(); - m_qEventQueue.pop(); - - m_pInterface->InterfaceEventHandler(currEvent); + CEvent *currEvent = m_qEventQueue.front(); + m_qEventQueue.pop(); + + m_pInterface->InterfaceEventHandler(currEvent); m_pInterface->ExternalEventHandler(currEvent); - - //entering the dispatching loop - no longer safe to modify m_vSpecificListeners - m_bIsDispatching = true; - - //dispatch the event at the front of the queue to all registered listeners - for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[currEvent->m_iEventType - 1].begin(); - it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); ++it) + + //entering the dispatching loop - no longer safe to modify m_vSpecificListeners + m_bIsDispatching = true; + + //dispatch the event at the front of the queue to all registered listeners + for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[currEvent->m_iEventType - 1].begin(); + it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); ++it) { - (*it)->HandleEvent(currEvent); - } - - //done dispatching this event - safe to modify m_vSpecificListeners - m_bIsDispatching = false; - - //register all listeners that have been waiting to be added - for(EvtListenerCollection::iterator it = m_vPendingSpecificReg.begin(); it != m_vPendingSpecificReg.end(); ++it) - RegisterListener((*it).first, (*it).second); - - //unregister all that have been waiting to be removed - for(EvtListenerCollection::iterator it = m_vPendingSpecificUnreg.begin(); it != m_vPendingSpecificUnreg.end(); ++it) - UnregisterListener((*it).first, (*it).second); - - m_vPendingSpecificUnreg.clear(); - m_vPendingSpecificReg.clear(); + (*it)->HandleEvent(currEvent); + } + + //done dispatching this event - safe to modify m_vSpecificListeners + m_bIsDispatching = false; + + //register all listeners that have been waiting to be added + for(EvtListenerCollection::iterator it = m_vPendingSpecificReg.begin(); it != m_vPendingSpecificReg.end(); ++it) + RegisterListener((*it).first, (*it).second); + + //unregister all that have been waiting to be removed + for(EvtListenerCollection::iterator it = m_vPendingSpecificUnreg.begin(); it != m_vPendingSpecificUnreg.end(); ++it) + UnregisterListener((*it).first, (*it).second); + + m_vPendingSpecificUnreg.clear(); + m_vPendingSpecificReg.clear(); } } void CEventHandler::EnqueueEvent(CEvent *pEvent) { - m_qEventQueue.push(pEvent); + m_qEventQueue.push(pEvent); } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { - + // Only try to add a new listener if it doesn't already exist in the Listener map if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { if(!m_bIsDispatching) { m_vSpecificListeners[iEventType - 1].push_back(pListener); } else { // Add the listener to the pending set if events are being dispatched m_vPendingSpecificReg.push_back(std::make_pair(pListener, iEventType)); } } else { // Can't add the same listener twice } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - - for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { - RegisterListener(pListener, curEvtType); - } + + for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { + RegisterListener(pListener, curEvtType); + } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { - + if(!m_bIsDispatching) { - - for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType - 1].begin(); it != m_vSpecificListeners[iEventType - 1].end(); ++it) { - if((*it) == pListener) - m_vSpecificListeners[iEventType - 1].erase(it); - break; - } + + for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType - 1].begin(); it != m_vSpecificListeners[iEventType - 1].end(); ++it) { + if((*it) == pListener) { + m_vSpecificListeners[iEventType - 1].erase(it); + break; + } + } } else { - m_vPendingSpecificUnreg.push_back(std::make_pair(pListener, iEventType)); + m_vPendingSpecificUnreg.push_back(std::make_pair(pListener, iEventType)); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { - - for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { - UnregisterListener(pListener, curEvtType); - } + + for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { + UnregisterListener(pListener, curEvtType); + } }
rgee/HFOSS-Dasher
3740c8ce6f5cdc6c3231fd50b678d41704b4bb20
Added test data to version control
diff --git a/Testing/dasher_tests/test_data/word_gen_full_data.txt b/Testing/dasher_tests/test_data/word_gen_full_data.txt new file mode 100644 index 0000000..277e809 --- /dev/null +++ b/Testing/dasher_tests/test_data/word_gen_full_data.txt @@ -0,0 +1,79 @@ +I'm a senior at Cesar Chavez high in San Francisco's sunny Mission district, and that makes me one of the most surveilled people in the world. My name is Marcus Yallow, but back when this story starts, I was going by w1n5t0n. Pronounced "Winston." + +*Not* pronounced "Double-you-one-enn-five-tee-zero-enn" -- unless you're a clueless disciplinary officer who's far enough behind the curve that you still call the Internet "the information superhighway." + +I know just such a clueless person, and his name is Fred Benson, one of three vice-principals at Cesar Chavez. He's a sucking chest wound of a human being. But if you're going to have a jailer, better a clueless one than one who's really on the ball. + +"Marcus Yallow," he said over the PA one Friday morning. The PA isn't very good to begin with, and when you combine that with Benson's habitual mumble, you get something that sounds more like someone struggling to digest a bad burrito than a school announcement. But human beings are good at picking their names out of audio confusion -- it's a survival trait. + +I grabbed my bag and folded my laptop three-quarters shut -- I didn't want to blow my downloads -- and got ready for the inevitable. + +"Report to the administration office immediately." + +My social studies teacher, Ms Galvez, rolled her eyes at me and I rolled my eyes back at her. The Man was always coming down on me, just because I go through school firewalls like wet kleenex, spoof the gait-recognition software, and nuke the snitch chips they track us with. Galvez is a good type, anyway, never holds that against me (especially when I'm helping get with her webmail so she can talk to her brother who's stationed in Iraq). + +My boy Darryl gave me a smack on the ass as I walked past. I've known Darryl since we were still in diapers and escaping from play-school, and I've been getting him into and out of trouble the whole time. I raised my arms over my head like a prizefighter and made my exit from Social Studies and began the perp-walk to the office. + +I was halfway there when my phone went. That was another no-no -- phones are muy prohibido at Chavez High -- but why should that stop me? I ducked into the toilet and shut myself in the middle stall (the furthest stall is always grossest because so many people head straight for it, hoping to escape the smell and the squick -- the smart money and good hygiene is down the middle). I checked the phone -- my home PC had sent it an email to tell it that there was something new up on Harajuku Fun Madness, which happens to be the best game ever invented. + +I grinned. Spending Fridays at school was teh suck anyway, and I was glad of the excuse to make my escape. + +I ambled the rest of the way to Benson's office and tossed him a wave as I sailed through the door. + +"If it isn't Double-you-one-enn-five-tee-zero-enn," he said. Fredrick Benson -- Social Security number 545-03-2343, date of birth August 15 1962, mother's maiden name Di Bona, hometown Petaluma -- is a lot taller than me. I'm a runty 5'8", while he stands 6'7", and his college basketball days are far enough behind him that his chest muscles have turned into saggy man-boobs that were painfully obvious through his freebie dot-com polo-shirts. He always looks like he's about to slam-dunk your ass, and he's really into raising his voice for dramatic effect. Both these start to lose their efficacy with repeated application. + +"Sorry, nope," I said. "I never heard of this R2D2 character of yours." + +"W1n5t0n," he said, spelling it out again. He gave me a hairy eyeball and waited for me to wilt. Of course it was my handle, and had been for years. It was the identity I used when I was posting on message-boards where I was making my contributions to the field of applied security research. You know, like sneaking out of school and disabling the minder-tracer on my phone. But he didn't know that this was my handle. Only a small number of people did, and I trusted them all to the end of the earth. + +"Um, not ringing any bells," I said. I'd done some pretty cool stuff around school using that handle -- I was very proud of my work on snitch-tag killers -- and if he could link the two identities, I'd be in trouble. No one at school ever called me w1n5t0n or even Winston. Not even my pals. It was Marcus or nothing. + +Benson settled down behind his desk and tapped his class-ring nervously on his blotter. He did this whenever things started to go bad for him. Poker players call stuff like this a "tell" -- something that let you know what was going on in the other guy's head. I knew Benson's tells backwards and forwards. + +"Marcus, I hope you realize how serious this is." + +"I will just as soon as you explain what this is, sir." I always say "sir" to authority figures when I'm messing with them. It's my own tell. + +He shook his head at me and looked down, another tell. Any second now, he was going to start shouting at me. "Listen, kiddo! It's time you came to grips with the fact that we know about what you've been doing, and that we're not going to be lenient about it. You're going to be lucky if you're not expelled before this meeting is through. Do you want to graduate?" + +"Mr Benson, you still haven't explained what the problem is --" + +He slammed his hand down on the desk and then pointed his finger at me. "The *problem*, Mr Yallow, is that you've been engaged in criminal conspiracy to subvert this school's security system, and you have supplied security countermeasures to your fellow students. You know that we expelled Graciella Uriarte last week for using one of your devices." Uriarte had gotten a bad rap. She'd bought a radio-jammer from a head-shop near the 16th Street BART station and it had set off the countermeasures in the school hallway. Not my doing, but I felt for her. + +"And you think I'm involved in that?" + +"We have reliable intelligence indicating that you are w1n5t0n" -- again, he spelled it out, and I began to wonder if he hadn't figured out that the 1 was an I and the 5 was an S. "We know that this w1n5t0n character is responsible for the theft of last year's standardized tests." That actually hadn't been me, but it was a sweet hack, and it was kind of flattering to hear it attributed to me. "And therefore liable for several years in prison unless you cooperate with me." + +"You have 'reliable intelligence'? I'd like to see it." + +He glowered at me. "Your attitude isn't going to help you." + +"If there's evidence, sir, I think you should call the police and turn it over to them. It sounds like this is a very serious matter, and I wouldn't want to stand in the way of a proper investigation by the duly constituted authorities." + +"You want me to call the police." + +"And my parents, I think. That would be for the best." + +We stared at each other across the desk. He'd clearly expected me to fold the second he dropped the bomb on me. I don't fold. I have a trick for staring down people like Benson. I look slightly to the left of their heads, and think about the lyrics to old Irish folk songs, the kinds with three hundred verses. It makes me look perfectly composed and unworried. + +*And the wing was on the bird and the bird was on the egg and the egg was in the nest and the nest was on the leaf and the leaf was on the twig and the twig was on the branch and the branch was on the limb and the limb was in the tree and the tree was in the bog -- the bog down in the valley-oh! High-ho the rattlin' bog, the bog down in the valley-oh --* + +"You can return to class now," he said. "I'll call on you once the police are ready to speak to you." + +"Are you going to call them now?" + +"The procedure for calling in the police is complicated. I'd hoped that we could settle this fairly and quickly, but since you insist --" + +"I can wait while you call them is all," I said. "I don't mind." + +He tapped his ring again and I braced for the blast. + +"*Go!*" he yelled. "Get the hell out of my office, you miserable little --" + +I got out, keeping my expression neutral. He wasn't going to call the cops. If he'd had enough evidence to go to the police with, he would have called them in the first place. He hated my guts. I figured he'd heard some unverified gossip and hoped to spook me into confirming it. + +I moved down the corridor lightly and sprightly, keeping my gait even and measured for the gait-recognition cameras. These had been installed only a year before, and I loved them for their sheer idiocy. Beforehand, we'd had face-recognition cameras covering nearly every public space in school, but a court ruled that was unconstitutional. So Benson and a lot of other paranoid school administrators had spent our textbook dollars on these idiot cameras that were supposed to be able to tell one person's walk from another. Yeah, right. + +I got back to class and sat down again, Ms Galvez warmly welcoming me back. I unpacked the school's standard-issue machine and got back into classroom mode. The SchoolBooks were the snitchiest technology of them all, logging every keystroke, watching all the network traffic for suspicious keywords, counting every click, keeping track of every fleeting thought you put out over the net. We'd gotten them in my junior year, and it only took a couple months for the shininess to wear off. Once people figured out that these "free" laptops worked for the man -- and showed a never-ending parade of obnoxious ads to boot -- they suddenly started to feel very heavy and burdensome. + +Cracking my SchoolBook had been easy. The crack was online within a month of the machine showing up, and there was nothing to it -- just download a DVD image, burn it, stick it in the SchoolBook, and boot it while holding down a bunch of different keys at the same time. The DVD did the rest, installing a whole bunch of hidden programs on the machine, programs that would stay hidden even when the Board of Ed did its daily remote integrity checks of the machines. Every now and again I had to get an update for the software to get around the Board's latest tests, but it was a small price to pay to get a little control over the box. diff --git a/Testing/dasher_tests/test_data/word_gen_single_line.txt b/Testing/dasher_tests/test_data/word_gen_single_line.txt new file mode 100644 index 0000000..6c5c2ae --- /dev/null +++ b/Testing/dasher_tests/test_data/word_gen_single_line.txt @@ -0,0 +1 @@ +I'm a senior at Cesar Chavez high in San Francisco's sunny Mission district, and that makes me one of the most surveilled people in the world. My name is Marcus Yallow, but back when this story starts, I was going by w1n5t0n. Pronounced "Winston."
rgee/HFOSS-Dasher
27219d63692cd4467ec3da3c3f9170abdbf1922e
Documented test intents
diff --git a/Testing/dasher_tests/WordGenTest.cpp b/Testing/dasher_tests/WordGenTest.cpp index 8e1ae9a..a16df4d 100644 --- a/Testing/dasher_tests/WordGenTest.cpp +++ b/Testing/dasher_tests/WordGenTest.cpp @@ -1,55 +1,69 @@ #include "gtest/gtest.h" #include "../../Src/DasherCore/FileWordGenerator.h" using namespace Dasher; +/* + * Test fixture + */ class WordGenTest : public ::testing::Test { public: WordGenTest() { fullGen = new CFileWordGenerator("test_data/word_gen_full_data.txt"); singleLineGen = new CFileWordGenerator("test_data/word_gen_single_line.txt"); } protected: CFileWordGenerator* fullGen; CFileWordGenerator* singleLineGen; }; /* * Tests whether the word fullGenerator opens a file * correctly. */ TEST_F(WordGenTest, FileOpensCorrectly) { bool opened = fullGen->GetFileHandle().is_open(); bool good = fullGen->GetFileHandle().good(); ASSERT_EQ(opened, true); ASSERT_EQ(good, true); } /* * Tests whether the file name getter returns expected results. */ TEST_F(WordGenTest, FilenameExtraction) { ASSERT_EQ("word_gen_full_data.txt", fullGen->GetFilename()); } +/* + * Tests if retrieving the next word returns expected results. + */ TEST_F(WordGenTest, WordIteration) { ASSERT_EQ("I'm", fullGen->GetNextWord()); ASSERT_EQ("a", fullGen->GetNextWord()); } +/* + * Tests if the word generator actually grabs the right amount of data + * from the stream + */ TEST_F(WordGenTest, GetBuffer) { std::ifstream fin; std::string buffer; fin.open("test_data/word_gen_single_line.txt"); std::getline(fin, buffer); ASSERT_EQ(buffer, singleLineGen->GetWholeBuffer()); } +/* This test /should/ determine whether we return the right value when + * we reach the end of a file...Not sure what's causing this to fail now + */ TEST_F(WordGenTest, EndsAtEOF) { for(int i = 0; i < 1000; i++) singleLineGen->GetNextWord(); ASSERT_EQ("", singleLineGen->GetNextWord()); } +
rgee/HFOSS-Dasher
ee70fc46b801c7778dad758dfdbe0d57c9be3225
Made shell script to encapsulate running all tests.
diff --git a/Testing/dasher_tests/run_tests.sh b/Testing/dasher_tests/run_tests.sh new file mode 100755 index 0000000..f1bb839 --- /dev/null +++ b/Testing/dasher_tests/run_tests.sh @@ -0,0 +1,4 @@ +# This script just runs all the tests in the dasher_tests dir. + +./EventTest +./WordGenTest
rgee/HFOSS-Dasher
0f9520cf568dc2d69eff318fb1ce4fdc56078e24
Lowered the number of dispatches in the stress test so it doesn't destroy Ryan's computer. Currently performing 10,0000,000 dispatches.
diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index 8d50867..efa7306 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,157 +1,157 @@ #include "gtest/gtest.h" #include "../../Src/TestPlatform/MockInterfaceBase.h" #include "../../Src/TestPlatform/MockSettingsStore.h" #include "../../Src/DasherCore/EventHandler.h" #include "../../Src/DasherCore/SettingsStore.h" //A Dasher component that allows tests to easily determine whether //or not it was notified of an event which it subscribed to. class DummyComponent : public Dasher::CDasherComponent { public: int evtCount; std::vector<Dasher::CEvent*> receivedEvents; DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : Dasher::CDasherComponent(pEventHandler, pSettingsStore, std::vector<int>()) { evtCount = 0; } virtual void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; receivedEvents.push_back(pEvent); } }; //An extension of DummyComponent that fires a CStartEvent every time its HandleEvent is called class RecursionComponent : public DummyComponent { public: RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : DummyComponent(pEventHandler, pSettingsStore) { } void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); } }; //Test fixture - sets up the EventHandler, SettingsStore, and InterfaceBase instances. class EventTest : public ::testing::Test { public: EventTest() { interfaceBase = new CMockInterfaceBase(); evtHandler = new Dasher::CEventHandler(interfaceBase); settingsStore = new CMockSettingsStore(evtHandler); } protected: Dasher::CEventHandler *evtHandler; CMockInterfaceBase *interfaceBase; CMockSettingsStore *settingsStore; }; //very basic test - subscribe 5 components, fire one event, and assert that they all were notified TEST_F(EventTest, BasicTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 5; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } evtHandler->InsertEvent(new CParameterNotificationEvent(0)); for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { EXPECT_EQ((*iter)->evtCount, 1); } } //stress test - register a lot of listeners, fire a lot of events, and EXPECT that //everything was notified without crashing TEST_F(EventTest, StressTest) { std::vector<DummyComponent*> components; - for(int c = 0; c < 10000; c++) { + for(int c = 0; c < 1000; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } - for(int c = 0; c < 10000; c++) { + for(int c = 0; c < 1000; c++) { evtHandler->InsertEvent(new CParameterNotificationEvent(0)); } for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { - EXPECT_EQ((*iter)->evtCount, 10000); + EXPECT_EQ((*iter)->evtCount, 1000); } } //test for proper behavior when components call InsertEvent in their HandleEvent TEST_F(EventTest, RecursionTest) { RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); evtHandler->RegisterListener(listener, EV_START); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(rec1->evtCount, 1); EXPECT_EQ(rec2->evtCount, 1); EXPECT_EQ(listener->evtCount, 2); } //register listeners for one event, fire a different event, and //check that they DON'T receieve that event TEST_F(EventTest, StaysQuiet) { DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(listener1, EV_TEXTDRAW); evtHandler->RegisterListener(listener2, EV_COMMAND); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); EXPECT_EQ(listener1->evtCount, 0); EXPECT_EQ(listener2->evtCount, 0); } //verify that events are fired in the order we claim them to be TEST_F(EventTest, EventOrdering) { std::vector<CEvent*> events; DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(listener, EV_START); for(int c = 0; c < 5; c++) { Dasher::CStartEvent *curEvt = new Dasher::CStartEvent(); events.push_back(curEvt); evtHandler->InsertEvent(curEvt); } for(int c = 0; c < 5; c++) { EXPECT_EQ(events[c], listener->receivedEvents[c]); } }
rgee/HFOSS-Dasher
5a2b8f4d6c147bcede2f6b1eb4d41d7d28688be8
Did some reorganization in EventHandler and wrote some new unit tests.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index 5dda894..d7f6db8 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,117 +1,129 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif #include <sstream> void CEventHandler::InsertEvent(CEvent *pEvent) { //put the event at the end of the queue EnqueueEvent(pEvent); //if we are already dispatching events, don't do it again //this is necessary to keep recursive calls from removing //events from the queue while we iterate over it - if(m_bIsDispatching) + if(m_bIsDispatching) { return; + } + else { + ProcessEventQueue(); + } +} + +void CEventHandler::ProcessEventQueue() { + //iterate over the event queue until it's empty while(!m_qEventQueue.empty()) { CEvent *currEvent = m_qEventQueue.front(); m_qEventQueue.pop(); m_pInterface->InterfaceEventHandler(currEvent); m_pInterface->ExternalEventHandler(currEvent); //entering the dispatching loop - no longer safe to modify m_vSpecificListeners m_bIsDispatching = true; //dispatch the event at the front of the queue to all registered listeners for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[currEvent->m_iEventType - 1].begin(); it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); ++it) { (*it)->HandleEvent(currEvent); } //done dispatching this event - safe to modify m_vSpecificListeners m_bIsDispatching = false; //register all listeners that have been waiting to be added for(EvtListenerCollection::iterator it = m_vPendingSpecificReg.begin(); it != m_vPendingSpecificReg.end(); ++it) RegisterListener((*it).first, (*it).second); //unregister all that have been waiting to be removed for(EvtListenerCollection::iterator it = m_vPendingSpecificUnreg.begin(); it != m_vPendingSpecificUnreg.end(); ++it) UnregisterListener((*it).first, (*it).second); - } + + m_vPendingSpecificUnreg.clear(); + m_vPendingSpecificReg.clear(); + } + } void CEventHandler::EnqueueEvent(CEvent *pEvent) { m_qEventQueue.push(pEvent); } -void CEventHandler::RegisterListener(CDasherComponent *pListener) { - - for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { - RegisterListener(pListener, curEvtType); - } -} - void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { // Only try to add a new listener if it doesn't already exist in the Listener map - if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { + if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { if(!m_bIsDispatching) { m_vSpecificListeners[iEventType - 1].push_back(pListener); } else { // Add the listener to the pending set if events are being dispatched m_vPendingSpecificReg.push_back(std::make_pair(pListener, iEventType)); } } else { // Can't add the same listener twice } } +void CEventHandler::RegisterListener(CDasherComponent *pListener) { + + for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { + RegisterListener(pListener, curEvtType); + } +} + void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { if(!m_bIsDispatching) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType - 1].begin(); it != m_vSpecificListeners[iEventType - 1].end(); ++it) { if((*it) == pListener) m_vSpecificListeners[iEventType - 1].erase(it); break; } } else { m_vPendingSpecificUnreg.push_back(std::make_pair(pListener, iEventType)); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { UnregisterListener(pListener, curEvtType); } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 4b07282..8311997 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,147 +1,155 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: + /** + * Dispatch all the events in the event queue, and take + * care of all the pending additions/deletions to m_vSpecificListeners + * in between events. Empties m_qEventQueue, m_vPendingSpecificReg, and + * m_vPendSpecificUnreg + */ + void ProcessEventQueue(); + /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index 43ab64d..d128fcb 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,120 +1,157 @@ #include "gtest/gtest.h" #include "../../Src/TestPlatform/MockInterfaceBase.h" #include "../../Src/TestPlatform/MockSettingsStore.h" #include "../../Src/DasherCore/EventHandler.h" #include "../../Src/DasherCore/SettingsStore.h" //A Dasher component that allows tests to easily determine whether -//or not it was notified of an event which it subscribed to +//or not it was notified of an event which it subscribed to. class DummyComponent : public Dasher::CDasherComponent { public: int evtCount; + std::vector<Dasher::CEvent*> receivedEvents; DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : - Dasher::CDasherComponent(pEventHandler, pSettingsStore) { + Dasher::CDasherComponent(pEventHandler, pSettingsStore, std::vector<int>()) { evtCount = 0; } virtual void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; + receivedEvents.push_back(pEvent); } }; //An extension of DummyComponent that fires a CStartEvent every time its HandleEvent is called class RecursionComponent : public DummyComponent { public: RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : DummyComponent(pEventHandler, pSettingsStore) { } void HandleEvent(Dasher::CEvent *pEvent) { evtCount++; m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); } }; //Test fixture - sets up the EventHandler, SettingsStore, and InterfaceBase instances. class EventTest : public ::testing::Test { public: EventTest() { interfaceBase = new CMockInterfaceBase(); evtHandler = new Dasher::CEventHandler(interfaceBase); settingsStore = new CMockSettingsStore(evtHandler); } protected: Dasher::CEventHandler *evtHandler; CMockInterfaceBase *interfaceBase; CMockSettingsStore *settingsStore; }; //very basic test - subscribe 5 components, fire one event, and assert that they all were notified -/*TEST_F(EventTest, SingleEventBasic) { - - DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener3 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener4 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener5 = new DummyComponent(evtHandler, settingsStore); - - evtHandler->RegisterListener(listener1, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener2, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener3, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener4, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener5, EV_PARAM_NOTIFY); - - evtHandler->InsertEvent(new CParameterNotificationEvent(12)); - - ASSERT_EQ(listener1->evtCount, 1); - ASSERT_EQ(listener2->evtCount, 1); - ASSERT_EQ(listener3->evtCount, 1); - ASSERT_EQ(listener4->evtCount, 1); - ASSERT_EQ(listener5->evtCount, 1); +TEST_F(EventTest, BasicTest) { + + std::vector<DummyComponent*> components; + + for(int c = 0; c < 5; c++) { + + DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); + components.push_back(newComponent); + evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); + } + + evtHandler->InsertEvent(new CParameterNotificationEvent(0)); + + for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { + EXPECT_EQ((*iter)->evtCount, 1); + } } -//stress test - register a lot of listeners, fire a lot of events, and assert that +//stress test - register a lot of listeners, fire a lot of events, and EXPECT that //everything was notified without crashing -TEST_F(EventTest, StressTestBasic) { +TEST_F(EventTest, StressTest) { std::vector<DummyComponent*> components; for(int c = 0; c < 10000; c++) { DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); + components.push_back(newComponent); evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); } for(int c = 0; c < 10000; c++) { evtHandler->InsertEvent(new CParameterNotificationEvent(0)); } for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { - ASSERT_EQ((*iter)->evtCount, 10000); + EXPECT_EQ((*iter)->evtCount, 10000); } -}*/ +} -TEST_F(EventTest, RecursionTestBasic) { +//test for proper behavior when components call InsertEvent in their HandleEvent +TEST_F(EventTest, RecursionTest) { RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); evtHandler->RegisterListener(listener, EV_START); evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); - ASSERT_EQ(rec1->evtCount, 1); - ASSERT_EQ(rec2->evtCount, 1); - ASSERT_EQ(listener->evtCount, 2); + EXPECT_EQ(rec1->evtCount, 1); + EXPECT_EQ(rec2->evtCount, 1); + EXPECT_EQ(listener->evtCount, 2); +} + +//register listeners for one event, fire a different event, and +//check that they DON'T receieve that event +TEST_F(EventTest, StaysQuiet) { + + DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); + + evtHandler->RegisterListener(listener1, EV_TEXTDRAW); + evtHandler->RegisterListener(listener2, EV_COMMAND); + + evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); + + EXPECT_EQ(listener1->evtCount, 0); + EXPECT_EQ(listener2->evtCount, 0); +} + +//verify that events are fired in the order we claim them to be +TEST_F(EventTest, EventOrdering) { + + std::vector<CEvent*> events; + + DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); + + evtHandler->RegisterListener(listener, EV_START); + + for(int c = 0; c < 5; c++) { + + Dasher::CStartEvent *curEvt = new Dasher::CStartEvent(); + events.push_back(curEvt); + evtHandler->InsertEvent(curEvt); + } + + for(int c = 0; c < 5; c++) { + EXPECT_EQ(events[c], listener->receivedEvents[c]); + } } +
rgee/HFOSS-Dasher
796bd99c74fd4380ee82e1a3e8503cfa612f1fcd
Cleaned up file word generator. Segfaulting randomly on startup for some reason. Maybe a merge with new event code will fix it.
diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 3502cad..22a7b3a 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,67 +1,67 @@ #include "FileWordGenerator.h" using namespace Dasher; bool CFileWordGenerator::Generate() { if(!m_sFileHandle.is_open()) m_sFileHandle.open(m_sPath.c_str()); m_uiPos = 0; m_sGeneratedString.clear(); - if(m_sFileHandle.good()) { + if(m_sFileHandle.eof()) { + m_sCurrentWord = ""; + return false; + } else if(m_sFileHandle.good()) { std::getline(m_sFileHandle, m_sGeneratedString); FindNextWord(); return true; } else { return false; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { - return m_sPath.substr(m_sPath.rfind("/")); + return m_sPath.substr(m_sPath.rfind("/")+1); } std::string CFileWordGenerator::GetNextWord() { std::string result = m_sCurrentWord; FindNextWord(); return result; } void CFileWordGenerator::FindNextWord() { std::string result; // We are at the end of the buffer. if(m_uiPos >= m_sGeneratedString.length()) { // Attempt to reload the buffer. if(!Generate()) { - // If file IO fails, return empty. + // If file IO fails, set the current word to empty. result = ""; m_sCurrentWord = result; + return; } } size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); // If there are no space characters. if(found != string::npos) { result = m_sGeneratedString.substr(m_uiPos, found); m_uiPos += (found + 1); } else { result = m_sGeneratedString.substr(m_uiPos); } m_sCurrentWord = result; } -CWordGeneratorBase& CFileWordGenerator::operator++() { - GetNextWord(); - return *this; -} diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index 5c54a85..974135a 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,143 +1,137 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE * kept open for the lifetime of this object and the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all * at once. */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string sPath, int iRegen) : m_sPath(sPath), m_sCurrentWord(""), CWordGeneratorBase(iRegen) {Generate();} CFileWordGenerator(std::string sPath) : m_sPath(sPath), m_sCurrentWord(""), CWordGeneratorBase(0) {Generate();} virtual ~CFileWordGenerator() { m_sFileHandle.close(); } /** * The generator function. In this implementation, it reads from a * file to produce strings.In this implementation, failure means file * io has failed for some reason. * @see CWordGeneratorBase::Generate */ virtual bool Generate(); /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** - * File name getter + * File name getter. Returns the file name and extension, without + * any slashes. * @return The actual name of the file being read from */ std::string GetFilename(); - /** - * Prefix increment operator. - * - * Moves the generator one word ahead. - */ - virtual CWordGeneratorBase& operator++(); - std::ifstream& GetFileHandle() { return m_sFileHandle; } std::string GetWholeBuffer() { return m_sGeneratedString; } size_t GetStringPosition() { return m_uiPos; } private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Find the next word in the generated string buffer. * This does NOT return that string, which is why this is not a public * facing method. It only updates the current string to be presented. * * @warning Ensure that this is called whenever m_sGeneratedString is * remade or whenever the current word is actually presented * to a client. */ void FindNextWord(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * The current word we're looking at. This is the next word that * will be returned when GetNextWord is called. */ std::string m_sCurrentWord; /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * Flag for whether there are words left in this model. */ bool m_bWordsLeft; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h index ef2ba2b..c2e0bf5 100644 --- a/Src/DasherCore/WordGeneratorBase.h +++ b/Src/DasherCore/WordGeneratorBase.h @@ -1,84 +1,71 @@ #ifndef __WordGeneratorBase_h__ #define __WordGeneratorBase_h__ #include <string> using namespace std; namespace Dasher { /** * The base class for all word generators. Word generators encapsulate * logic for simply generating words based on implementation-specific * conditions. Currently, this is being used to wrap GameMode's simple * text-file reading mechanism, but another generator can easily be * written that selects words based on a function of the current value * of the Sri Lankan rupee and the amount of twitter feeds regarding * the winter olympics, for example. * * * A typical use case for any class deriving from CWordGeneratorBase * would be the following: * 1) Construct the object (providing any implementation-specific params) * - The words will be generated on construction. * * 2) To retrieve a word, simply call GetNextWord. This will continue * until the specific implementation determines that there are no * more words for any reason. When there are no more, GetNextWord * returns the empty string. - * - * After construcing the object, you also have the option of a secondary - * usage method: - * 1) Construc the object as normal - * - * 2) Use the PREFIX increment operator to ready up the next word - * - * 3) Call GetNextWord. */ class CWordGeneratorBase { public: CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} virtual ~CWordGeneratorBase() { } /** * Gets a single word based on the generation rules. * @pre { Generate must have been called at least once. } * @return The next string from this generator */ virtual std::string GetNextWord() = 0; /** * -- NOT YET IMPLEMENTED -- * Gets the previous word in the generated string based on generation rules. * @pre { Generate must have been called at least once. } * @return The previous string from this generator */ //virtual std::string GetPreviousWord() = 0; - /** - * All word generators must provide the prefix increment operator. - */ - virtual CWordGeneratorBase& operator++() = 0; - protected: /** * Generate the words based on the generation rules * @return True if the generation succeeded, false if not. * @warning The return value of this function should always be checked * in case it's using files or other solutions that can fail. */ virtual bool Generate() = 0; /** * The time in seconds after which a generator should regenerate. */ int m_iRegenTime; /** * A boolean representing whether the words have been generated yet. */ bool m_bWordsReady; }; } #endif diff --git a/Testing/dasher_tests/WordGenTest.cpp b/Testing/dasher_tests/WordGenTest.cpp index 3ecc60d..8e1ae9a 100644 --- a/Testing/dasher_tests/WordGenTest.cpp +++ b/Testing/dasher_tests/WordGenTest.cpp @@ -1,18 +1,55 @@ #include "gtest/gtest.h" #include "../../Src/DasherCore/FileWordGenerator.h" using namespace Dasher; -class WordGenTest : pulbic ::Testing::Test { +class WordGenTest : public ::testing::Test { public: WordGenTest() { - gen = new CFileWordGenerator("test_data/test_text.txt"); + fullGen = new CFileWordGenerator("test_data/word_gen_full_data.txt"); + singleLineGen = new CFileWordGenerator("test_data/word_gen_single_line.txt"); } protected: - CFileWordGenerator* gen; + CFileWordGenerator* fullGen; + CFileWordGenerator* singleLineGen; }; +/* + * Tests whether the word fullGenerator opens a file + * correctly. + */ TEST_F(WordGenTest, FileOpensCorrectly) { - ASSERT_PRED1(gen->GetFileHandle.is_open()); - ASSERT_PRED1(gen->GetFileHandle.good()); + bool opened = fullGen->GetFileHandle().is_open(); + bool good = fullGen->GetFileHandle().good(); + ASSERT_EQ(opened, true); + ASSERT_EQ(good, true); } + +/* + * Tests whether the file name getter returns expected results. + */ +TEST_F(WordGenTest, FilenameExtraction) { + ASSERT_EQ("word_gen_full_data.txt", fullGen->GetFilename()); +} + +TEST_F(WordGenTest, WordIteration) { + ASSERT_EQ("I'm", fullGen->GetNextWord()); + ASSERT_EQ("a", fullGen->GetNextWord()); +} + +TEST_F(WordGenTest, GetBuffer) { + std::ifstream fin; + std::string buffer; + fin.open("test_data/word_gen_single_line.txt"); + std::getline(fin, buffer); + + ASSERT_EQ(buffer, singleLineGen->GetWholeBuffer()); +} + +TEST_F(WordGenTest, EndsAtEOF) { + for(int i = 0; i < 1000; i++) + singleLineGen->GetNextWord(); + + ASSERT_EQ("", singleLineGen->GetNextWord()); +} +
rgee/HFOSS-Dasher
b54606e29585ec37e357c1a61d47c71897f269ac
Refactored out magic string in FileWordGen. Added incomplete unit test for it
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 88cca61..0b6e807 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -452,714 +452,714 @@ void CDasherInterfaceBase::Pause() { #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h int GameEvents[] = {EV_EDIT, EV_TEXTDRAW}; RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"), - std::vector<int>(GameEvents, GameEvents + sizeof(GameEvents) / sizeof(int)), new CFileWordGenerator(""))); + std::vector<int>(GameEvents, GameEvents + sizeof(GameEvents) / sizeof(int)), new CFileWordGenerator("test_text.txt"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 60601c8..3502cad 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,67 +1,67 @@ #include "FileWordGenerator.h" using namespace Dasher; bool CFileWordGenerator::Generate() { if(!m_sFileHandle.is_open()) - m_sFileHandle.open("test_text.txt"); + m_sFileHandle.open(m_sPath.c_str()); m_uiPos = 0; m_sGeneratedString.clear(); if(m_sFileHandle.good()) { std::getline(m_sFileHandle, m_sGeneratedString); FindNextWord(); return true; } else { return false; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")); } std::string CFileWordGenerator::GetNextWord() { std::string result = m_sCurrentWord; FindNextWord(); return result; } void CFileWordGenerator::FindNextWord() { std::string result; // We are at the end of the buffer. if(m_uiPos >= m_sGeneratedString.length()) { // Attempt to reload the buffer. if(!Generate()) { // If file IO fails, return empty. result = ""; m_sCurrentWord = result; } } size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); // If there are no space characters. if(found != string::npos) { result = m_sGeneratedString.substr(m_uiPos, found); m_uiPos += (found + 1); } else { result = m_sGeneratedString.substr(m_uiPos); } m_sCurrentWord = result; } CWordGeneratorBase& CFileWordGenerator::operator++() { GetNextWord(); return *this; } diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index 43ab64d..f86a2bd 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,120 +1,120 @@ #include "gtest/gtest.h" #include "../../Src/TestPlatform/MockInterfaceBase.h" #include "../../Src/TestPlatform/MockSettingsStore.h" #include "../../Src/DasherCore/EventHandler.h" #include "../../Src/DasherCore/SettingsStore.h" //A Dasher component that allows tests to easily determine whether //or not it was notified of an event which it subscribed to class DummyComponent : public Dasher::CDasherComponent { - - public: - - int evtCount; - - DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : - Dasher::CDasherComponent(pEventHandler, pSettingsStore) { - evtCount = 0; - } - - virtual void HandleEvent(Dasher::CEvent *pEvent) { - evtCount++; - } + + public: + + int evtCount; + + DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : + Dasher::CDasherComponent(pEventHandler, pSettingsStore) { + evtCount = 0; + } + + virtual void HandleEvent(Dasher::CEvent *pEvent) { + evtCount++; + } }; //An extension of DummyComponent that fires a CStartEvent every time its HandleEvent is called class RecursionComponent : public DummyComponent { - - public: - - RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : - DummyComponent(pEventHandler, pSettingsStore) { - } - - void HandleEvent(Dasher::CEvent *pEvent) { - - evtCount++; - m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); - } + + public: + + RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : + DummyComponent(pEventHandler, pSettingsStore) { + } + + void HandleEvent(Dasher::CEvent *pEvent) { + + evtCount++; + m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); + } }; //Test fixture - sets up the EventHandler, SettingsStore, and InterfaceBase instances. class EventTest : public ::testing::Test { - - public: - - EventTest() { - - interfaceBase = new CMockInterfaceBase(); - evtHandler = new Dasher::CEventHandler(interfaceBase); - settingsStore = new CMockSettingsStore(evtHandler); - } - - protected: - - Dasher::CEventHandler *evtHandler; - CMockInterfaceBase *interfaceBase; - CMockSettingsStore *settingsStore; + + public: + + EventTest() { + + interfaceBase = new CMockInterfaceBase(); + evtHandler = new Dasher::CEventHandler(interfaceBase); + settingsStore = new CMockSettingsStore(evtHandler); + } + + protected: + + Dasher::CEventHandler *evtHandler; + CMockInterfaceBase *interfaceBase; + CMockSettingsStore *settingsStore; }; //very basic test - subscribe 5 components, fire one event, and assert that they all were notified -/*TEST_F(EventTest, SingleEventBasic) { +/*TEST_F(EventTest, SingleEventBasic) { - DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener3 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener4 = new DummyComponent(evtHandler, settingsStore); - DummyComponent *listener5 = new DummyComponent(evtHandler, settingsStore); - - evtHandler->RegisterListener(listener1, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener2, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener3, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener4, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener5, EV_PARAM_NOTIFY); - - evtHandler->InsertEvent(new CParameterNotificationEvent(12)); - - ASSERT_EQ(listener1->evtCount, 1); - ASSERT_EQ(listener2->evtCount, 1); - ASSERT_EQ(listener3->evtCount, 1); - ASSERT_EQ(listener4->evtCount, 1); - ASSERT_EQ(listener5->evtCount, 1); + DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener3 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener4 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener5 = new DummyComponent(evtHandler, settingsStore); + + evtHandler->RegisterListener(listener1, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener2, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener3, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener4, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener5, EV_PARAM_NOTIFY); + + evtHandler->InsertEvent(new CParameterNotificationEvent(12)); + + ASSERT_EQ(listener1->evtCount, 1); + ASSERT_EQ(listener2->evtCount, 1); + ASSERT_EQ(listener3->evtCount, 1); + ASSERT_EQ(listener4->evtCount, 1); + ASSERT_EQ(listener5->evtCount, 1); } //stress test - register a lot of listeners, fire a lot of events, and assert that //everything was notified without crashing TEST_F(EventTest, StressTestBasic) { - - std::vector<DummyComponent*> components; - - for(int c = 0; c < 10000; c++) { - - DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); - evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); - } - - for(int c = 0; c < 10000; c++) { - evtHandler->InsertEvent(new CParameterNotificationEvent(0)); - } - - for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { - ASSERT_EQ((*iter)->evtCount, 10000); - } -}*/ + + std::vector<DummyComponent*> components; + + for(int c = 0; c < 10000; c++) { + + DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); + evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); + } + + for(int c = 0; c < 10000; c++) { + evtHandler->InsertEvent(new CParameterNotificationEvent(0)); + } + + for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { + ASSERT_EQ((*iter)->evtCount, 10000); + } +} TEST_F(EventTest, RecursionTestBasic) { - - RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); - RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); - DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); - - evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); - evtHandler->RegisterListener(listener, EV_START); - - evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); - - ASSERT_EQ(rec1->evtCount, 1); - ASSERT_EQ(rec2->evtCount, 1); - ASSERT_EQ(listener->evtCount, 2); -} + + RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); + RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); + DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); + + evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener, EV_START); + + evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); + + ASSERT_EQ(rec1->evtCount, 1); + ASSERT_EQ(rec2->evtCount, 1); + ASSERT_EQ(listener->evtCount, 2); +} */ diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index d395e37..3869db1 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,109 +1,111 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. GTEST_DIR = ../gtest #Points to the root of Dasher's source code DASHER_CORE_DIR = ../../Src/DasherCore TEST_PLATFORM_DIR = ../../Src/TestPlatform # Where to find user code. USER_DIR = . # Where to find dasher object files DASHER_SANDBOX_DIR = ../../dasher-sandbox/Src DASHER_DIR = ../../Src # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include -I$(DASHER_DIR)/DasherCore # Flags passed to the C++ compiler. CXXFLAGS += -g # All tests produced by this Makefile. Remember to add new tests you # created to the list. TESTS = EventTest WordGenTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. A test should link with either gtest.a or # gtest_main.a, depending on whether it defines its own main() # function. #sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc #sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ # $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc #sample1_unittest : sample1.o sample1_unittest.o gtest_main.a # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ -FileWordGenTest : FileWordGenTest.o gtest_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ - -FileWordGenTest.o : $(USER_DIR)/FileWordGenTest.cpp - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/FileWordGenTest.cpp +WordGenTest.o : $(USER_DIR)/WordGenTest.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/WordGenTest.cpp +WordGenTest : WordGenTest.o \ + gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ + $(DASHER_CORE_DIR)/libdasherprefs.a \ + $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a + $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@ EventTest.o : $(USER_DIR)/EventTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp EventTest : EventTest.o \ gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ $(DASHER_CORE_DIR)/libdasherprefs.a \ $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@ diff --git a/Testing/dasher_tests/WordGenTest.cpp b/Testing/dasher_tests/WordGenTest.cpp new file mode 100644 index 0000000..3ecc60d --- /dev/null +++ b/Testing/dasher_tests/WordGenTest.cpp @@ -0,0 +1,18 @@ +#include "gtest/gtest.h" +#include "../../Src/DasherCore/FileWordGenerator.h" +using namespace Dasher; + +class WordGenTest : pulbic ::Testing::Test { + public: + WordGenTest() { + gen = new CFileWordGenerator("test_data/test_text.txt"); + } + + protected: + CFileWordGenerator* gen; +}; + +TEST_F(WordGenTest, FileOpensCorrectly) { + ASSERT_PRED1(gen->GetFileHandle.is_open()); + ASSERT_PRED1(gen->GetFileHandle.good()); +} diff --git a/Testing/dasher_tests/test_data/test_text.txt b/Testing/dasher_tests/test_data/test_text.txt new file mode 100644 index 0000000..7e94834 --- /dev/null +++ b/Testing/dasher_tests/test_data/test_text.txt @@ -0,0 +1,79 @@ +I'm_a_senior at Cesar Chavez high in San Francisco's sunny Mission district, and that makes me one of the most surveilled people in the world. My name is Marcus Yallow, but back when this story starts, I was going by w1n5t0n. Pronounced "Winston." + +*Not* pronounced "Double-you-one-enn-five-tee-zero-enn" -- unless you're a clueless disciplinary officer who's far enough behind the curve that you still call the Internet "the information superhighway." + +I know just such a clueless person, and his name is Fred Benson, one of three vice-principals at Cesar Chavez. He's a sucking chest wound of a human being. But if you're going to have a jailer, better a clueless one than one who's really on the ball. + +"Marcus Yallow," he said over the PA one Friday morning. The PA isn't very good to begin with, and when you combine that with Benson's habitual mumble, you get something that sounds more like someone struggling to digest a bad burrito than a school announcement. But human beings are good at picking their names out of audio confusion -- it's a survival trait. + +I grabbed my bag and folded my laptop three-quarters shut -- I didn't want to blow my downloads -- and got ready for the inevitable. + +"Report to the administration office immediately." + +My social studies teacher, Ms Galvez, rolled her eyes at me and I rolled my eyes back at her. The Man was always coming down on me, just because I go through school firewalls like wet kleenex, spoof the gait-recognition software, and nuke the snitch chips they track us with. Galvez is a good type, anyway, never holds that against me (especially when I'm helping get with her webmail so she can talk to her brother who's stationed in Iraq). + +My boy Darryl gave me a smack on the ass as I walked past. I've known Darryl since we were still in diapers and escaping from play-school, and I've been getting him into and out of trouble the whole time. I raised my arms over my head like a prizefighter and made my exit from Social Studies and began the perp-walk to the office. + +I was halfway there when my phone went. That was another no-no -- phones are muy prohibido at Chavez High -- but why should that stop me? I ducked into the toilet and shut myself in the middle stall (the furthest stall is always grossest because so many people head straight for it, hoping to escape the smell and the squick -- the smart money and good hygiene is down the middle). I checked the phone -- my home PC had sent it an email to tell it that there was something new up on Harajuku Fun Madness, which happens to be the best game ever invented. + +I grinned. Spending Fridays at school was teh suck anyway, and I was glad of the excuse to make my escape. + +I ambled the rest of the way to Benson's office and tossed him a wave as I sailed through the door. + +"If it isn't Double-you-one-enn-five-tee-zero-enn," he said. Fredrick Benson -- Social Security number 545-03-2343, date of birth August 15 1962, mother's maiden name Di Bona, hometown Petaluma -- is a lot taller than me. I'm a runty 5'8", while he stands 6'7", and his college basketball days are far enough behind him that his chest muscles have turned into saggy man-boobs that were painfully obvious through his freebie dot-com polo-shirts. He always looks like he's about to slam-dunk your ass, and he's really into raising his voice for dramatic effect. Both these start to lose their efficacy with repeated application. + +"Sorry, nope," I said. "I never heard of this R2D2 character of yours." + +"W1n5t0n," he said, spelling it out again. He gave me a hairy eyeball and waited for me to wilt. Of course it was my handle, and had been for years. It was the identity I used when I was posting on message-boards where I was making my contributions to the field of applied security research. You know, like sneaking out of school and disabling the minder-tracer on my phone. But he didn't know that this was my handle. Only a small number of people did, and I trusted them all to the end of the earth. + +"Um, not ringing any bells," I said. I'd done some pretty cool stuff around school using that handle -- I was very proud of my work on snitch-tag killers -- and if he could link the two identities, I'd be in trouble. No one at school ever called me w1n5t0n or even Winston. Not even my pals. It was Marcus or nothing. + +Benson settled down behind his desk and tapped his class-ring nervously on his blotter. He did this whenever things started to go bad for him. Poker players call stuff like this a "tell" -- something that let you know what was going on in the other guy's head. I knew Benson's tells backwards and forwards. + +"Marcus, I hope you realize how serious this is." + +"I will just as soon as you explain what this is, sir." I always say "sir" to authority figures when I'm messing with them. It's my own tell. + +He shook his head at me and looked down, another tell. Any second now, he was going to start shouting at me. "Listen, kiddo! It's time you came to grips with the fact that we know about what you've been doing, and that we're not going to be lenient about it. You're going to be lucky if you're not expelled before this meeting is through. Do you want to graduate?" + +"Mr Benson, you still haven't explained what the problem is --" + +He slammed his hand down on the desk and then pointed his finger at me. "The *problem*, Mr Yallow, is that you've been engaged in criminal conspiracy to subvert this school's security system, and you have supplied security countermeasures to your fellow students. You know that we expelled Graciella Uriarte last week for using one of your devices." Uriarte had gotten a bad rap. She'd bought a radio-jammer from a head-shop near the 16th Street BART station and it had set off the countermeasures in the school hallway. Not my doing, but I felt for her. + +"And you think I'm involved in that?" + +"We have reliable intelligence indicating that you are w1n5t0n" -- again, he spelled it out, and I began to wonder if he hadn't figured out that the 1 was an I and the 5 was an S. "We know that this w1n5t0n character is responsible for the theft of last year's standardized tests." That actually hadn't been me, but it was a sweet hack, and it was kind of flattering to hear it attributed to me. "And therefore liable for several years in prison unless you cooperate with me." + +"You have 'reliable intelligence'? I'd like to see it." + +He glowered at me. "Your attitude isn't going to help you." + +"If there's evidence, sir, I think you should call the police and turn it over to them. It sounds like this is a very serious matter, and I wouldn't want to stand in the way of a proper investigation by the duly constituted authorities." + +"You want me to call the police." + +"And my parents, I think. That would be for the best." + +We stared at each other across the desk. He'd clearly expected me to fold the second he dropped the bomb on me. I don't fold. I have a trick for staring down people like Benson. I look slightly to the left of their heads, and think about the lyrics to old Irish folk songs, the kinds with three hundred verses. It makes me look perfectly composed and unworried. + +*And the wing was on the bird and the bird was on the egg and the egg was in the nest and the nest was on the leaf and the leaf was on the twig and the twig was on the branch and the branch was on the limb and the limb was in the tree and the tree was in the bog -- the bog down in the valley-oh! High-ho the rattlin' bog, the bog down in the valley-oh --* + +"You can return to class now," he said. "I'll call on you once the police are ready to speak to you." + +"Are you going to call them now?" + +"The procedure for calling in the police is complicated. I'd hoped that we could settle this fairly and quickly, but since you insist --" + +"I can wait while you call them is all," I said. "I don't mind." + +He tapped his ring again and I braced for the blast. + +"*Go!*" he yelled. "Get the hell out of my office, you miserable little --" + +I got out, keeping my expression neutral. He wasn't going to call the cops. If he'd had enough evidence to go to the police with, he would have called them in the first place. He hated my guts. I figured he'd heard some unverified gossip and hoped to spook me into confirming it. + +I moved down the corridor lightly and sprightly, keeping my gait even and measured for the gait-recognition cameras. These had been installed only a year before, and I loved them for their sheer idiocy. Beforehand, we'd had face-recognition cameras covering nearly every public space in school, but a court ruled that was unconstitutional. So Benson and a lot of other paranoid school administrators had spent our textbook dollars on these idiot cameras that were supposed to be able to tell one person's walk from another. Yeah, right. + +I got back to class and sat down again, Ms Galvez warmly welcoming me back. I unpacked the school's standard-issue machine and got back into classroom mode. The SchoolBooks were the snitchiest technology of them all, logging every keystroke, watching all the network traffic for suspicious keywords, counting every click, keeping track of every fleeting thought you put out over the net. We'd gotten them in my junior year, and it only took a couple months for the shininess to wear off. Once people figured out that these "free" laptops worked for the man -- and showed a never-ending parade of obnoxious ads to boot -- they suddenly started to feel very heavy and burdensome. + +Cracking my SchoolBook had been easy. The crack was online within a month of the machine showing up, and there was nothing to it -- just download a DVD image, burn it, stick it in the SchoolBook, and boot it while holding down a bunch of different keys at the same time. The DVD did the rest, installing a whole bunch of hidden programs on the machine, programs that would stay hidden even when the Board of Ed did its daily remote integrity checks of the machines. Every now and again I had to get an update for the software to get around the Board's latest tests, but it was a small price to pay to get a little control over the box.
rgee/HFOSS-Dasher
7b4e83f3525aee7765964ba95ae5680d8014a9a1
Added TestPlatform to version control
diff --git a/Src/TestPlatform/Makefile.am b/Src/TestPlatform/Makefile.am new file mode 100644 index 0000000..e69de29 diff --git a/Src/TestPlatform/MockInterfaceBase.h b/Src/TestPlatform/MockInterfaceBase.h new file mode 100644 index 0000000..dcc6683 --- /dev/null +++ b/Src/TestPlatform/MockInterfaceBase.h @@ -0,0 +1,34 @@ +#include "../DasherCore/DasherInterfaceBase.h" + +using namespace Dasher; + +/** + * A useless, but concrete implementation of CDasherInterfaceBase + * used for unit testing purposes. Allows us to instantiate + * CDasherInterfaceBase without delving into platform specific code. + */ +class CMockInterfaceBase : public CDasherInterfaceBase { + + public: + + CMockInterfaceBase() : CDasherInterfaceBase() {}; + + void CreateModules() {}; + + void SetupPaths() {}; + + void ScanAlphabetFiles(std::vector<std::string> &vFileList) {}; + + void ScanColourFiles(std::vector<std::string> &vFileList) {}; + + void SetupUI() {}; + + void CreateSettingsStore() {}; + + int GetFileSize(const std::string &strFileName) { return 0; }; + + void StartTimer() {}; + + void ShutdownTimer() {}; + +}; diff --git a/Src/TestPlatform/MockSettingsStore.h b/Src/TestPlatform/MockSettingsStore.h new file mode 100644 index 0000000..33cc0d2 --- /dev/null +++ b/Src/TestPlatform/MockSettingsStore.h @@ -0,0 +1,25 @@ +#include "../DasherCore/SettingsStore.h" + +using namespace Dasher; + +/** + * A useless, but concrete implementation of CSettingsStore. + * used for unit testing purposes. Allows us to instantiate + * CSettingsStore without using platform specific code. + */ +class CMockSettingsStore : public CSettingsStore { + + public: + + CMockSettingsStore(Dasher::CEventHandler * pEventHandler) : CSettingsStore(pEventHandler) {} + + bool LoadSetting(const std::string & Key, bool * Value) { return true; } + + bool LoadSetting(const std::string & Key, long * Value) { return true; } + + void SaveSetting(const std::string & Key, bool Value) {} + + void SaveSetting(const std::string & Key, long Value) {} + + void SaveSetting(const std::string & Key, const std::string & Value) {} +};
rgee/HFOSS-Dasher
a7ea58f7f3d2328748bce157e4bd225fb372ab79
Cleaned up weird, old make targets...
diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index 3a7b5c1..d395e37 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,126 +1,109 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. GTEST_DIR = ../gtest #Points to the root of Dasher's source code DASHER_CORE_DIR = ../../Src/DasherCore TEST_PLATFORM_DIR = ../../Src/TestPlatform # Where to find user code. USER_DIR = . # Where to find dasher object files DASHER_SANDBOX_DIR = ../../dasher-sandbox/Src DASHER_DIR = ../../Src # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include -I$(DASHER_DIR)/DasherCore # Flags passed to the C++ compiler. CXXFLAGS += -g # All tests produced by this Makefile. Remember to add new tests you # created to the list. -TESTS = EventTest +TESTS = EventTest WordGenTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ -<<<<<<< HEAD -<<<<<<< HEAD + # Builds a sample test. A test should link with either gtest.a or # gtest_main.a, depending on whether it defines its own main() # function. #sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc #sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ # $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc #sample1_unittest : sample1.o sample1_unittest.o gtest_main.a # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ FileWordGenTest : FileWordGenTest.o gtest_main.a $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ FileWordGenTest.o : $(USER_DIR)/FileWordGenTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/FileWordGenTest.cpp -EventTest : EventTest.o gtest_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DASHER_SANDBOX_DIR)/DasherCore/FileWordGenerator.o -lpthread $^ -o $@ - -EventTest.o : $(USER_DIR)/EventTest.cpp - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp - - - - -======= -======= ->>>>>>> 5433c1428344783d48b65e951bfa1c364c0ca865 EventTest.o : $(USER_DIR)/EventTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp EventTest : EventTest.o \ gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ $(DASHER_CORE_DIR)/libdasherprefs.a \ $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@ -<<<<<<< HEAD - ->>>>>>> 89bbcb570f5762f48ae0abc1daab863d49cd9b33 -======= ->>>>>>> 5433c1428344783d48b65e951bfa1c364c0ca865 +
rgee/HFOSS-Dasher
9e25f941c4e27a969306c1a3ff5c28d87b1be100
Increased number of events in event manager to support the new node tagging events.
diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index a051ebc..8c27293 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,148 +1,148 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: /** * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(12), m_pInterface(pInterface) { m_bIsDispatching = false; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; /** * TODO - when we refactor, rename this to DispatchEvent * Insert an event into the queue, then flush the queue * such that all event listeners are notified of the * events they subscribed to. */ void InsertEvent(Dasher::CEvent * pEvent); /** * Add an event to the event queue. * @param pEvent the event to add to the queue */ void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); private: /** * The queue of events waiting to be dispatched. */ std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ EvtListenerTable m_vSpecificListeners; /** * The set of specific listeners waiting to be registered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificReg; /** * The set of specific listeners waiting to be unregistered * while m_vSpecificListeners is being iterated over. */ EvtListenerCollection m_vPendingSpecificUnreg; Dasher::CDasherInterfaceBase * m_pInterface; /** * Boolean flag - true if we are in the middle of flushing * the event queue, false if not. Used to determine whether it * is safe to modify m_vSpecificListeners */ bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif
rgee/HFOSS-Dasher
4437de7b166cf979b2bd56c651b184ec92b8315d
Writing more unit tests. Found a bug with recursive calls to EventHandler:: InsertEvent - trying to figure that out.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index a589834..5dda894 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,118 +1,117 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif #include <sstream> void CEventHandler::InsertEvent(CEvent *pEvent) { //put the event at the end of the queue EnqueueEvent(pEvent); //if we are already dispatching events, don't do it again //this is necessary to keep recursive calls from removing //events from the queue while we iterate over it if(m_bIsDispatching) return; //iterate over the event queue until it's empty while(!m_qEventQueue.empty()) { CEvent *currEvent = m_qEventQueue.front(); m_qEventQueue.pop(); m_pInterface->InterfaceEventHandler(currEvent); m_pInterface->ExternalEventHandler(currEvent); //entering the dispatching loop - no longer safe to modify m_vSpecificListeners m_bIsDispatching = true; //dispatch the event at the front of the queue to all registered listeners for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[currEvent->m_iEventType - 1].begin(); - it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); - ++it) + it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); ++it) { (*it)->HandleEvent(currEvent); } //done dispatching this event - safe to modify m_vSpecificListeners m_bIsDispatching = false; //register all listeners that have been waiting to be added for(EvtListenerCollection::iterator it = m_vPendingSpecificReg.begin(); it != m_vPendingSpecificReg.end(); ++it) RegisterListener((*it).first, (*it).second); //unregister all that have been waiting to be removed for(EvtListenerCollection::iterator it = m_vPendingSpecificUnreg.begin(); it != m_vPendingSpecificUnreg.end(); ++it) UnregisterListener((*it).first, (*it).second); } } void CEventHandler::EnqueueEvent(CEvent *pEvent) { m_qEventQueue.push(pEvent); } void CEventHandler::RegisterListener(CDasherComponent *pListener) { for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { RegisterListener(pListener, curEvtType); } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { // Only try to add a new listener if it doesn't already exist in the Listener map if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { if(!m_bIsDispatching) { m_vSpecificListeners[iEventType - 1].push_back(pListener); } else { // Add the listener to the pending set if events are being dispatched m_vPendingSpecificReg.push_back(std::make_pair(pListener, iEventType)); } } else { // Can't add the same listener twice } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { if(!m_bIsDispatching) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType - 1].begin(); it != m_vSpecificListeners[iEventType - 1].end(); ++it) { if((*it) == pListener) m_vSpecificListeners[iEventType - 1].erase(it); break; } } else { m_vPendingSpecificUnreg.push_back(std::make_pair(pListener, iEventType)); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { UnregisterListener(pListener, curEvtType); } } diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index ca2821d..43ab64d 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,46 +1,120 @@ #include "gtest/gtest.h" #include "../../Src/TestPlatform/MockInterfaceBase.h" #include "../../Src/TestPlatform/MockSettingsStore.h" #include "../../Src/DasherCore/EventHandler.h" +#include "../../Src/DasherCore/SettingsStore.h" +//A Dasher component that allows tests to easily determine whether +//or not it was notified of an event which it subscribed to class DummyComponent : public Dasher::CDasherComponent { public: - bool receivedEvent; + int evtCount; - DummyComponent(Dasher::CEventHandler* pEventHandler, Dasher::CSettingsStore* pSettingsStore) : + DummyComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : Dasher::CDasherComponent(pEventHandler, pSettingsStore) { - receivedEvent = false; + evtCount = 0; + } + + virtual void HandleEvent(Dasher::CEvent *pEvent) { + evtCount++; + } +}; + +//An extension of DummyComponent that fires a CStartEvent every time its HandleEvent is called +class RecursionComponent : public DummyComponent { + + public: + + RecursionComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore) : + DummyComponent(pEventHandler, pSettingsStore) { } void HandleEvent(Dasher::CEvent *pEvent) { - receivedEvent = true; + + evtCount++; + m_pEventHandler->InsertEvent(new Dasher::CStartEvent()); } }; -class EventTest : public ::Testing::Test { +//Test fixture - sets up the EventHandler, SettingsStore, and InterfaceBase instances. +class EventTest : public ::testing::Test { public: EventTest() { interfaceBase = new CMockInterfaceBase(); - settingsStore = new CMockSettingsStore(); evtHandler = new Dasher::CEventHandler(interfaceBase); + settingsStore = new CMockSettingsStore(evtHandler); } protected: Dasher::CEventHandler *evtHandler; CMockInterfaceBase *interfaceBase; CMockSettingsStore *settingsStore; }; -TEST_F(EventTest, BasicHandling) { +//very basic test - subscribe 5 components, fire one event, and assert that they all were notified +/*TEST_F(EventTest, SingleEventBasic) { - DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); - evtHandler->RegisterListener(listener, 1); + DummyComponent *listener1 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener2 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener3 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener4 = new DummyComponent(evtHandler, settingsStore); + DummyComponent *listener5 = new DummyComponent(evtHandler, settingsStore); + + evtHandler->RegisterListener(listener1, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener2, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener3, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener4, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener5, EV_PARAM_NOTIFY); + evtHandler->InsertEvent(new CParameterNotificationEvent(12)); - ASSERT_TRUE(listener->receievedEvent); + + ASSERT_EQ(listener1->evtCount, 1); + ASSERT_EQ(listener2->evtCount, 1); + ASSERT_EQ(listener3->evtCount, 1); + ASSERT_EQ(listener4->evtCount, 1); + ASSERT_EQ(listener5->evtCount, 1); +} + +//stress test - register a lot of listeners, fire a lot of events, and assert that +//everything was notified without crashing +TEST_F(EventTest, StressTestBasic) { + + std::vector<DummyComponent*> components; + + for(int c = 0; c < 10000; c++) { + + DummyComponent *newComponent = new DummyComponent(evtHandler, settingsStore); + evtHandler->RegisterListener(newComponent, EV_PARAM_NOTIFY); + } + + for(int c = 0; c < 10000; c++) { + evtHandler->InsertEvent(new CParameterNotificationEvent(0)); + } + + for(std::vector<DummyComponent*>::iterator iter = components.begin(); iter != components.end(); ++iter) { + ASSERT_EQ((*iter)->evtCount, 10000); + } +}*/ + +TEST_F(EventTest, RecursionTestBasic) { + + RecursionComponent *rec1 = new RecursionComponent(evtHandler, settingsStore); + RecursionComponent *rec2 = new RecursionComponent(evtHandler, settingsStore); + DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); + + evtHandler->RegisterListener(rec1, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(rec2, EV_PARAM_NOTIFY); + evtHandler->RegisterListener(listener, EV_START); + + evtHandler->InsertEvent(new Dasher::CParameterNotificationEvent(0)); + + ASSERT_EQ(rec1->evtCount, 1); + ASSERT_EQ(rec2->evtCount, 1); + ASSERT_EQ(listener->evtCount, 2); }
rgee/HFOSS-Dasher
94f59b8b2fec2a072cc034db9529b17024fbd483
New game mode node tagging almost complete. Dasher model doesn't seem to be properly getting the target string, currently.
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index 70afecf..92e46c3 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,462 +1,463 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, pGroup ? (pGroup->bVisible ? pGroup->iColour : pParent->getColour()) : pMgr->m_pNCManager->GetAlphabet()->GetColour(0, iOffset%2), pGroup ? pGroup->strLabel : "", pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { return new CSymbolNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup) { return new CGroupNode(pParent, iOffset, iLbnd, iHbnd, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pNewNode = makeGroup(pParent, iNewOffset, iLower, iUpper, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pNewNode = makeSymbol(pParent, iNewOffset, iLower, iUpper, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->iContext = iContext; return pNewNode; } bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { SetFlag(NF_GAME, true); return true; } return false; } + bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { if (GameSearchChildren(strTargetUtf8Char)) { SetFlag(NF_GAME, true); return true; } -return false; + return false; } CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->offset() == offset()); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // When creating a group node... // ...the offset is the same as the parent... CGroupNode *pNewNode = makeGroup(pParent, pParent->offset(), iLbnd, iHbnd, pInfo); //...as is the context! pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (offset() == pParent->offset()); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); } else { // TODO: Exceptions / error handling in general CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, pParent->offset()+1, iLbnd, iHbnd, iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(offset() == pParent->offset() + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); //loop for eliding groups with single children (see below). // Variables store necessary properties of any elided groups: std::string groupPrefix=""; int iOverrideColour=-1; SGroupInfo *pInner=pCurrentNode; while (true) { if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop break; //exit inner (group elision) loop } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); i = pInner->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) // (maybe not of pCurrentNode now, which might be a subgroup filling the original) break; //exit inner (group elision) loop } //were about to create a group node, which would have only one child // (eventually, if the group node were PopulateChildren'd). // Such a child would entirely fill it's parent (the group), and thus, // creation/destruction of the child would cause the node's colour to flash // between that for parent group and child. // Hence, instead we elide the group node and create the child _here_... //1. however we also have to take account of the appearance of the elided group. Hence: groupPrefix += pInner->strLabel; if (pInner->bVisible) iOverrideColour=pInner->iColour; //2. now go into the group... pInner = pInner->pChild; bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok //3. loop round inner loop... } //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); //now adjust the node we've actually created, to take account of any elided group(s)... // tho not if we've reused the existing node, assume that's been adjusted already if (pNewChild && pNewChild!=buildAround) pNewChild->PrependElidedGroup(iOverrideColour, groupPrefix); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(offset()); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(offset()-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/AlphabetManager.h b/Src/DasherCore/AlphabetManager.h index 6b98c6b..89184f7 100644 --- a/Src/DasherCore/AlphabetManager.h +++ b/Src/DasherCore/AlphabetManager.h @@ -1,154 +1,171 @@ // AlphabetManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __alphabetmanager_h__ #define __alphabetmanager_h__ #include "LanguageModelling/LanguageModel.h" #include "DasherNode.h" #include "Parameters.h" #include "NodeManager.h" class CNodeCreationManager; struct SGroupInfo; namespace Dasher { class CDasherInterfaceBase; /// \ingroup Model /// @{ /// Implementation of CNodeManager for regular 'alphabet' nodes, ie /// the basic Dasher behaviour. Child nodes are populated according /// to the appropriate alphabet file, with sizes given by the /// language model. /// class CAlphabetManager : public CNodeManager { public: CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel); protected: class CGroupNode; class CAlphNode : public CDasherNode { public: virtual CAlphabetManager *mgr() {return m_pMgr;} CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr); CLanguageModel::Context iContext; /// /// Delete any storage alocated for this node /// virtual ~CAlphNode(); virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel); CDasherNode *RebuildParent(int iNewOffset); ///Have to call this from CAlphabetManager, and from CGroupNode on a _different_ CAlphNode, hence public... virtual std::vector<unsigned int> *GetProbInfo(); virtual int ExpectedNumChildren(); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd)=0; virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd)=0; private: std::vector<unsigned int> *m_pProbInfo; protected: CAlphabetManager *m_pMgr; }; class CSymbolNode : public CAlphNode { public: ///Standard constructor, gets colour+label by looking up symbol in current alphabet (& computing phase from offset) CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol iSymbol); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual CDasherNode *RebuildParent(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization); virtual void Undo(int *pNumDeleted); virtual void SetFlag(int iFlag, bool bValue); + /** + * Checks whether this node represents the target string. + * In the case of group nodes, this function checks this node's + * children, which are symbol nodes. + * @param strTargetUtf8Char The string to compare to. + * @return True if this node represents the target string. False + * otherwise. + */ virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); virtual symbol GetAlphSymbol(); const symbol iSymbol; virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); private: virtual const std::string &outputText(); protected: ///Compatibility constructor, so that subclasses can specify their own colour & label CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol); }; class CGroupNode : public CAlphNode { public: CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup); /// /// Provide children for the supplied node /// virtual CDasherNode *RebuildParent(); virtual void PopulateChildren(); virtual int ExpectedNumChildren(); + + /** + * Checks whether this node represents the target string. + * In the case of group nodes, this function checks this node's + * children, which are symbol nodes. + * @param strTargetUtf8Char The string to compare to. + * @return True if this node represents the target string. False + * otherwise. + */ virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); std::vector<unsigned int> *GetProbInfo(); private: SGroupInfo *m_pGroup; }; public: /// /// Get a new root node owned by this manager /// bEnteredLast - true if this "root" node should be considered as entering the preceding symbol /// Offset is the index of the character which _child_ nodes (i.e. between which this root allows selection) /// will enter. (Also used to build context for preceding characters.) virtual CAlphNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset); protected: /// /// Factory method for CAlphNode construction, so subclasses can override. /// virtual CSymbolNode *makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol); virtual CGroupNode *makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup); virtual CDasherNode *CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CLanguageModel::Context CreateSymbolContext(CAlphNode *pParent, symbol iSymbol); virtual CGroupNode *CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); CLanguageModel *m_pLanguageModel; CNodeCreationManager *m_pNCManager; private: void IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround); CLanguageModel::Context m_iLearnContext; CDasherInterfaceBase *m_pInterface; }; /// @} } #endif diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 88cca61..b2d1463 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -450,716 +450,716 @@ void CDasherInterfaceBase::Pause() { m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h - int GameEvents[] = {EV_EDIT, EV_TEXTDRAW}; + int GameEvents[] = {EV_EDIT, EV_TEXTDRAW, EV_GAME_NODE_DRAWN}; RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"), std::vector<int>(GameEvents, GameEvents + sizeof(GameEvents) / sizeof(int)), new CFileWordGenerator(""))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 8a980aa..c0c5bbd 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,815 +1,824 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { + if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { + CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); + + m_strGameTarget = pTargetChangedEvent->m_strTargetText; + } CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); m_strGameTarget = pTargetChangedEvent->m_strTargetText; } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; + m_Root->SetFlag(NF_GAME, true); // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. - GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); - if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) + //GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); + //if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) + if(pNode->GetFlag(NF_GAME)) { - std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); + /*std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); - } + }*/ + + pNode->GameSearchChildren(m_strGameTarget); } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index c89cb47..3fe96f7 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,927 +1,939 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. -void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove) { +void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove, CDasherNode* pNode) { + // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } - + if((pNode != NULL) && (pNode->GetFlag(NF_GAME) == true)) { + m_pEventHandler->InsertEvent(new CGameNodeDrawEvent(pNode, this, newleft2, newtop2)); + } // Tell other listeners that text has been drawn and provide some information // about the draw call. - m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplayText,this, newleft2, newtop2, Size)); + //m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplayText,this, newleft2, newtop2, Size)); // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, - CExpansionPolicy &policy) { + CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), - // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), - // 0, -1, Nodes1, false, true, 1); + // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), + // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, - int mostleft, CExpansionPolicy &policy, double dMaxCost, - myint parent_width, int parent_color, int iDepth) + int mostleft, CExpansionPolicy &policy, double dMaxCost, + myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); - + if (y1 <= iDasherMaxY && y2 >= iDasherMinY) - { + { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; - + Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); - + Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) - { - //node should be rendered! - - RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); - return true; - } - } + { + //node should be rendered! + + RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); + return true; + } + } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, - int mostleft, CExpansionPolicy &policy, double dMaxCost, - myint parent_width,int parent_color, int iDepth) + int mostleft, CExpansionPolicy &policy, double dMaxCost, + myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); + + + + // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); const std::string &sDisplayText(pRender->getDisplayText()); if( sDisplayText.size() > 0 ) - { - DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); + { + if(pRender->GetFlag(NF_GAME)) { + DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove(), pRender); + } else { + DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); + + } } - + pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->getColour(), -1, Nodes1, 0); - //also allow it to be expanded, it's big enough. - policy.pushNode(pRender, y1, y2, true, dMaxCost); - return; + //also allow it to be expanded, it's big enough. + policy.pushNode(pRender, y1, y2, true, dMaxCost); + return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); - + // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; int temp_parentcolor = pRender->getColour(); const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, - policy, dMaxCost, - temp_parentwidth, temp_parentcolor, iDepth); + policy, dMaxCost, + temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } - + if (!pRender->onlyChildRendered) { //render all children... - for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); - i != pRender->GetChildren().end(); i++) { - id++; - CDasherNode *pChild = *i; - - myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints - myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; + for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); + i != pRender->GetChildren().end(); i++) { + id++; + CDasherNode *pChild = *i; + + myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints + myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } - if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, - temp_parentwidth, temp_parentcolor, iDepth+1)) - { - + if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, + temp_parentwidth, temp_parentcolor, iDepth+1)) + { + if (lasty<newy1) { - //if child has been drawn then the interval between him and the - //last drawn child should be drawn too. - //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; - - RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, - pRender->getDisplayText(), - pRender->bShove(), - temp_parentwidth); + //if child has been drawn then the interval between him and the + //last drawn child should be drawn too. + //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; + + RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, + pRender->getDisplayText(), + pRender->bShove(), + temp_parentwidth); } - - lasty = newy2; - } - } - - // Finish off the drawing process - - // if(iDepth == 1) { - // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. - if(lasty<y2) { - RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, - pRender->getDisplayText(), - pRender->bShove(), - temp_parentwidth); - } + + lasty = newy2; + } + } + + // Finish off the drawing process + + // if(iDepth == 1) { + // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. + if(lasty<y2) { + RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, + pRender->getDisplayText(), + pRender->bShove(), + temp_parentwidth); + } } // Draw the outline if(pRender->getColour() != -1) {//-1 = invisible RenderNodeOutlineFast(pRender->getColour(), - y1, y2, mostleft, - pRender->getDisplayText(), - pRender->bShove()); + y1, y2, mostleft, + pRender->getDisplayText(), + pRender->bShove()); } // } } bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else quot = num / denom; rem = num % denom; #endif if (rem < 0) res = quot - 1; else if (rem > 0) res = quot + 1; else res = quot; return res; // return (iNumerator + iDenominator - 1) / iDenominator; } void CDasherViewSquare::Dasher2Screen(myint iDasherX, myint iDasherY, screenint &iScreenX, screenint &iScreenY) { // Apply the nonlinearities iDasherX = xmap(iDasherX); iDasherY = ymap(iDasherY); // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation( GetLongParameter(LP_REAL_ORIENTATION) ); // Note that integer division is rounded *away* from zero here to // ensure that this really is the inverse of the map the other way // around. switch( eOrientation ) { case Dasher::Opts::LeftToRight: iScreenX = screenint(iScreenWidth / 2 - - CustomIDiv((( iDasherX - iCenterX ) * iScaleFactorX), m_iScalingFactor)); + CustomIDiv((( iDasherX - iCenterX ) * iScaleFactorX), m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + - CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::RightToLeft: iScreenX = screenint(iScreenWidth / 2 + - CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorX, m_iScalingFactor)); + CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + - CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::TopToBottom: iScreenX = screenint(iScreenWidth / 2 + - CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 - - CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); + CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::BottomToTop: iScreenX = screenint(iScreenWidth / 2 + - CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + - CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); + CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); break; } } void CDasherViewSquare::Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) { - iDasherX = xmap(iDasherX); + iDasherX = xmap(iDasherX); iDasherY = ymap(iDasherY); - + myint iDasherOX = xmap(GetLongParameter(LP_OX)); myint iDasherOY = ymap(GetLongParameter(LP_OY)); - + double x = -(iDasherX - iDasherOX) / double(iDasherOX); //Use normalised coords so min r works double y = -(iDasherY - iDasherOY) / double(iDasherOY); theta = atan2(y, x); r = sqrt(x * x + y * y); } void CDasherViewSquare::DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, vector<CDasherScreen::point> &vPoints) { if (x1!=x2 && y1!=y2) { //only diagonal lines ever get changed... if (GetBoolParameter(BP_NONLINEAR_Y)) { if ((y1 < m_Y3 && y2 > m_Y3) ||(y2 < m_Y3 && y1 > m_Y3)) { //crosses bottom non-linearity border int x_mid = x1+(x2-x1) * (m_Y3-y1)/(y2-y1); DasherLine2Screen(x1, y1, x_mid, m_Y3, vPoints); x1=x_mid; y1=m_Y3; }//else //no, a single line might cross _both_ borders! if ((y1 > m_Y2 && y2 < m_Y2) || (y2 > m_Y2 && y1 < m_Y2)) { //crosses top non-linearity border int x_mid = x1 + (x2-x1) * (m_Y2-y1)/(y2-y1); DasherLine2Screen(x1, y1, x_mid, m_Y2, vPoints); x1=x_mid; y1=m_Y2; } } double dMax(static_cast<double>(GetLongParameter(LP_MAX_Y))); if (GetLongParameter(LP_NONLINEAR_X) && (x1 / dMax > m_dXmpb || x2 / dMax > m_dXmpb)) { //into logarithmic section CDasherScreen::point pStart, pScreenMid, pEnd; Dasher2Screen(x2, y2, pEnd.x, pEnd.y); for(;;) { Dasher2Screen(x1, y1, pStart.x, pStart.y); //a straight line on the screen between pStart and pEnd passes through pScreenMid: pScreenMid.x = (pStart.x + pEnd.x)/2; pScreenMid.y = (pStart.y + pEnd.y)/2; //whereas a straight line _in_Dasher_space_ passes through pDasherMid: int xMid=(x1+x2)/2, yMid=(y1+y2)/2; CDasherScreen::point pDasherMid; Dasher2Screen(xMid, yMid, pDasherMid.x, pDasherMid.y); //since we know both endpoints are in the same section of the screen wrt. Y nonlinearity, //the midpoint along the DasherY axis of both lines should be the same. const Dasher::Opts::ScreenOrientations orient(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); if (orient==Dasher::Opts::LeftToRight || orient==Dasher::Opts::RightToLeft) { DASHER_ASSERT(abs(pDasherMid.y - pScreenMid.y)<=1);//allow for rounding error if (abs(pDasherMid.x - pScreenMid.x)<=1) break; //call a straight line accurate enough } else { DASHER_ASSERT(abs(pDasherMid.x - pScreenMid.x)<=1); if (abs(pDasherMid.y - pScreenMid.y)<=1) break; } //line should appear bent. Subdivide! DasherLine2Screen(x1,y1,xMid,yMid,vPoints); //recurse for first half (to Dasher-space midpoint) x1=xMid; y1=yMid; //& loop round for second half } //broke out of loop. a straight line (x1,y1)-(x2,y2) on the screen is an accurate portrayal of a straight line in Dasher-space. vPoints.push_back(pEnd); return; } //ok, not in x nonlinear section; fall through. } #ifdef DEBUG CDasherScreen::point pTest; Dasher2Screen(x1, y1, pTest.x, pTest.y); DASHER_ASSERT(vPoints.back().x == pTest.x && vPoints.back().y == pTest.y); #endif CDasherScreen::point p; Dasher2Screen(x2, y2, p.x, p.y); vPoints.push_back(p); } void CDasherViewSquare::VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) { // TODO: Change output parameters to pointers and allow NULL to mean // 'I don't care'. Need to be slightly careful about this as it will // require a slightly more sophisticated caching mechanism if(!m_bVisibleRegionValid) { int eOrientation( GetLongParameter(LP_REAL_ORIENTATION) ); switch( eOrientation ) { case Dasher::Opts::LeftToRight: Screen2Dasher(Screen()->GetWidth(),0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(0,Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::RightToLeft: Screen2Dasher(0,0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::TopToBottom: Screen2Dasher(0,Screen()->GetHeight(),m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),0,m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::BottomToTop: Screen2Dasher(0,0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; } m_bVisibleRegionValid = true; } iDasherMinX = m_iDasherMinX; iDasherMaxX = m_iDasherMaxX; iDasherMinY = m_iDasherMinY; iDasherMaxY = m_iDasherMaxY; } // void CDasherViewSquare::NewDrawGoTo(myint iDasherMin, myint iDasherMax, bool bActive) { // myint iHeight(iDasherMax - iDasherMin); // int iColour; // int iWidth; // if(bActive) { // iColour = 1; // iWidth = 3; // } // else { // iColour = 2; // iWidth = 1; // } // CDasherScreen::point p[4]; // Dasher2Screen( 0, iDasherMin, p[0].x, p[0].y); // Dasher2Screen( iHeight, iDasherMin, p[1].x, p[1].y); // Dasher2Screen( iHeight, iDasherMax, p[2].x, p[2].y); // Dasher2Screen( 0, iDasherMax, p[3].x, p[3].y); // Screen()->Polyline(p, 4, iWidth, iColour); // } void CDasherViewSquare::ChangeScreen(CDasherScreen *NewScreen) { CDasherView::ChangeScreen(NewScreen); m_bVisibleRegionValid = false; m_iScalingFactor = 100000000; SetScaleFactor(); } diff --git a/Src/DasherCore/DasherViewSquare.h b/Src/DasherCore/DasherViewSquare.h index 433c477..96fb788 100644 --- a/Src/DasherCore/DasherViewSquare.h +++ b/Src/DasherCore/DasherViewSquare.h @@ -1,202 +1,214 @@ // DasherViewSquare.h // // Copyright (c) 2001-2004 David Ward #ifndef __DasherViewSquare_h__ #define __DasherViewSquare_h__ #include "DasherView.h" #include "DelayedDraw.h" #include "DasherScreen.h" +#include "DasherNode.h" #include <deque> #include "Alphabet/GroupInfo.h" using namespace std; namespace Dasher { class CDasherViewSquare; class CDasherView; class CDasherModel; class CDelayedDraw; class CDasherNode; } class Dasher::CDasherViewSquare; class Dasher::CDasherModel; class Dasher::CDelayedDraw; class Dasher::CDasherNode; /// \ingroup View /// @{ /// An implementation of the DasherView class /// /// This class renders Dasher in the vanilla style, /// but with horizontal and vertical mappings /// /// Horizontal mapping - linear and log /// Vertical mapping - linear with different gradient class Dasher::CDasherViewSquare:public Dasher::CDasherView { public: /// Constructor /// /// \param pEventHandler Event handler. /// \param pSettingsStore Settings store. /// \param DasherScreen Pointer to creen to which the view will render. /// \todo Don't cache screen and model locally - screen can be /// passed as parameter to the drawing functions, and data structure /// can be extracted from the model and passed too. CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen); ~CDasherViewSquare(); /// /// Event handler /// virtual void HandleEvent(Dasher::CEvent * pEvent); /// /// Supply a new screen to draw to /// void ChangeScreen(CDasherScreen * NewScreen); /// /// @name Coordinate system conversion /// Convert between screen and Dasher coordinates /// @{ /// /// Convert a screen co-ordinate to Dasher co-ordinates /// void Screen2Dasher(screenint iInputX, screenint iInputY, myint & iDasherX, myint & iDasherY); /// /// Convert Dasher co-ordinates to screen co-ordinates /// void Dasher2Screen(myint iDasherX, myint iDasherY, screenint & iScreenX, screenint & iScreenY); /// /// Convert Dasher co-ordinates to polar co-ordinates (r,theta), with 0<r<1, 0<theta<2*pi /// - virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta); - + virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta); + /// /// Return true if there is any space around a node spanning y1 to y2 /// and the screen boundary; return false if such a node entirely encloses /// the screen boundary /// bool IsSpaceAroundNode(myint y1, myint y2); /// /// Get the bounding box of the visible region. /// void VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ); /// @} void DasherSpaceLine(myint x1, myint x2, myint y1, myint y2, int iColor, int iWidth); private: /// /// Draw text specified in Dasher co-ordinates + /// NOTE: The node pointer optional parameter is to allow the node flags + /// to be checked at the time when the exact text position is available. + /// + /// This solution is not intended to be permanent, but it's extremely + /// convenient for game mode because an event must be dispatched + /// ONLY if a certain node flag (NF_GAME) is true...and it must include + /// the text draw position. Grouping these together is the ultimate + /// goal here. - Rgee + /// + /// With a significant amount of code duplication, this could be + /// refactored to an overloaded implementation. /// + void DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string & sDisplayText, int &mostleft, bool bShove, CDasherNode* pNode = NULL); - void DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string & sDisplayText, int &mostleft, bool bShove); CDelayedDraw m_DelayDraw; /// /// Render the current state of the model. /// virtual void RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy); /// /// Recursively render all nodes in a tree. Responsible for all the Render_node calls /// void RecursiveRender(CDasherNode * Render, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth); ///Check that a node is large enough, and onscreen, to render; ///calls RecursiveRender if so, or collapses the node immediately if not bool CheckRender(CDasherNode * Render, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth); /// Render a single node /// \param Color The colour to draw it /// \param y1 Upper extent. /// \param y2 Lower extent /// \param mostleft The left most position in which the text (l->r) /// can be displayed in order to avoid overlap. This is updated by /// the function to allow for the new text /// \param sDisplayText Text to display. /// \param bShove Whether the node shoves /// \todo Character and displaytext are redundant. We shouldn't need /// to know about alphabets here, so only use the latterr // int RenderNode(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove); int RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove); int RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove, myint iParentWidth); #ifdef _WIN32 /// /// FIXME - couldn't find windows version of round(double) so here's one! /// \param number to be rounded /// double round(double d) { if(d - floor(d) < 0.5) - return floor(d); + return floor(d); else - return ceil(d); + return ceil(d); }; #endif /// @name Nonlinearity /// Implements the non-linear part of the coordinate space mapping /// Maps a dasher Y coordinate to the Y value in a linear version of Dasher space (i.e. still not screen pixels) /// (i.e. screen coordinate = scale(ymap(dasher coord))) inline myint ymap(myint iDasherY) const; /// Inverse of the previous - i.e. dasher coord = iymap(scale(screen coord)) myint iymap(myint y) const; ///parameters used by previous const myint m_Y1, m_Y2, m_Y3; myint xmap(myint x) const; myint ixmap(myint x) const; inline void Crosshair(myint sx); inline myint CustomIDiv(myint iNumerator, myint iDenominator); void DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, vector<CDasherScreen::point> &vPoints); // Called on screen size or orientation changes void SetScaleFactor(); // Data double m_dXmpa, m_dXmpb, m_dXmpc; screenint iCenterX; // Cached values for scaling myint iScaleFactorX; myint iScaleFactorY; // The factor that scale factors are multipled by myint m_iScalingFactor; // Cached extents of visible region myint m_iDasherMinX; myint m_iDasherMaxX; myint m_iDasherMinY; myint m_iDasherMaxY; }; /// @} #include "DasherViewSquare.inl" #endif /* #ifndef __DasherViewSquare_h__ */ diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 0a644a9..bd20cd8 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,191 +1,209 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" + namespace Dasher { class CEvent; class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CGameTargetChangedEvent; + class CGameNodeDrawEvent; class CMessageEvent; class CCommandEvent; class CDasherView; + class CDasherNode; } enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW, EV_GAME_TARGET_CHANGED + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_GAME_TARGET_CHANGED, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW, + EV_GAME_NODE_DRAWN }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; +class Dasher::CGameNodeDrawEvent : public Dasher::CEvent { +public: + CGameNodeDrawEvent(CDasherNode* pNode, CDasherView* pView, screenint iX, screenint iY) + : m_pNode(pNode), + m_pView(pView), + m_iX(iX), + m_iY(iY) { + m_iEventType = EV_GAME_NODE_DRAWN; + }; + + CDasherNode* m_pNode; + screenint m_iX, m_iY; + CDasherView* m_pView; +}; class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { public: CGameTargetChangedEvent(std::string strTargetText) : m_strTargetText(strTargetText) { m_iEventType = EV_GAME_TARGET_CHANGED; }; std::string m_strTargetText; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_pDasherView(pView), m_iX(iX), m_iY(iY), m_iSize(iSize) { m_iEventType = EV_TEXTDRAW; }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The dasher view that emitted this event. */ CDasherView* m_pDasherView; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index a18a045..d69ffd4 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,131 +1,131 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: /** * @var typedef vector<vector<CDasherComponent*>> ListenerMap * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<CDasherComponent*> > ListenerMap; /** * @var typedef vector<pair<CDasherComponent*, int> > ListenerQueue * @brief A queue whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<CDasherComponent*, int> > ListenerQueue; - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(11), m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(12), m_pInterface(pInterface) { m_iInHandler = 0; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ ListenerMap m_vSpecificListeners; /** * The queue of listeners waiting to be registered with specific * events while InsertEvent is still processing. Used to prevent * m_vSpecificListeners from being modified while InsertEvent is * iterating over it. */ ListenerQueue m_vSpecificListenerQueue; /** * The queue of "old style" listeners waiting to be registered * with all events while InsertEvent is still processing. Used * to prevent m_vSpecificListeners from being modified while * InsertEvent is iterating over it. */ std::vector<CDasherComponent*> m_vGeneralListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; private: /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 8ec1fc0..03cc58d 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,139 +1,148 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); + } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: - g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } + case EV_GAME_NODE_DRAWN: + { + CGameNodeDrawEvent* evt = static_cast<CGameNodeDrawEvent*>(pEvent); + evt->m_pView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + } + break; + /* case EV_TEXTDRAW: { - CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); + CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; + */ default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } - // This causes all sorts of strange errors about abiguous references. - //m_pEventHandler->InsertEvent(new CGameTargetChangedEvent(m_sTargetString)); + m_pEventHandler->InsertEvent( + new CGameTargetChangedEvent(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)) + ); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index d2134ee..59b9f87 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,210 +1,213 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" +#include "EventHandler.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); + + } virtual ~CGameModule() { }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
89bbcb570f5762f48ae0abc1daab863d49cd9b33
Finally got Gtest integrated into our build process. Starting to write some unit tests for the new event system.
diff --git a/Makefile.am b/Makefile.am index 84ceda7..fa59c4f 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,71 +1,71 @@ -SUBDIRS = Src Data Doc +SUBDIRS = Src Data Doc Testing/dasher_tests if USE_INTLTOOL SUBDIRS += po endif ACLOCAL_AMFLAGS = -I m4 distuninstallcheck_listfiles = \ find . -type f -print | \ grep -v '^\./var/scrollkeeper' | \ grep -v '^\./share/gnome/help' EXTRA_DIST = \ INSTALL.Linux \ INSTALL.WinCE \ INSTALL.Windows \ MAINTAINERS \ m4/pkg.m4 \ m4/glib-gettext.m4 \ m4/dgconf-2.m4 \ m4/gnome-doc-utils.m4 \ m4/intltool.m4 \ m4/nls.m4 \ intltool-merge.in \ intltool-extract.in \ intltool-update.in \ gnome-doc-utils.make \ .tarball-version \ build-aux/mkversion DISTCLEANFILES = \ intltool-merge \ intltool-extract \ intltool-update \ Data/dasher.desktop \ Data/Help/Gnome/Makefile MAINTAINERCLEANFILES = \ $(srcdir)/INSTALL \ $(srcdir)/aclocal.m4 \ $(srcdir)/autoscan.log \ $(srcdir)/compile \ $(srcdir)/config.guess \ $(srcdir)/config.h.in \ $(srcdir)/config.h.in~ \ $(srcdir)/config.sub \ $(srcdir)/configure \ $(srcdir)/configure.scan \ $(srcdir)/depcomp \ $(srcdir)/install-sh \ $(srcdir)/ltmain.sh \ $(srcdir)/missing \ $(srcdir)/mkinstalldirs \ $(srcdir)/intltool-extract.in \ $(srcdir)/intltool-merge.in \ $(srcdir)/intltool-update.in \ $(srcdir)/omf.make \ $(srcdir)/xmldocs.make \ $(srcdir)/po/Makefile.in.in maemo-install: all - mkdir tmp_build cp -a Data/maemo/* tmp_build cp Src/dasher tmp_build/usr/bin/dasher strip tmp_build/usr/bin/dasher cp Data/GUI/dashermaemo.ui Data/GUI/dashermaemofullscreen.ui tmp_build/usr/share/dasher cp Data/training/training_english_GB.txt Data/alphabets/alphabet.english.xml Data/colours/colour.xml tmp_build/usr/share/dasher ln -sf /usr/share/applications/hildon/dasher.desktop tmp_build/etc/others-menu/extra_applications/0301_dasher.desktop - find tmp_build -name .git -exec rm -rf \{\} \; dpkg-deb -b tmp_build dasher_4.11.0.0inferencemaemo1_armel.deb rm -rf tmp_build diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index 038bac7..ca2821d 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,6 +1,46 @@ #include "gtest/gtest.h" -#include "MockInterfaceBase.h" +#include "../../Src/TestPlatform/MockInterfaceBase.h" +#include "../../Src/TestPlatform/MockSettingsStore.h" +#include "../../Src/DasherCore/EventHandler.h" -TEST(EventTest, simpletest) { - EXPECT_EQ(1, 1); +class DummyComponent : public Dasher::CDasherComponent { + + public: + + bool receivedEvent; + + DummyComponent(Dasher::CEventHandler* pEventHandler, Dasher::CSettingsStore* pSettingsStore) : + Dasher::CDasherComponent(pEventHandler, pSettingsStore) { + receivedEvent = false; + } + + void HandleEvent(Dasher::CEvent *pEvent) { + receivedEvent = true; + } +}; + +class EventTest : public ::Testing::Test { + + public: + + EventTest() { + + interfaceBase = new CMockInterfaceBase(); + settingsStore = new CMockSettingsStore(); + evtHandler = new Dasher::CEventHandler(interfaceBase); + } + + protected: + + Dasher::CEventHandler *evtHandler; + CMockInterfaceBase *interfaceBase; + CMockSettingsStore *settingsStore; +}; + +TEST_F(EventTest, BasicHandling) { + + DummyComponent *listener = new DummyComponent(evtHandler, settingsStore); + evtHandler->RegisterListener(listener, 1); + evtHandler->InsertEvent(new CParameterNotificationEvent(12)); + ASSERT_TRUE(listener->receievedEvent); } diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index dabfc60..e2b6311 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,78 +1,81 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. GTEST_DIR = ../gtest #Points to the root of Dasher's source code DASHER_CORE_DIR = ../../Src/DasherCore TEST_PLATFORM_DIR = ../../Src/TestPlatform # Where to find user code. USER_DIR = . # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include # Flags passed to the C++ compiler. -CXXFLAGS += -g -Wall -Wextra +CXXFLAGS += -g # All tests produced by this Makefile. Remember to add new tests you # created to the list. TESTS = EventTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ -EventTest : EventTest.o gtest_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ - EventTest.o : $(USER_DIR)/EventTest.cpp - $(CXX) $(CPPFLAGS) -I$(DASHER_CORE_DIR) -I$(TEST_PLATFORM_DIR) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp +EventTest : EventTest.o \ + gtest_main.a $(DASHER_CORE_DIR)/libdashercore.a \ + $(DASHER_CORE_DIR)/libdasherprefs.a \ + $(DASHER_CORE_DIR)/LanguageModelling/libdasherlm.a + $(CXX) $(CPPFLAGS) -lexpat $(CXXFLAGS) -lpthread $^ -o $@ +
rgee/HFOSS-Dasher
6772aeba544a0bce957b1a0ad2dc2e4945d83d53
Begun trying to integrate NF_GAME to track nodes on the game target's path.
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index bd5ce3e..70afecf 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,461 +1,462 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, pGroup ? (pGroup->bVisible ? pGroup->iColour : pParent->getColour()) : pMgr->m_pNCManager->GetAlphabet()->GetColour(0, iOffset%2), pGroup ? pGroup->strLabel : "", pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { return new CSymbolNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup) { return new CGroupNode(pParent, iOffset, iLbnd, iHbnd, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pNewNode = makeGroup(pParent, iNewOffset, iLower, iUpper, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pNewNode = makeSymbol(pParent, iNewOffset, iLower, iUpper, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->iContext = iContext; + return pNewNode; } bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { SetFlag(NF_GAME, true); return true; } return false; } bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { if (GameSearchChildren(strTargetUtf8Char)) { SetFlag(NF_GAME, true); return true; } return false; } CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->offset() == offset()); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // When creating a group node... // ...the offset is the same as the parent... CGroupNode *pNewNode = makeGroup(pParent, pParent->offset(), iLbnd, iHbnd, pInfo); //...as is the context! pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (offset() == pParent->offset()); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); } else { // TODO: Exceptions / error handling in general CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, pParent->offset()+1, iLbnd, iHbnd, iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(offset() == pParent->offset() + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); //loop for eliding groups with single children (see below). // Variables store necessary properties of any elided groups: std::string groupPrefix=""; int iOverrideColour=-1; SGroupInfo *pInner=pCurrentNode; while (true) { if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop break; //exit inner (group elision) loop } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); i = pInner->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) // (maybe not of pCurrentNode now, which might be a subgroup filling the original) break; //exit inner (group elision) loop } //were about to create a group node, which would have only one child // (eventually, if the group node were PopulateChildren'd). // Such a child would entirely fill it's parent (the group), and thus, // creation/destruction of the child would cause the node's colour to flash // between that for parent group and child. // Hence, instead we elide the group node and create the child _here_... //1. however we also have to take account of the appearance of the elided group. Hence: groupPrefix += pInner->strLabel; if (pInner->bVisible) iOverrideColour=pInner->iColour; //2. now go into the group... pInner = pInner->pChild; bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok //3. loop round inner loop... } //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); //now adjust the node we've actually created, to take account of any elided group(s)... // tho not if we've reused the existing node, assume that's been adjusted already if (pNewChild && pNewChild!=buildAround) pNewChild->PrependElidedGroup(iOverrideColour, groupPrefix); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(offset()); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(offset()-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 536ea35..8a980aa 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,810 +1,815 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, - CSettingsStore *pSettingsStore, - CNodeCreationManager *pNCManager, - CDasherInterfaceBase *pDasherInterface, - CDasherView *pView, int iOffset) + CSettingsStore *pSettingsStore, + CNodeCreationManager *pNCManager, + CDasherInterfaceBase *pDasherInterface, + CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) - TriggerSlowdown(); + TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } + else if(pEvent->m_iEventType == EV_GAME_TARGET_CHANGED) { + CGameTargetChangedEvent *pTargetChangedEvent(static_cast< CGameTargetChangedEvent * >(pEvent)); + + m_strGameTarget = pTargetChangedEvent->m_strTargetText; + } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; // Create children of the root... ExpandNode(m_Root); - + // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) - break; + break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) { std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") - pNode->SetFlag(NF_END_GAME, true); - else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { + pNode->SetFlag(NF_END_GAME, true); + else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); } } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index 82482f3..85dbf02 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,374 +1,379 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; + + /** + * The string a user must type if game mode is active. + */ + std::string m_strGameTarget; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */ diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index e3303ce..0a644a9 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,179 +1,191 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; + class CGameTargetChangedEvent; class CMessageEvent; class CCommandEvent; class CDasherView; } enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW, EV_GAME_TARGET_CHANGED }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; + +class Dasher::CGameTargetChangedEvent : public Dasher::CEvent { +public: + CGameTargetChangedEvent(std::string strTargetText) + : m_strTargetText(strTargetText) { + m_iEventType = EV_GAME_TARGET_CHANGED; + }; + + std::string m_strTargetText; +}; + class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) - :m_sDisplayText(sDisplayText), - m_pDasherView(pView), - m_iX(iX), - m_iY(iY), - m_iSize(iSize) - { - m_iEventType = EV_TEXTDRAW; - }; + :m_sDisplayText(sDisplayText), + m_pDasherView(pView), + m_iX(iX), + m_iY(iY), + m_iSize(iSize) + { + m_iEventType = EV_TEXTDRAW; + }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The dasher view that emitted this event. */ CDasherView* m_pDasherView; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 0bbeda1..a18a045 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,131 +1,131 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: /** * @var typedef vector<vector<CDasherComponent*>> ListenerMap * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<CDasherComponent*> > ListenerMap; /** * @var typedef vector<pair<CDasherComponent*, int> > ListenerQueue * @brief A queue whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<CDasherComponent*, int> > ListenerQueue; - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(11), m_pInterface(pInterface) { m_iInHandler = 0; - // Initialize the event listener container (and queue) so we can add elements without - // checking if the sub-vectors actually exist or not. - for(int i = 0; i < m_iNUM_EVENTS; i++) { - m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); - } + // Initialize the event listener container (and queue) so we can add elements without + // checking if the sub-vectors actually exist or not. + for(int i = 0; i < m_iNUM_EVENTS; i++) { + m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); + } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent); - /** + /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h - * that represents the event to which you'd like to subscribe. + * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h - * that represents the event to which you'd like to unsubscribe. + * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); - /** + /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ ListenerMap m_vSpecificListeners; /** * The queue of listeners waiting to be registered with specific * events while InsertEvent is still processing. Used to prevent * m_vSpecificListeners from being modified while InsertEvent is * iterating over it. */ ListenerQueue m_vSpecificListenerQueue; /** * The queue of "old style" listeners waiting to be registered * with all events while InsertEvent is still processing. Used * to prevent m_vSpecificListeners from being modified while * InsertEvent is iterating over it. */ std::vector<CDasherComponent*> m_vGeneralListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; private: /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 39d533f..8ec1fc0 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,137 +1,139 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); CDasherScreen::point points[2]; // Top Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line points[0].x = screenTargetX - m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX + m_iCrosshairExtent; points[0].y = screenTargetY - m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line points[0].x = screenTargetX + m_iCrosshairExtent; points[1].x = screenTargetX - m_iCrosshairExtent; points[0].y = screenTargetY + m_iCrosshairExtent; points[1].y = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line points[0].x = screenTargetX; points[1].x = screenTargetX; points[0].y = screenTargetY + m_iCrosshairCrosslineLength; points[1].y = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line points[0].x = screenTargetX + m_iCrosshairCrosslineLength; points[1].x = screenTargetX - m_iCrosshairCrosslineLength; points[0].y = screenTargetY; points[1].y = screenTargetY; pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } + // This causes all sorts of strange errors about abiguous references. + //m_pEventHandler->InsertEvent(new CGameTargetChangedEvent(m_sTargetString)); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index a7d1680..d2134ee 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,208 +1,210 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" + + namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
885faada0499e7aee3e4cc11c3bc993d93db1776
ScreenPolyline now takes an array of points. This makes much more sense. Updated GameModule to comply.
diff --git a/Src/DasherCore/DasherView.cpp b/Src/DasherCore/DasherView.cpp index 219a580..cf8dc15 100644 --- a/Src/DasherCore/DasherView.cpp +++ b/Src/DasherCore/DasherView.cpp @@ -1,322 +1,313 @@ // DasherView.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherGameMode.h" #include "DasherInput.h" #include "DasherModel.h" #include "DasherView.h" #include "Event.h" #include "EventHandler.h" #include "DasherScreen.h" using namespace Dasher; using std::vector; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif ///////////////////////////////////////////////////////////////////////////// CDasherView::CDasherView(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) :CDasherComponent(pEventHandler, pSettingsStore), m_pScreen(DasherScreen), m_pInput(0), m_bDemoMode(false), m_bGameMode(false) { } ///////////////////////////////////////////////////////////////////////////// void CDasherView::ChangeScreen(CDasherScreen *NewScreen) { m_pScreen = NewScreen; } ///////////////////////////////////////////////////////////////////////////// void CDasherView::Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay) { m_iRenderCount = 0; Screen()->SetLoadBackground(false); RenderNodes(pRoot, iRootMin, iRootMax, policy); } int CDasherView::GetCoordinateCount() { // TODO: Do we really need support for co-ordinate counts other than 2? if(m_pInput) return m_pInput->GetCoordinateCount(); else return 0; } int CDasherView::GetInputCoordinates(int iN, myint * pCoordinates) { if(m_pInput) return m_pInput->GetCoordinates(iN, pCoordinates); else return 0; } void CDasherView::SetInput(CDasherInput * _pInput) { // TODO: Is it sensible to make this responsible for the input // device - I guess it makes sense for now DASHER_ASSERT_VALIDPTR_RW(_pInput); // Don't delete the old input class; whoever is calling this method // might want to keep several Input class instances around and // change which one is currently driving dasher without deleting any m_pInput = _pInput; // Tell the new object about maximum values myint iMaxCoordinates[2]; iMaxCoordinates[0] = GetLongParameter(LP_MAX_Y); iMaxCoordinates[1] = GetLongParameter(LP_MAX_Y); m_pInput->SetMaxCoordinates(2, iMaxCoordinates); } void CDasherView::Display() { Screen()->SetLoadBackground(true); m_pScreen->Display(); } void CDasherView::DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColor) { if (!ClipLineToVisible(x1, y1, x2, y2)) return; vector<CDasherScreen::point> vPoints; CDasherScreen::point p; Dasher2Screen(x1, y1, p.x, p.y); vPoints.push_back(p); DasherLine2Screen(x1,y1,x2,y2,vPoints); CDasherScreen::point *pts = new CDasherScreen::point[vPoints.size()]; for (int i = vPoints.size(); i-->0; ) pts[i] = vPoints[i]; Screen()->Polyline(pts, vPoints.size(), iWidth, iColor); } bool CDasherView::ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2) { if (x1 > x2) return ClipLineToVisible(x2,y2,x1,y1); //ok. have x1 <= x2... myint iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (x1 > iDasherMaxX) { DASHER_ASSERT(x2>iDasherMaxX); return false; //entirely offscreen! } if (x2 < iDasherMinX) { DASHER_ASSERT(x1<iDasherMinX); return false; } if (y1 < iDasherMinY && y2 < iDasherMinY) return false; if (y1 > iDasherMaxY && y2 > iDasherMaxY) return false; if (x1 < iDasherMinX) { y1 = y2+((y1-y2)*(iDasherMinX-x2)/(x1 - x2)); x1 = iDasherMinX; } if (x2 > iDasherMaxX) { y2 = y1 + (y2-y1)*(iDasherMaxX-x1)/(x2-x1); x2 = iDasherMaxX; } for (int i=0; i<2; i++) { myint &y(i ? y2 : y1), &oy(i ? y1 : y2); myint &x(i ? x2 : x1), &ox(i ? x1 : x2); if (y<iDasherMinY) { x = ox- (ox-x)*(oy-iDasherMinY)/(oy-y); y = iDasherMinY; } else if (y>iDasherMaxY) { x = ox-(ox-x)*(oy-iDasherMaxY)/(oy-y); y = iDasherMaxY; } } return true; } /// Draw a polyline specified in Dasher co-ordinates void CDasherView::DasherPolyline(myint *x, myint *y, int n, int iWidth, int iColour) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); if(iColour != -1) { Screen()->Polyline(ScreenPoints, n, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n, iWidth,0);//no color given } delete[]ScreenPoints; } -void CDasherView::ScreenPolyline(screenint *x, screenint *y, int n, int iWidth, int iColour) { - CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; - - for(int i(0); i < n; ++i) - { - ScreenPoints[i].x = x[i]; - ScreenPoints[i].y = y[i]; - } - +void CDasherView::ScreenPolyline(CDasherScreen::point points[], int n, int iWidth, int iColour) { if(iColour != -1) { - Screen()->Polyline(ScreenPoints, n, iWidth, iColour); + Screen()->Polyline(points, n, iWidth, iColour); } else { - Screen()->Polyline(ScreenPoints, n, iWidth, 0); + Screen()->Polyline(points, n, iWidth, 0); } - delete[] ScreenPoints; } // Draw a polyline with an arrow on the end void CDasherView::DasherPolyarrow(myint *x, myint *y, int n, int iWidth, int iColour, double dArrowSizeFactor) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n+3]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); int iXvec = (int)((ScreenPoints[n-2].x - ScreenPoints[n-1].x)*dArrowSizeFactor); int iYvec = (int)((ScreenPoints[n-2].y - ScreenPoints[n-1].y)*dArrowSizeFactor); ScreenPoints[n].x = ScreenPoints[n-1].x + iXvec + iYvec; ScreenPoints[n].y = ScreenPoints[n-1].y - iXvec + iYvec; ScreenPoints[n+1].x = ScreenPoints[n-1].x ; ScreenPoints[n+1].y = ScreenPoints[n-1].y ; ScreenPoints[n+2].x = ScreenPoints[n-1].x + iXvec - iYvec; ScreenPoints[n+2].y = ScreenPoints[n-1].y + iXvec + iYvec; if(iColour != -1) { Screen()->Polyline(ScreenPoints, n+3, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n+3, iWidth,0);//no color given } delete[]ScreenPoints; } // Draw a box specified in Dasher co-ordinates void CDasherView::DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness) { screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iLeft, iTop, iScreenLeft, iScreenTop); Dasher2Screen(iRight, iBottom, iScreenRight, iScreenBottom); Screen()->DrawRectangle(iScreenLeft, iScreenTop, iScreenRight, iScreenBottom, Color, iOutlineColour, ColorScheme, iThickness); } /// Draw a rectangle centred on a given dasher co-ordinate, but with a size specified in screen co-ordinates (used for drawing the mouse blob) void CDasherView::DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline) { screenint iScreenX; screenint iScreenY; Dasher2Screen(iDasherX, iDasherY, iScreenX, iScreenY); Screen()->DrawRectangle(iScreenX - iSize, iScreenY - iSize, iScreenX + iSize, iScreenY + iSize, Color, -1, ColorScheme, bDrawOutline ? 1 : 0); } void CDasherView::DrawText(const std::string & str, screenint x, screenint y, int iSize, int iColor) { Screen()->DrawString(str, x, y, iSize, iColor); } void CDasherView::DrawText(const std::string & str, myint x, myint y, int Size, int iColor) { screenint X, Y; Dasher2Screen(x, y, X, Y); Screen()->DrawString(str, X, Y, Size, iColor); } int CDasherView::GetCoordinates(myint &iDasherX, myint &iDasherY) { // FIXME - Actually turn autocalibration on and off! // FIXME - AutoCalibrate should use Dasher co-ordinates, not raw mouse co-ordinates? // FIXME - Have I broken this by moving it before the offset is applied? // FIXME - put ymap stuff back in // FIXME - optimise this int iCoordinateCount(GetCoordinateCount()); myint *pCoordinates(new myint[iCoordinateCount]); int iType(GetInputCoordinates(iCoordinateCount, pCoordinates)); screenint mousex; screenint mousey; if(iCoordinateCount == 1) { mousex = 0; mousey = pCoordinates[0]; } else { mousex = pCoordinates[0]; mousey = pCoordinates[1]; } delete[]pCoordinates; switch(iType) { case 0: Screen2Dasher(mousex, mousey, iDasherX, iDasherY); break; case 1: iDasherX = mousex; iDasherY = mousey; break; default: // TODO: Error break; } ///GAME/// if(m_bGameMode) { using GameMode::CDasherGameMode; if(m_bDemoMode) CDasherGameMode::GetTeacher()->DemoModeGetCoordinates(iDasherX, iDasherY); CDasherGameMode::GetTeacher()->SetUserMouseCoordinates(iDasherX, iDasherY); } return iType; } void CDasherView::SetDemoMode(bool bDemoMode) { m_bDemoMode = bDemoMode; } void CDasherView::SetGameMode(bool bGameMode) { m_bGameMode = bGameMode; } diff --git a/Src/DasherCore/DasherView.h b/Src/DasherCore/DasherView.h index 3d3b47a..a83ca66 100644 --- a/Src/DasherCore/DasherView.h +++ b/Src/DasherCore/DasherView.h @@ -1,248 +1,248 @@ // DasherView.h // // Copyright (c) 2001-2005 David Ward #ifndef __DasherView_h_ #define __DasherView_h_ namespace Dasher { class CDasherModel; class CDasherInput; // Why does DasherView care about input? - pconlon class CDasherComponent; class CDasherView; class CDasherNode; } #include "DasherTypes.h" #include "DasherComponent.h" #include "ExpansionPolicy.h" #include "DasherScreen.h" /// \defgroup View Visualisation of the model /// @{ /// \brief View base class. /// /// Dasher views represent the visualisation of a Dasher model on the screen. /// /// Note that we really should aim to avoid having to try and keep /// multiple pointers to the same object (model etc.) up-to-date at /// once. We should be able to avoid the need for this just by being /// sane about passing pointers as arguments to the relevant /// functions, for example we could pass a pointer to the canvas every /// time we call the render routine, rather than worrying about /// notifying this object every time it changes. The same logic can be /// applied in several other places. /// /// We should also attempt to try and remove the need for this class /// to know about the model. When we call render we should just pass a /// pointer to the root node, which we can obtain elsewhere, and make /// sure that the data structure contains all the info we need to do /// the rendering (eg make sure it contains strings as well as symbol /// IDs). /// /// There are really three roles played by CDasherView: providing high /// level drawing functions, providing a mapping between Dasher /// co-ordinates and screen co-ordinates and providing a mapping /// between true and effective Dasher co-ordinates (eg for eyetracking /// mode). We should probably consider creating separate classes for /// these. class Dasher::CDasherView : public Dasher::CDasherComponent { public: /// Constructor /// /// \param pEventHandler Pointer to the event handler /// \param pSettingsStore Pointer to the settings store /// \param DasherScreen Pointer to the CDasherScreen object used to do rendering CDasherView(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CDasherScreen * DasherScreen); virtual ~CDasherView() { } /// @name Pointing device mappings /// @{ /// Set the input device class. Note that this class will now assume ownership of the pointer, ie it will delete the object when it's done with it. /// \param _pInput Pointer to the new CDasherInput. void SetInput(CDasherInput * _pInput); void SetDemoMode(bool); void SetGameMode(bool); /// Translates the screen coordinates to Dasher coordinates and calls /// dashermodel.TapOnDisplay virtual int GetCoordinates(myint &iDasherX, myint &iDasherY); /// Get the co-ordinate count from the input device int GetCoordinateCount(); /// @} /// /// @name Coordinate system conversion /// Convert between screen and Dasher coordinates /// @{ /// /// Convert a screen co-ordinate to Dasher co-ordinates /// virtual void Screen2Dasher(screenint iInputX, screenint iInputY, myint & iDasherX, myint & iDasherY) = 0; /// /// Convert Dasher co-ordinates to screen co-ordinates /// virtual void Dasher2Screen(myint iDasherX, myint iDasherY, screenint & iScreenX, screenint & iScreenY) = 0; /// /// Convert Dasher co-ordinates to polar co-ordinates (r,theta), with 0<r<1, 0<theta<2*pi /// virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) = 0; virtual bool IsSpaceAroundNode(myint y1, myint y2)=0; virtual void VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) = 0; /// @} /// Change the screen - must be called if the Screen is replaced or resized /// \param NewScreen Pointer to the new CDasherScreen. virtual void ChangeScreen(CDasherScreen * NewScreen); /// @name High level drawing /// Drawing more complex structures, generally implemented by derived class /// @{ /// Renders Dasher with mouse-dependent items /// \todo Clarify relationship between Render functions and probably only expose one virtual void Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay); /// @} ////// Return a reference to the screen - can't be protected due to circlestarthandler CDasherScreen *Screen() { return m_pScreen; } /// /// @name Low level drawing /// Basic drawing primitives specified in Dasher coordinates. /// @{ ///Draw a straight line in Dasher-space - which may be curved on the screen... void DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColour); /// /// Draw a polyline specified in Dasher co-ordinates /// void DasherPolyline(myint * x, myint * y, int n, int iWidth, int iColour); /** * Draw a line in screen coordinates. Needed for drawing without respect to * the strange squishing and resizing that can happen when drawing in Dasher * coordinates. * * @see DasherPolyline */ - void ScreenPolyline(screenint * x, screenint * y, int n, int iWidth, int iColour); + void ScreenPolyline(CDasherScreen::point points[], int n, int iWidth, int iColour); /** * Draw an arrow in Dasher space. The parameters x and y allow the client to specify * points through which the arrow's main line should be drawn. For example, to draw an * arrow through the Dasher coordinates (1000, 2000) and (3000, 4000), one would pass in: * * myint x[2] = {1000, 3000}; * myint y[2] = {2000, 4000}; * * @param x - an array of x coordinates to draw the arrow through * @param y - an array of y coordinates to draw the arrow through * @param iWidth - the width to make the arrow lines - typically of the form * GetLongParameter(LP_LINE_WIDTH)*CONSTANT * @param iColour - the color to make the arrow (in Dasher color) * @param dArrowSizeFactor - the factor by which to scale the "hat" on the arrow */ void DasherPolyarrow(myint * x, myint * y, int n, int iWidth, int iColour, double dArrowSizeFactor = 0.7071); /// /// Draw a rectangle specified in Dasher co-ordinates /// Color of -1 => no fill; any other value => fill in that color /// iOutlineColor of -1 => no outline; any other value => outline in that color, EXCEPT /// Thickness < 1 => no outline. /// void DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness); /// /// Draw a centred rectangle specified in Dasher co-ordinates (used for mouse cursor) /// void DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline); void DrawText(const std::string & str, myint x, myint y, int Size, int iColor); /** * Draw a string to the screen. Defined in screen coordinates because * the original implementation will conver them anyway. They're also * easier to reason about for drawing overlays. * @param str The actual string to be drawn * @param x The x coordinate in screen coordinates. * @param y The y coordinate in screen coordinates. * @param iSize The size of the text. * @param iColor The color of the text. */ void DrawText(const std::string & str, screenint x, screenint y, int iSize, int iColor); /// Request the Screen to copy its buffer to the Display /// \todo Shouldn't be public? void Display(); /// @} protected: /// Clips a line (specified in Dasher co-ordinates) to the visible region /// by intersecting with all boundaries. /// \return true if any part of the line was within the visible region; in this case, (x1,y1)-(x2,y2) delineate exactly that part /// false if the line would be entirely outside the visible region; x1, y1, x2, y2 unaffected. bool ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2); ///Convert a straight line in Dasher-space, to coordinates for a corresponding polyline on the screen /// (because of nonlinearity, this may require multiple line segments) /// \param x1,y1 Dasher co-ordinates of start of line segment; note that these are guaranteed within VisibleRegion. /// \param x2,y2 Dasher co-ordinates of end of line segment; also guaranteed within VisibleRegion. /// \param vPoints vector to which to add screen points. Note that at the point that DasherLine2Screen is called, /// the screen coordinates of the first point should already have been added to this vector; DasherLine2Screen /// will then add exactly one CDasherScreen::point for each line segment required. virtual void DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, std::vector<CDasherScreen::point> &vPoints)=0; // Orientation of Dasher Screen /* inline void MapScreen(screenint * DrawX, screenint * DrawY); */ /* inline void UnMapScreen(screenint * DrawX, screenint * DrawY); */ bool m_bVisibleRegionValid; int m_iRenderCount; private: CDasherScreen *m_pScreen; // provides the graphics (text, lines, rectangles): CDasherInput *m_pInput; // Input device abstraction /// Renders the Dasher node structure virtual void RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) = 0; /// Get the co-ordinates from the input device int GetInputCoordinates(int iN, myint * pCoordinates); bool m_bDemoMode; bool m_bGameMode; }; /// @} #endif /* #ifndef __DasherView_h_ */ diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 4f31576..39d533f 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,138 +1,137 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); - - screenint x[2]; - screenint y[2]; - + + CDasherScreen::point points[2]; + // Top Line - x[0] = screenTargetX + m_iCrosshairExtent; - x[1] = screenTargetX - m_iCrosshairExtent; - y[0] = screenTargetY - m_iCrosshairExtent; - y[1] = screenTargetY - m_iCrosshairExtent; - pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + points[0].x = screenTargetX + m_iCrosshairExtent; + points[1].x = screenTargetX - m_iCrosshairExtent; + points[0].y = screenTargetY - m_iCrosshairExtent; + points[1].y = screenTargetY - m_iCrosshairExtent; + pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line - x[0] = screenTargetX - m_iCrosshairExtent; - x[1] = screenTargetX - m_iCrosshairExtent; - y[0] = screenTargetY - m_iCrosshairExtent; - y[1] = screenTargetY + m_iCrosshairExtent; - pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + points[0].x = screenTargetX - m_iCrosshairExtent; + points[1].x = screenTargetX - m_iCrosshairExtent; + points[0].y = screenTargetY - m_iCrosshairExtent; + points[1].y = screenTargetY + m_iCrosshairExtent; + pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line - x[0] = screenTargetX + m_iCrosshairExtent; - x[1] = screenTargetX + m_iCrosshairExtent; - y[0] = screenTargetY - m_iCrosshairExtent; - y[1] = screenTargetY + m_iCrosshairExtent; - pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + points[0].x = screenTargetX + m_iCrosshairExtent; + points[1].x = screenTargetX + m_iCrosshairExtent; + points[0].y = screenTargetY - m_iCrosshairExtent; + points[1].y = screenTargetY + m_iCrosshairExtent; + pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line - x[0] = screenTargetX + m_iCrosshairExtent; - x[1] = screenTargetX - m_iCrosshairExtent; - y[0] = screenTargetY + m_iCrosshairExtent; - y[1] = screenTargetY + m_iCrosshairExtent; - pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + points[0].x = screenTargetX + m_iCrosshairExtent; + points[1].x = screenTargetX - m_iCrosshairExtent; + points[0].y = screenTargetY + m_iCrosshairExtent; + points[1].y = screenTargetY + m_iCrosshairExtent; + pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line - x[0] = screenTargetX; - x[1] = screenTargetX; - y[0] = screenTargetY + m_iCrosshairCrosslineLength; - y[1] = screenTargetY - m_iCrosshairCrosslineLength; - pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + points[0].x = screenTargetX; + points[1].x = screenTargetX; + points[0].y = screenTargetY + m_iCrosshairCrosslineLength; + points[1].y = screenTargetY - m_iCrosshairCrosslineLength; + pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line - x[0] = screenTargetX + m_iCrosshairCrosslineLength; - x[1] = screenTargetX - m_iCrosshairCrosslineLength; - y[0] = screenTargetY; - y[1] = screenTargetY; - pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + points[0].x = screenTargetX + m_iCrosshairCrosslineLength; + points[1].x = screenTargetX - m_iCrosshairCrosslineLength; + points[0].y = screenTargetY; + points[1].y = screenTargetY; + pView->ScreenPolyline(points, 2, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } }
rgee/HFOSS-Dasher
815e38ffeb0a139015b74672ada0816ed0530916
More work integrating GTest
diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp index 4cfab05..038bac7 100755 --- a/Testing/dasher_tests/EventTest.cpp +++ b/Testing/dasher_tests/EventTest.cpp @@ -1,5 +1,6 @@ #include "gtest/gtest.h" +#include "MockInterfaceBase.h" TEST(EventTest, simpletest) { EXPECT_EQ(1, 1); } diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index c03d350..dabfc60 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,87 +1,78 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. -GTEST_DIR = ../gtest-1.5.0 +GTEST_DIR = ../gtest + +#Points to the root of Dasher's source code +DASHER_CORE_DIR = ../../Src/DasherCore + +TEST_PLATFORM_DIR = ../../Src/TestPlatform # Where to find user code. USER_DIR = . # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include # Flags passed to the C++ compiler. CXXFLAGS += -g -Wall -Wextra # All tests produced by this Makefile. Remember to add new tests you # created to the list. TESTS = EventTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ - -# Builds a sample test. A test should link with either gtest.a or -# gtest_main.a, depending on whether it defines its own main() -# function. - -#sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) -# $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc - -#sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ -# $(USER_DIR)/sample1.h $(GTEST_HEADERS) -# $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc - -#sample1_unittest : sample1.o sample1_unittest.o gtest_main.a -# $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ EventTest : EventTest.o gtest_main.a $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ EventTest.o : $(USER_DIR)/EventTest.cpp - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp + $(CXX) $(CPPFLAGS) -I$(DASHER_CORE_DIR) -I$(TEST_PLATFORM_DIR) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp
rgee/HFOSS-Dasher
555ee857c43a779a50b27d040d60fd92e35af914
Game Module now overlays the typed text with a different color to indicate progress through the target string.
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 118031e..4f31576 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,139 +1,138 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); screenint x[2]; screenint y[2]; // Top Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY - m_iCrosshairExtent; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x[0] = screenTargetX - m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX + m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY + m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x[0] = screenTargetX; x[1] = screenTargetX; y[0] = screenTargetY + m_iCrosshairCrosslineLength; y[1] = screenTargetY - m_iCrosshairCrosslineLength; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x[0] = screenTargetX + m_iCrosshairCrosslineLength; x[1] = screenTargetX - m_iCrosshairCrosslineLength; y[0] = screenTargetY; y[1] = screenTargetY; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); - - pView->DrawText(GetUntypedTarget(), 400, 20, 200, m_iCrosshairColor); - + pView->DrawText(m_sTargetString, 400, 17, m_iFontSize, m_iCrosshairColor); + pView->DrawText(GetTypedTarget(), 400, 20, m_iFontSize, m_iCrosshairColor - 20); return true; } std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? - "" : m_sTargetString.substr(0, m_iCurrentStringPos)); + "" : m_sTargetString.substr(0, m_iCurrentStringPos + 1)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 570a4dc..a7d1680 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,209 +1,208 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; - /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
0eb9c809c5d17f50fb7f24c8eecddadee76ad5d4
Fixed a dumb syntax error. I should have checked for it.
diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 10c743f..570a4dc 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,209 +1,209 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; if(m_pWordGenerator == NULL) g_pLogger->LogCritical("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") - g_pLogger->LogCritica("Word generation FAILED"); + g_pLogger->LogCritical("Word generation FAILED"); } virtual ~CGameModule() { }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
73b3a5e775772f09eac56590f1ccc5a32a7d4e0c
Cleaned up Game Module constructor and wrote stand-alone developer documentation.
diff --git a/Doc/development/game_mode.pdf b/Doc/development/game_mode.pdf new file mode 100644 index 0000000..21b8000 Binary files /dev/null and b/Doc/development/game_mode.pdf differ diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 972f4f5..10c743f 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,209 +1,209 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), + m_iCurrentStringPos(-1), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; - //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) - g_pLogger->Log("Word generator creation FAILED"); + g_pLogger->LogCritical("Word generator creation FAILED"); + GenerateChunk(); if(m_sTargetString == "") - m_sTargetString = "My name is julian."; - m_iCurrentStringPos = -1; + g_pLogger->LogCritica("Word generation FAILED"); } virtual ~CGameModule() { }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
08ac9152dcbaf1d627ef732ae1769639cdc0634e
No longer deleting anything. Turns out I didn't understand what I was doing. Dodged that bullet... Also cleaned up obsolete, commented-out code.
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index e723542..118031e 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,178 +1,139 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); - /* - return( (m_iCurrentStringPos == 0) ? - !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : - !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); - */ } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); - /* - return( (m_iCurrentStringPos == 0) ? - !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : - !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); - */ } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); screenint x[2]; screenint y[2]; // Top Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY - m_iCrosshairExtent; - - //screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - //screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x[0] = screenTargetX - m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; - - //x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX + m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; - - - //x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; - //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY + m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; - - - //x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - //y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x[0] = screenTargetX; x[1] = screenTargetX; y[0] = screenTargetY + m_iCrosshairCrosslineLength; y[1] = screenTargetY - m_iCrosshairCrosslineLength; - - //x = {screenTargetX, screenTargetX}; - //y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x[0] = screenTargetX + m_iCrosshairCrosslineLength; x[1] = screenTargetX - m_iCrosshairCrosslineLength; y[0] = screenTargetY; y[1] = screenTargetY; - - - //x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; - //y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(GetUntypedTarget(), 400, 20, 200, m_iCrosshairColor); return true; } -//CDasherNode CGameModule::StringToNode(std::string sText) { -// -//} std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); - /* - return ((m_iCurrentStringPos == -1) ? - m_sTargetString.substr(m_iCurrentStringPos + 1) : - m_sTargetString.substr(m_iCurrentStringPos + 1)); - */ } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 32ad8fc..972f4f5 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,211 +1,209 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) g_pLogger->Log("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") m_sTargetString = "My name is julian."; m_iCurrentStringPos = -1; } virtual ~CGameModule() { - delete m_pWordGenerator; - delete m_pInterface; }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
8fe01e4969da80decbf8dce51cc8912ff1d15fb4
Revert "Reformatted crosshair coord. array section"
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 20cfe93..e723542 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,157 +1,178 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); /* return( (m_iCurrentStringPos == 0) ? !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); */ } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); /* return( (m_iCurrentStringPos == 0) ? !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); */ } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); screenint x[2]; screenint y[2]; // Top Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY - m_iCrosshairExtent; + + //screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + //screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x[0] = screenTargetX - m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; + + //x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX + m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; + + + //x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; + //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY + m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; + + + //x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + //y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x[0] = screenTargetX; x[1] = screenTargetX; y[0] = screenTargetY + m_iCrosshairCrosslineLength; y[1] = screenTargetY - m_iCrosshairCrosslineLength; + + //x = {screenTargetX, screenTargetX}; + //y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x[0] = screenTargetX + m_iCrosshairCrosslineLength; x[1] = screenTargetX - m_iCrosshairCrosslineLength; y[0] = screenTargetY; y[1] = screenTargetY; + + + //x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; + //y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(GetUntypedTarget(), 400, 20, 200, m_iCrosshairColor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); /* return ((m_iCurrentStringPos == -1) ? m_sTargetString.substr(m_iCurrentStringPos + 1) : m_sTargetString.substr(m_iCurrentStringPos + 1)); */ } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } }
rgee/HFOSS-Dasher
ab6ba665326542b614d0f7a31c860508b0fbcb07
Created proper destructor. Now we actually get rid of dangling pointers. :P
diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 918daef..32ad8fc 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,208 +1,211 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) g_pLogger->Log("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") m_sTargetString = "My name is julian."; m_iCurrentStringPos = -1; } - virtual ~CGameModule() {}; + virtual ~CGameModule() { + delete m_pWordGenerator; + delete m_pInterface; + }; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
e3db9f8d2464fd4f279df8380bce12691773b53f
Got rid of unused member variables.
diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 62fdc69..918daef 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,218 +1,208 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) g_pLogger->Log("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") m_sTargetString = "My name is julian."; m_iCurrentStringPos = -1; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; - /** - * The last node the user typed. - */ - CDasherNode *pLastTypedNode; - - /** - * The next node (character) the user must type. - */ - CDasherNode *pNextTargetNode; - /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
f7ce8b792a655f6ed011cbd89c891eae2a14b422
Finished converting the event handler to a queue based implementation. Haven't tested rigorously, but compiles and runs without errors.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index adbdb25..a589834 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,116 +1,118 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif #include <sstream> void CEventHandler::InsertEvent(CEvent *pEvent) { - ++m_iInHandler; - - for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType - 1].begin(); - it != m_vSpecificListeners[pEvent->m_iEventType - 1].end(); - ++it) - { - (*it)->HandleEvent(pEvent); - } - - m_pInterface->InterfaceEventHandler(pEvent); + //put the event at the end of the queue + EnqueueEvent(pEvent); - m_pInterface->ExternalEventHandler(pEvent); + //if we are already dispatching events, don't do it again + //this is necessary to keep recursive calls from removing + //events from the queue while we iterate over it + if(m_bIsDispatching) + return; + + //iterate over the event queue until it's empty + while(!m_qEventQueue.empty()) { - --m_iInHandler; + CEvent *currEvent = m_qEventQueue.front(); + m_qEventQueue.pop(); + + m_pInterface->InterfaceEventHandler(currEvent); + + m_pInterface->ExternalEventHandler(currEvent); + + //entering the dispatching loop - no longer safe to modify m_vSpecificListeners + m_bIsDispatching = true; + + //dispatch the event at the front of the queue to all registered listeners + for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[currEvent->m_iEventType - 1].begin(); + it != m_vSpecificListeners[currEvent->m_iEventType - 1].end(); + ++it) + { + (*it)->HandleEvent(currEvent); + } + + //done dispatching this event - safe to modify m_vSpecificListeners + m_bIsDispatching = false; + + //register all listeners that have been waiting to be added + for(EvtListenerCollection::iterator it = m_vPendingSpecificReg.begin(); it != m_vPendingSpecificReg.end(); ++it) + RegisterListener((*it).first, (*it).second); + + //unregister all that have been waiting to be removed + for(EvtListenerCollection::iterator it = m_vPendingSpecificUnreg.begin(); it != m_vPendingSpecificUnreg.end(); ++it) + UnregisterListener((*it).first, (*it).second); + } +} - if(m_iInHandler == 0) { - - //loop through the queue of specific listeners waiting to be registered and register them - for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - RegisterListener((*it).first, (*it).second); - } - } +void CEventHandler::EnqueueEvent(CEvent *pEvent) { + m_qEventQueue.push(pEvent); } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - // If the listener is in the queue waiting to be added, don't add it again - if((std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener) != m_vGeneralListenerQueue.end())) { - return; - } - else { - // For each event listener list, either add it or queue it... - for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - //...but only if it doesn't already exist - if((std::find((*it).begin(), (*it).end(), pListener) == (*it).end())) { - - if(m_iInHandler == 0) { - (*it).push_back(pListener); - } - else { - m_vGeneralListenerQueue.push_back(pListener); - } - } - else { - // Can't add the same listener twice - } - } - } + + for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { + RegisterListener(pListener, curEvtType); + } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { + // Only try to add a new listener if it doesn't already exist in the Listener map if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { - if(m_iInHandler == 0) + + if(!m_bIsDispatching) { m_vSpecificListeners[iEventType - 1].push_back(pListener); - else - // Add the listener to the queue if events are being processed - m_vSpecificListenerQueue.push_back(std::make_pair(pListener, iEventType)); + } + else { + // Add the listener to the pending set if events are being dispatched + m_vPendingSpecificReg.push_back(std::make_pair(pListener, iEventType)); + } } else { // Can't add the same listener twice } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { - for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { - if( (*it) == pListener) - m_vSpecificListeners[iEventType].erase(it); + + if(!m_bIsDispatching) { + + for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType - 1].begin(); it != m_vSpecificListeners[iEventType - 1].end(); ++it) { + if((*it) == pListener) + m_vSpecificListeners[iEventType - 1].erase(it); + break; + } } -} - -void CEventHandler::UnregisterListener(CDasherComponent *pListener) { - - std::vector < CDasherComponent * >::iterator mapFound; - - for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - mapFound = std::find((*it).begin(), (*it).end(), pListener); - if(mapFound != (*it).end()) - (*it).erase(mapFound); + else { + m_vPendingSpecificUnreg.push_back(std::make_pair(pListener, iEventType)); } +} - std::vector < CDasherComponent * >::iterator queueFound = std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener); - if(queueFound != m_vGeneralListenerQueue.end()) - m_vGeneralListenerQueue.erase(queueFound); - - for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - if((*it).first == pListener) { - it = m_vSpecificListenerQueue.erase(it); - } - } - +void CEventHandler::UnregisterListener(CDasherComponent *pListener) { + + for(int curEvtType = 1; curEvtType <= m_iNUM_EVENTS; curEvtType++) { + UnregisterListener(pListener, curEvtType); + } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 0bbeda1..4b07282 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,131 +1,147 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> +#include <queue> #include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { + public: /** - * @var typedef vector<vector<CDasherComponent*>> ListenerMap + * @var typedef vector<vector<CDasherComponent*>> EvtListenerTable * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ - typedef std::vector<std::vector<CDasherComponent*> > ListenerMap; + typedef std::vector<std::vector<Dasher::CDasherComponent*> > EvtListenerTable; /** - * @var typedef vector<pair<CDasherComponent*, int> > ListenerQueue - * @brief A queue whose elements represent 1 to 1 associations between + * @var typedef vector<pair<CDasherComponent*, int> > EvtListenerCollection + * @brief A collection whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ - typedef std::vector<std::pair<CDasherComponent*, int> > ListenerQueue; + typedef std::vector<std::pair<Dasher::CDasherComponent*, int> > EvtListenerCollection; - CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { - m_iInHandler = 0; + m_bIsDispatching = false; + // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < m_iNUM_EVENTS; i++) { - m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); + m_vSpecificListeners.push_back(std::vector<Dasher::CDasherComponent*>()); } }; ~CEventHandler() { }; - // Insert an event, which will be propagated to all listeners. - + + /** + * TODO - when we refactor, rename this to DispatchEvent + * Insert an event into the queue, then flush the queue + * such that all event listeners are notified of the + * events they subscribed to. + */ void InsertEvent(Dasher::CEvent * pEvent); + /** + * Add an event to the event queue. + * @param pEvent the event to add to the queue + */ + void EnqueueEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); -protected: +private: + + /** + * The queue of events waiting to be dispatched. + */ + std::queue<Dasher::CEvent*> m_qEventQueue; /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration - * in Event.h. To access a vector for a specific event type, index into the top-level + * in Event.h). To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ - ListenerMap m_vSpecificListeners; + EvtListenerTable m_vSpecificListeners; /** - * The queue of listeners waiting to be registered with specific - * events while InsertEvent is still processing. Used to prevent - * m_vSpecificListeners from being modified while InsertEvent is - * iterating over it. + * The set of specific listeners waiting to be registered + * while m_vSpecificListeners is being iterated over. */ - ListenerQueue m_vSpecificListenerQueue; - + EvtListenerCollection m_vPendingSpecificReg; + /** - * The queue of "old style" listeners waiting to be registered - * with all events while InsertEvent is still processing. Used - * to prevent m_vSpecificListeners from being modified while - * InsertEvent is iterating over it. - */ - std::vector<CDasherComponent*> m_vGeneralListenerQueue; + * The set of specific listeners waiting to be unregistered + * while m_vSpecificListeners is being iterated over. + */ + EvtListenerCollection m_vPendingSpecificUnreg; - int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; - -private: + /** + * Boolean flag - true if we are in the middle of flushing + * the event queue, false if not. Used to determine whether it + * is safe to modify m_vSpecificListeners + */ + bool m_bIsDispatching; /** * @var m_iNUM_EVENTS * @brief The number of event types in the enumeration of Dasher events in Event.h. Had * to put it here to stop the compiler from complaining about multiple definitions. Please * keep this up to date with the number of items in the enumeration. * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy */ const int m_iNUM_EVENTS; }; /// @} #endif
rgee/HFOSS-Dasher
d77803de743c5779743a058725508012dfb4fbe8
Reformatted crosshair coord. array section
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index e723542..20cfe93 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,178 +1,157 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); /* return( (m_iCurrentStringPos == 0) ? !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); */ } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); /* return( (m_iCurrentStringPos == 0) ? !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); */ } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); screenint x[2]; screenint y[2]; // Top Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY - m_iCrosshairExtent; - - //screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - //screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x[0] = screenTargetX - m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; - - //x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX + m_iCrosshairExtent; y[0] = screenTargetY - m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; - - - //x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; - //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x[0] = screenTargetX + m_iCrosshairExtent; x[1] = screenTargetX - m_iCrosshairExtent; y[0] = screenTargetY + m_iCrosshairExtent; y[1] = screenTargetY + m_iCrosshairExtent; - - - //x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - //y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x[0] = screenTargetX; x[1] = screenTargetX; y[0] = screenTargetY + m_iCrosshairCrosslineLength; y[1] = screenTargetY - m_iCrosshairCrosslineLength; - - //x = {screenTargetX, screenTargetX}; - //y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x[0] = screenTargetX + m_iCrosshairCrosslineLength; x[1] = screenTargetX - m_iCrosshairCrosslineLength; y[0] = screenTargetY; y[1] = screenTargetY; - - - //x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; - //y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); pView->DrawText(GetUntypedTarget(), 400, 20, 200, m_iCrosshairColor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return ((m_iCurrentStringPos == -1) ? "" : m_sTargetString.substr(0, m_iCurrentStringPos)); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_iCurrentStringPos + 1); /* return ((m_iCurrentStringPos == -1) ? m_sTargetString.substr(m_iCurrentStringPos + 1) : m_sTargetString.substr(m_iCurrentStringPos + 1)); */ } void CGameModule::GenerateChunk() { m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } }
rgee/HFOSS-Dasher
82c615a41ed7c6bcebc377cf024ac5998421e8b4
Fixed issue with drawing the incorrect target string. Made crosshair coordinate arrays not use C++0x-only syntax.
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index e5c96eb..e723542 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,138 +1,178 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk - if((m_stCurrentStringPos) == m_sTargetString.length() - 2) { + if((m_iCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { - ++m_stCurrentStringPos; + ++m_iCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { - return( (m_stCurrentStringPos == 0) ? - !pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1)) : - !pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); + return !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); + /* + return( (m_iCurrentStringPos == 0) ? + !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : + !pEvent->m_sText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); + */ } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { - return( (m_stCurrentStringPos == 0) ? - !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1)) : - !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); + return !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1)); + /* + return( (m_iCurrentStringPos == 0) ? + !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos, 1)) : + !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_iCurrentStringPos + 1, 1))); + */ } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); + screenint x[2]; + screenint y[2]; // Top Line - screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; + x[0] = screenTargetX + m_iCrosshairExtent; + x[1] = screenTargetX - m_iCrosshairExtent; + y[0] = screenTargetY - m_iCrosshairExtent; + y[1] = screenTargetY - m_iCrosshairExtent; + + //screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + //screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line - x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; + x[0] = screenTargetX - m_iCrosshairExtent; + x[1] = screenTargetX - m_iCrosshairExtent; + y[0] = screenTargetY - m_iCrosshairExtent; + y[1] = screenTargetY + m_iCrosshairExtent; + + //x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line - x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; - y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; + x[0] = screenTargetX + m_iCrosshairExtent; + x[1] = screenTargetX + m_iCrosshairExtent; + y[0] = screenTargetY - m_iCrosshairExtent; + y[1] = screenTargetY + m_iCrosshairExtent; + + + //x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; + //y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line - x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; - y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; + x[0] = screenTargetX + m_iCrosshairExtent; + x[1] = screenTargetX - m_iCrosshairExtent; + y[0] = screenTargetY + m_iCrosshairExtent; + y[1] = screenTargetY + m_iCrosshairExtent; + + + //x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + //y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line - x = {screenTargetX, screenTargetX}; - y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; + x[0] = screenTargetX; + x[1] = screenTargetX; + y[0] = screenTargetY + m_iCrosshairCrosslineLength; + y[1] = screenTargetY - m_iCrosshairCrosslineLength; + + //x = {screenTargetX, screenTargetX}; + //y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line - x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; - y = {screenTargetY, screenTargetY}; - pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + x[0] = screenTargetX + m_iCrosshairCrosslineLength; + x[1] = screenTargetX - m_iCrosshairCrosslineLength; + y[0] = screenTargetY; + y[1] = screenTargetY; + //x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; + //y = {screenTargetY, screenTargetY}; + pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); - // Draw the target strings. One color for the completed portion - // and another for the uncompleted portion. - //pView->DrawText(GetTypedTarget(), 20, 20, 200, m_iCrosshairColor); pView->DrawText(GetUntypedTarget(), 400, 20, 200, m_iCrosshairColor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { - return ((m_stCurrentStringPos == 0) ? - "" : m_sTargetString.substr(0, m_stCurrentStringPos - 1)); + return ((m_iCurrentStringPos == -1) ? + "" : m_sTargetString.substr(0, m_iCurrentStringPos)); } std::string CGameModule::GetUntypedTarget() { - return ((m_stCurrentStringPos == 0) ? - m_sTargetString.substr(m_stCurrentStringPos) : - m_sTargetString.substr(m_stCurrentStringPos + 1)); + return m_sTargetString.substr(m_iCurrentStringPos + 1); + /* + return ((m_iCurrentStringPos == -1) ? + m_sTargetString.substr(m_iCurrentStringPos + 1) : + m_sTargetString.substr(m_iCurrentStringPos + 1)); + */ } void CGameModule::GenerateChunk() { - m_stCurrentStringPos = 0; + m_iCurrentStringPos = -1; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 85c9650..62fdc69 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,218 +1,218 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_iFontSize(36), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) g_pLogger->Log("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") m_sTargetString = "My name is julian."; - m_stCurrentStringPos = 0; + m_iCurrentStringPos = -1; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ - size_t m_stCurrentStringPos; + int m_iCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; /** * The font size used to draw the target string. */ const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
921af652d7a8b6a0f1b272f12a6da576f4bd8269
Game Mode now draws the target string to the screen. I know the text is huge. Font size or any other display design things have not been decided whatsoever.
diff --git a/Src/DasherCore/DasherView.cpp b/Src/DasherCore/DasherView.cpp index 5d6eeda..219a580 100644 --- a/Src/DasherCore/DasherView.cpp +++ b/Src/DasherCore/DasherView.cpp @@ -1,322 +1,322 @@ // DasherView.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherGameMode.h" #include "DasherInput.h" #include "DasherModel.h" #include "DasherView.h" #include "Event.h" #include "EventHandler.h" #include "DasherScreen.h" using namespace Dasher; using std::vector; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif ///////////////////////////////////////////////////////////////////////////// CDasherView::CDasherView(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) :CDasherComponent(pEventHandler, pSettingsStore), m_pScreen(DasherScreen), m_pInput(0), m_bDemoMode(false), m_bGameMode(false) { } ///////////////////////////////////////////////////////////////////////////// void CDasherView::ChangeScreen(CDasherScreen *NewScreen) { m_pScreen = NewScreen; } ///////////////////////////////////////////////////////////////////////////// void CDasherView::Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay) { m_iRenderCount = 0; Screen()->SetLoadBackground(false); RenderNodes(pRoot, iRootMin, iRootMax, policy); } int CDasherView::GetCoordinateCount() { // TODO: Do we really need support for co-ordinate counts other than 2? if(m_pInput) return m_pInput->GetCoordinateCount(); else return 0; } int CDasherView::GetInputCoordinates(int iN, myint * pCoordinates) { if(m_pInput) return m_pInput->GetCoordinates(iN, pCoordinates); else return 0; } void CDasherView::SetInput(CDasherInput * _pInput) { // TODO: Is it sensible to make this responsible for the input // device - I guess it makes sense for now DASHER_ASSERT_VALIDPTR_RW(_pInput); // Don't delete the old input class; whoever is calling this method // might want to keep several Input class instances around and // change which one is currently driving dasher without deleting any m_pInput = _pInput; // Tell the new object about maximum values myint iMaxCoordinates[2]; iMaxCoordinates[0] = GetLongParameter(LP_MAX_Y); iMaxCoordinates[1] = GetLongParameter(LP_MAX_Y); m_pInput->SetMaxCoordinates(2, iMaxCoordinates); } void CDasherView::Display() { Screen()->SetLoadBackground(true); m_pScreen->Display(); } void CDasherView::DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColor) { if (!ClipLineToVisible(x1, y1, x2, y2)) return; vector<CDasherScreen::point> vPoints; CDasherScreen::point p; Dasher2Screen(x1, y1, p.x, p.y); vPoints.push_back(p); DasherLine2Screen(x1,y1,x2,y2,vPoints); CDasherScreen::point *pts = new CDasherScreen::point[vPoints.size()]; for (int i = vPoints.size(); i-->0; ) pts[i] = vPoints[i]; Screen()->Polyline(pts, vPoints.size(), iWidth, iColor); } bool CDasherView::ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2) { if (x1 > x2) return ClipLineToVisible(x2,y2,x1,y1); //ok. have x1 <= x2... myint iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (x1 > iDasherMaxX) { DASHER_ASSERT(x2>iDasherMaxX); return false; //entirely offscreen! } if (x2 < iDasherMinX) { DASHER_ASSERT(x1<iDasherMinX); return false; } if (y1 < iDasherMinY && y2 < iDasherMinY) return false; if (y1 > iDasherMaxY && y2 > iDasherMaxY) return false; if (x1 < iDasherMinX) { y1 = y2+((y1-y2)*(iDasherMinX-x2)/(x1 - x2)); x1 = iDasherMinX; } if (x2 > iDasherMaxX) { y2 = y1 + (y2-y1)*(iDasherMaxX-x1)/(x2-x1); x2 = iDasherMaxX; } for (int i=0; i<2; i++) { myint &y(i ? y2 : y1), &oy(i ? y1 : y2); myint &x(i ? x2 : x1), &ox(i ? x1 : x2); if (y<iDasherMinY) { x = ox- (ox-x)*(oy-iDasherMinY)/(oy-y); y = iDasherMinY; } else if (y>iDasherMaxY) { x = ox-(ox-x)*(oy-iDasherMaxY)/(oy-y); y = iDasherMaxY; } } return true; } /// Draw a polyline specified in Dasher co-ordinates void CDasherView::DasherPolyline(myint *x, myint *y, int n, int iWidth, int iColour) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); if(iColour != -1) { Screen()->Polyline(ScreenPoints, n, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n, iWidth,0);//no color given } delete[]ScreenPoints; } void CDasherView::ScreenPolyline(screenint *x, screenint *y, int n, int iWidth, int iColour) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; for(int i(0); i < n; ++i) { ScreenPoints[i].x = x[i]; ScreenPoints[i].y = y[i]; } if(iColour != -1) { Screen()->Polyline(ScreenPoints, n, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n, iWidth, 0); } delete[] ScreenPoints; } // Draw a polyline with an arrow on the end void CDasherView::DasherPolyarrow(myint *x, myint *y, int n, int iWidth, int iColour, double dArrowSizeFactor) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n+3]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); int iXvec = (int)((ScreenPoints[n-2].x - ScreenPoints[n-1].x)*dArrowSizeFactor); int iYvec = (int)((ScreenPoints[n-2].y - ScreenPoints[n-1].y)*dArrowSizeFactor); ScreenPoints[n].x = ScreenPoints[n-1].x + iXvec + iYvec; ScreenPoints[n].y = ScreenPoints[n-1].y - iXvec + iYvec; ScreenPoints[n+1].x = ScreenPoints[n-1].x ; ScreenPoints[n+1].y = ScreenPoints[n-1].y ; ScreenPoints[n+2].x = ScreenPoints[n-1].x + iXvec - iYvec; ScreenPoints[n+2].y = ScreenPoints[n-1].y + iXvec + iYvec; if(iColour != -1) { Screen()->Polyline(ScreenPoints, n+3, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n+3, iWidth,0);//no color given } delete[]ScreenPoints; } // Draw a box specified in Dasher co-ordinates void CDasherView::DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness) { screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iLeft, iTop, iScreenLeft, iScreenTop); Dasher2Screen(iRight, iBottom, iScreenRight, iScreenBottom); Screen()->DrawRectangle(iScreenLeft, iScreenTop, iScreenRight, iScreenBottom, Color, iOutlineColour, ColorScheme, iThickness); } /// Draw a rectangle centred on a given dasher co-ordinate, but with a size specified in screen co-ordinates (used for drawing the mouse blob) void CDasherView::DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline) { screenint iScreenX; screenint iScreenY; Dasher2Screen(iDasherX, iDasherY, iScreenX, iScreenY); Screen()->DrawRectangle(iScreenX - iSize, iScreenY - iSize, iScreenX + iSize, iScreenY + iSize, Color, -1, ColorScheme, bDrawOutline ? 1 : 0); } -void DrawText(const std::string & str, screenint x, screenint y, int iSize, int iColor) { +void CDasherView::DrawText(const std::string & str, screenint x, screenint y, int iSize, int iColor) { Screen()->DrawString(str, x, y, iSize, iColor); } void CDasherView::DrawText(const std::string & str, myint x, myint y, int Size, int iColor) { screenint X, Y; Dasher2Screen(x, y, X, Y); Screen()->DrawString(str, X, Y, Size, iColor); } int CDasherView::GetCoordinates(myint &iDasherX, myint &iDasherY) { // FIXME - Actually turn autocalibration on and off! // FIXME - AutoCalibrate should use Dasher co-ordinates, not raw mouse co-ordinates? // FIXME - Have I broken this by moving it before the offset is applied? // FIXME - put ymap stuff back in // FIXME - optimise this int iCoordinateCount(GetCoordinateCount()); myint *pCoordinates(new myint[iCoordinateCount]); int iType(GetInputCoordinates(iCoordinateCount, pCoordinates)); screenint mousex; screenint mousey; if(iCoordinateCount == 1) { mousex = 0; mousey = pCoordinates[0]; } else { mousex = pCoordinates[0]; mousey = pCoordinates[1]; } delete[]pCoordinates; switch(iType) { case 0: Screen2Dasher(mousex, mousey, iDasherX, iDasherY); break; case 1: iDasherX = mousex; iDasherY = mousey; break; default: // TODO: Error break; } ///GAME/// if(m_bGameMode) { using GameMode::CDasherGameMode; if(m_bDemoMode) CDasherGameMode::GetTeacher()->DemoModeGetCoordinates(iDasherX, iDasherY); CDasherGameMode::GetTeacher()->SetUserMouseCoordinates(iDasherX, iDasherY); } return iType; } void CDasherView::SetDemoMode(bool bDemoMode) { m_bDemoMode = bDemoMode; } void CDasherView::SetGameMode(bool bGameMode) { m_bGameMode = bGameMode; } diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 81a5bc9..e5c96eb 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,131 +1,138 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(CharacterFound(evt)) { // Check if we've reached the end of a chunk if((m_stCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_stCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::CharacterFound(CEditEvent* pEvent) { - if(m_stCurrentStringPos == 0) { - return (!pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1))); - } else { - return (!pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); - } + return( (m_stCurrentStringPos == 0) ? + !pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1)) : + !pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); } bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { - if(m_stCurrentStringPos == 0) { - return (!pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1))); - } else { - return (!pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); - } + return( (m_stCurrentStringPos == 0) ? + !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1)) : + !pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); // Top Line screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x = {screenTargetX, screenTargetX}; y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + + + + // Draw the target strings. One color for the completed portion + // and another for the uncompleted portion. + //pView->DrawText(GetTypedTarget(), 20, 20, 200, m_iCrosshairColor); + pView->DrawText(GetUntypedTarget(), 400, 20, 200, m_iCrosshairColor); + return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { - return m_sTargetString.substr(0, m_stCurrentStringPos - 1); + return ((m_stCurrentStringPos == 0) ? + "" : m_sTargetString.substr(0, m_stCurrentStringPos - 1)); } std::string CGameModule::GetUntypedTarget() { - return m_sTargetString.substr(m_stCurrentStringPos); + return ((m_stCurrentStringPos == 0) ? + m_sTargetString.substr(m_stCurrentStringPos) : + m_sTargetString.substr(m_stCurrentStringPos + 1)); } void CGameModule::GenerateChunk() { m_stCurrentStringPos = 0; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index c4caca1..85c9650 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,212 +1,218 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), + m_iFontSize(36), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) g_pLogger->Log("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") m_sTargetString = "My name is julian."; m_stCurrentStringPos = 0; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Checks whether the character associated with the given event * is the character we're currently targetting. A convenience method * that encapsulates + localizes some of the string manipulation logic. * * @param pEvent An edit event. * @return True if the character associated with the given event * is equal to the character we're looking for. False otherwise. */ bool CharacterFound(CEditEvent* pEvent); /** * @see CharacterFound */ bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** - * The length of the lines comprising the crosshair's + * The length of the lines comprising the crosshair's. * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; + + /** + * The font size used to draw the target string. + */ + const int m_iFontSize; }; } #endif
rgee/HFOSS-Dasher
2cceb46f62fb1223d8e674a876967a36dce7aef9
Wrote screen-space text draw function.
diff --git a/Src/DasherCore/DasherView.cpp b/Src/DasherCore/DasherView.cpp index 3701eac..5d6eeda 100644 --- a/Src/DasherCore/DasherView.cpp +++ b/Src/DasherCore/DasherView.cpp @@ -1,317 +1,322 @@ // DasherView.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherGameMode.h" #include "DasherInput.h" #include "DasherModel.h" #include "DasherView.h" #include "Event.h" #include "EventHandler.h" #include "DasherScreen.h" using namespace Dasher; using std::vector; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif ///////////////////////////////////////////////////////////////////////////// CDasherView::CDasherView(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) :CDasherComponent(pEventHandler, pSettingsStore), m_pScreen(DasherScreen), m_pInput(0), m_bDemoMode(false), m_bGameMode(false) { } ///////////////////////////////////////////////////////////////////////////// void CDasherView::ChangeScreen(CDasherScreen *NewScreen) { m_pScreen = NewScreen; } ///////////////////////////////////////////////////////////////////////////// void CDasherView::Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay) { m_iRenderCount = 0; Screen()->SetLoadBackground(false); RenderNodes(pRoot, iRootMin, iRootMax, policy); } int CDasherView::GetCoordinateCount() { // TODO: Do we really need support for co-ordinate counts other than 2? if(m_pInput) return m_pInput->GetCoordinateCount(); else return 0; } int CDasherView::GetInputCoordinates(int iN, myint * pCoordinates) { if(m_pInput) return m_pInput->GetCoordinates(iN, pCoordinates); else return 0; } void CDasherView::SetInput(CDasherInput * _pInput) { // TODO: Is it sensible to make this responsible for the input // device - I guess it makes sense for now DASHER_ASSERT_VALIDPTR_RW(_pInput); // Don't delete the old input class; whoever is calling this method // might want to keep several Input class instances around and // change which one is currently driving dasher without deleting any m_pInput = _pInput; // Tell the new object about maximum values myint iMaxCoordinates[2]; iMaxCoordinates[0] = GetLongParameter(LP_MAX_Y); iMaxCoordinates[1] = GetLongParameter(LP_MAX_Y); m_pInput->SetMaxCoordinates(2, iMaxCoordinates); } void CDasherView::Display() { Screen()->SetLoadBackground(true); m_pScreen->Display(); } void CDasherView::DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColor) { if (!ClipLineToVisible(x1, y1, x2, y2)) return; vector<CDasherScreen::point> vPoints; CDasherScreen::point p; Dasher2Screen(x1, y1, p.x, p.y); vPoints.push_back(p); DasherLine2Screen(x1,y1,x2,y2,vPoints); CDasherScreen::point *pts = new CDasherScreen::point[vPoints.size()]; for (int i = vPoints.size(); i-->0; ) pts[i] = vPoints[i]; Screen()->Polyline(pts, vPoints.size(), iWidth, iColor); } bool CDasherView::ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2) { if (x1 > x2) return ClipLineToVisible(x2,y2,x1,y1); //ok. have x1 <= x2... myint iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (x1 > iDasherMaxX) { DASHER_ASSERT(x2>iDasherMaxX); return false; //entirely offscreen! } if (x2 < iDasherMinX) { DASHER_ASSERT(x1<iDasherMinX); return false; } if (y1 < iDasherMinY && y2 < iDasherMinY) return false; if (y1 > iDasherMaxY && y2 > iDasherMaxY) return false; if (x1 < iDasherMinX) { y1 = y2+((y1-y2)*(iDasherMinX-x2)/(x1 - x2)); x1 = iDasherMinX; } if (x2 > iDasherMaxX) { y2 = y1 + (y2-y1)*(iDasherMaxX-x1)/(x2-x1); x2 = iDasherMaxX; } for (int i=0; i<2; i++) { myint &y(i ? y2 : y1), &oy(i ? y1 : y2); myint &x(i ? x2 : x1), &ox(i ? x1 : x2); if (y<iDasherMinY) { x = ox- (ox-x)*(oy-iDasherMinY)/(oy-y); y = iDasherMinY; } else if (y>iDasherMaxY) { x = ox-(ox-x)*(oy-iDasherMaxY)/(oy-y); y = iDasherMaxY; } } return true; } /// Draw a polyline specified in Dasher co-ordinates void CDasherView::DasherPolyline(myint *x, myint *y, int n, int iWidth, int iColour) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); if(iColour != -1) { Screen()->Polyline(ScreenPoints, n, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n, iWidth,0);//no color given } delete[]ScreenPoints; } void CDasherView::ScreenPolyline(screenint *x, screenint *y, int n, int iWidth, int iColour) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; for(int i(0); i < n; ++i) { ScreenPoints[i].x = x[i]; ScreenPoints[i].y = y[i]; } if(iColour != -1) { Screen()->Polyline(ScreenPoints, n, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n, iWidth, 0); } delete[] ScreenPoints; } // Draw a polyline with an arrow on the end void CDasherView::DasherPolyarrow(myint *x, myint *y, int n, int iWidth, int iColour, double dArrowSizeFactor) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n+3]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); int iXvec = (int)((ScreenPoints[n-2].x - ScreenPoints[n-1].x)*dArrowSizeFactor); int iYvec = (int)((ScreenPoints[n-2].y - ScreenPoints[n-1].y)*dArrowSizeFactor); ScreenPoints[n].x = ScreenPoints[n-1].x + iXvec + iYvec; ScreenPoints[n].y = ScreenPoints[n-1].y - iXvec + iYvec; ScreenPoints[n+1].x = ScreenPoints[n-1].x ; ScreenPoints[n+1].y = ScreenPoints[n-1].y ; ScreenPoints[n+2].x = ScreenPoints[n-1].x + iXvec - iYvec; ScreenPoints[n+2].y = ScreenPoints[n-1].y + iXvec + iYvec; if(iColour != -1) { Screen()->Polyline(ScreenPoints, n+3, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n+3, iWidth,0);//no color given } delete[]ScreenPoints; } // Draw a box specified in Dasher co-ordinates void CDasherView::DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness) { screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iLeft, iTop, iScreenLeft, iScreenTop); Dasher2Screen(iRight, iBottom, iScreenRight, iScreenBottom); Screen()->DrawRectangle(iScreenLeft, iScreenTop, iScreenRight, iScreenBottom, Color, iOutlineColour, ColorScheme, iThickness); } /// Draw a rectangle centred on a given dasher co-ordinate, but with a size specified in screen co-ordinates (used for drawing the mouse blob) void CDasherView::DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline) { screenint iScreenX; screenint iScreenY; Dasher2Screen(iDasherX, iDasherY, iScreenX, iScreenY); Screen()->DrawRectangle(iScreenX - iSize, iScreenY - iSize, iScreenX + iSize, iScreenY + iSize, Color, -1, ColorScheme, bDrawOutline ? 1 : 0); } + +void DrawText(const std::string & str, screenint x, screenint y, int iSize, int iColor) { + Screen()->DrawString(str, x, y, iSize, iColor); +} + void CDasherView::DrawText(const std::string & str, myint x, myint y, int Size, int iColor) { screenint X, Y; Dasher2Screen(x, y, X, Y); Screen()->DrawString(str, X, Y, Size, iColor); } int CDasherView::GetCoordinates(myint &iDasherX, myint &iDasherY) { // FIXME - Actually turn autocalibration on and off! // FIXME - AutoCalibrate should use Dasher co-ordinates, not raw mouse co-ordinates? // FIXME - Have I broken this by moving it before the offset is applied? // FIXME - put ymap stuff back in // FIXME - optimise this int iCoordinateCount(GetCoordinateCount()); myint *pCoordinates(new myint[iCoordinateCount]); int iType(GetInputCoordinates(iCoordinateCount, pCoordinates)); screenint mousex; screenint mousey; if(iCoordinateCount == 1) { mousex = 0; mousey = pCoordinates[0]; } else { mousex = pCoordinates[0]; mousey = pCoordinates[1]; } delete[]pCoordinates; switch(iType) { case 0: Screen2Dasher(mousex, mousey, iDasherX, iDasherY); break; case 1: iDasherX = mousex; iDasherY = mousey; break; default: // TODO: Error break; } ///GAME/// if(m_bGameMode) { using GameMode::CDasherGameMode; if(m_bDemoMode) CDasherGameMode::GetTeacher()->DemoModeGetCoordinates(iDasherX, iDasherY); CDasherGameMode::GetTeacher()->SetUserMouseCoordinates(iDasherX, iDasherY); } return iType; } void CDasherView::SetDemoMode(bool bDemoMode) { m_bDemoMode = bDemoMode; } void CDasherView::SetGameMode(bool bGameMode) { m_bGameMode = bGameMode; } diff --git a/Src/DasherCore/DasherView.h b/Src/DasherCore/DasherView.h index d9ae545..3d3b47a 100644 --- a/Src/DasherCore/DasherView.h +++ b/Src/DasherCore/DasherView.h @@ -1,235 +1,248 @@ // DasherView.h // // Copyright (c) 2001-2005 David Ward #ifndef __DasherView_h_ #define __DasherView_h_ namespace Dasher { class CDasherModel; class CDasherInput; // Why does DasherView care about input? - pconlon class CDasherComponent; class CDasherView; class CDasherNode; } #include "DasherTypes.h" #include "DasherComponent.h" #include "ExpansionPolicy.h" #include "DasherScreen.h" /// \defgroup View Visualisation of the model /// @{ /// \brief View base class. /// /// Dasher views represent the visualisation of a Dasher model on the screen. /// /// Note that we really should aim to avoid having to try and keep /// multiple pointers to the same object (model etc.) up-to-date at /// once. We should be able to avoid the need for this just by being /// sane about passing pointers as arguments to the relevant /// functions, for example we could pass a pointer to the canvas every /// time we call the render routine, rather than worrying about /// notifying this object every time it changes. The same logic can be /// applied in several other places. /// /// We should also attempt to try and remove the need for this class /// to know about the model. When we call render we should just pass a /// pointer to the root node, which we can obtain elsewhere, and make /// sure that the data structure contains all the info we need to do /// the rendering (eg make sure it contains strings as well as symbol /// IDs). /// /// There are really three roles played by CDasherView: providing high /// level drawing functions, providing a mapping between Dasher /// co-ordinates and screen co-ordinates and providing a mapping /// between true and effective Dasher co-ordinates (eg for eyetracking /// mode). We should probably consider creating separate classes for /// these. class Dasher::CDasherView : public Dasher::CDasherComponent { public: /// Constructor /// /// \param pEventHandler Pointer to the event handler /// \param pSettingsStore Pointer to the settings store /// \param DasherScreen Pointer to the CDasherScreen object used to do rendering CDasherView(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CDasherScreen * DasherScreen); virtual ~CDasherView() { } /// @name Pointing device mappings /// @{ /// Set the input device class. Note that this class will now assume ownership of the pointer, ie it will delete the object when it's done with it. /// \param _pInput Pointer to the new CDasherInput. void SetInput(CDasherInput * _pInput); void SetDemoMode(bool); void SetGameMode(bool); /// Translates the screen coordinates to Dasher coordinates and calls /// dashermodel.TapOnDisplay virtual int GetCoordinates(myint &iDasherX, myint &iDasherY); /// Get the co-ordinate count from the input device int GetCoordinateCount(); /// @} /// /// @name Coordinate system conversion /// Convert between screen and Dasher coordinates /// @{ /// /// Convert a screen co-ordinate to Dasher co-ordinates /// virtual void Screen2Dasher(screenint iInputX, screenint iInputY, myint & iDasherX, myint & iDasherY) = 0; /// /// Convert Dasher co-ordinates to screen co-ordinates /// virtual void Dasher2Screen(myint iDasherX, myint iDasherY, screenint & iScreenX, screenint & iScreenY) = 0; /// /// Convert Dasher co-ordinates to polar co-ordinates (r,theta), with 0<r<1, 0<theta<2*pi /// virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) = 0; virtual bool IsSpaceAroundNode(myint y1, myint y2)=0; virtual void VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) = 0; /// @} /// Change the screen - must be called if the Screen is replaced or resized /// \param NewScreen Pointer to the new CDasherScreen. virtual void ChangeScreen(CDasherScreen * NewScreen); /// @name High level drawing /// Drawing more complex structures, generally implemented by derived class /// @{ /// Renders Dasher with mouse-dependent items /// \todo Clarify relationship between Render functions and probably only expose one virtual void Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay); /// @} ////// Return a reference to the screen - can't be protected due to circlestarthandler CDasherScreen *Screen() { return m_pScreen; } /// /// @name Low level drawing /// Basic drawing primitives specified in Dasher coordinates. /// @{ ///Draw a straight line in Dasher-space - which may be curved on the screen... void DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColour); /// /// Draw a polyline specified in Dasher co-ordinates /// void DasherPolyline(myint * x, myint * y, int n, int iWidth, int iColour); /** * Draw a line in screen coordinates. Needed for drawing without respect to * the strange squishing and resizing that can happen when drawing in Dasher * coordinates. * * @see DasherPolyline */ void ScreenPolyline(screenint * x, screenint * y, int n, int iWidth, int iColour); /** * Draw an arrow in Dasher space. The parameters x and y allow the client to specify * points through which the arrow's main line should be drawn. For example, to draw an * arrow through the Dasher coordinates (1000, 2000) and (3000, 4000), one would pass in: * * myint x[2] = {1000, 3000}; * myint y[2] = {2000, 4000}; * * @param x - an array of x coordinates to draw the arrow through * @param y - an array of y coordinates to draw the arrow through * @param iWidth - the width to make the arrow lines - typically of the form * GetLongParameter(LP_LINE_WIDTH)*CONSTANT * @param iColour - the color to make the arrow (in Dasher color) * @param dArrowSizeFactor - the factor by which to scale the "hat" on the arrow */ void DasherPolyarrow(myint * x, myint * y, int n, int iWidth, int iColour, double dArrowSizeFactor = 0.7071); /// /// Draw a rectangle specified in Dasher co-ordinates /// Color of -1 => no fill; any other value => fill in that color /// iOutlineColor of -1 => no outline; any other value => outline in that color, EXCEPT /// Thickness < 1 => no outline. /// void DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness); /// /// Draw a centred rectangle specified in Dasher co-ordinates (used for mouse cursor) /// void DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline); void DrawText(const std::string & str, myint x, myint y, int Size, int iColor); + + /** + * Draw a string to the screen. Defined in screen coordinates because + * the original implementation will conver them anyway. They're also + * easier to reason about for drawing overlays. + * @param str The actual string to be drawn + * @param x The x coordinate in screen coordinates. + * @param y The y coordinate in screen coordinates. + * @param iSize The size of the text. + * @param iColor The color of the text. + */ + void DrawText(const std::string & str, screenint x, screenint y, int iSize, int iColor); + /// Request the Screen to copy its buffer to the Display /// \todo Shouldn't be public? void Display(); /// @} protected: /// Clips a line (specified in Dasher co-ordinates) to the visible region /// by intersecting with all boundaries. /// \return true if any part of the line was within the visible region; in this case, (x1,y1)-(x2,y2) delineate exactly that part /// false if the line would be entirely outside the visible region; x1, y1, x2, y2 unaffected. bool ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2); ///Convert a straight line in Dasher-space, to coordinates for a corresponding polyline on the screen /// (because of nonlinearity, this may require multiple line segments) /// \param x1,y1 Dasher co-ordinates of start of line segment; note that these are guaranteed within VisibleRegion. /// \param x2,y2 Dasher co-ordinates of end of line segment; also guaranteed within VisibleRegion. /// \param vPoints vector to which to add screen points. Note that at the point that DasherLine2Screen is called, /// the screen coordinates of the first point should already have been added to this vector; DasherLine2Screen /// will then add exactly one CDasherScreen::point for each line segment required. virtual void DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, std::vector<CDasherScreen::point> &vPoints)=0; // Orientation of Dasher Screen /* inline void MapScreen(screenint * DrawX, screenint * DrawY); */ /* inline void UnMapScreen(screenint * DrawX, screenint * DrawY); */ bool m_bVisibleRegionValid; int m_iRenderCount; private: CDasherScreen *m_pScreen; // provides the graphics (text, lines, rectangles): CDasherInput *m_pInput; // Input device abstraction /// Renders the Dasher node structure virtual void RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) = 0; /// Get the co-ordinates from the input device int GetInputCoordinates(int iN, myint * pCoordinates); bool m_bDemoMode; bool m_bGameMode; }; /// @} #endif /* #ifndef __DasherView_h_ */
rgee/HFOSS-Dasher
c9bbf5a4b44c7c38bb0b1df5b4b7dbb6665362b9
Can't seem to get this testing code to build properly. Keeping it around to come back to later.
diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index 411fbff..5c54a85 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,143 +1,143 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE * kept open for the lifetime of this object and the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all * at once. */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string sPath, int iRegen) : m_sPath(sPath), m_sCurrentWord(""), CWordGeneratorBase(iRegen) {Generate();} CFileWordGenerator(std::string sPath) : m_sPath(sPath), m_sCurrentWord(""), CWordGeneratorBase(0) {Generate();} virtual ~CFileWordGenerator() { m_sFileHandle.close(); } /** * The generator function. In this implementation, it reads from a * file to produce strings.In this implementation, failure means file * io has failed for some reason. * @see CWordGeneratorBase::Generate */ virtual bool Generate(); /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter * @return The actual name of the file being read from */ std::string GetFilename(); /** * Prefix increment operator. * * Moves the generator one word ahead. */ virtual CWordGeneratorBase& operator++(); - std::ifstream GetFileHandle() { return m_sFileHandle; } + std::ifstream& GetFileHandle() { return m_sFileHandle; } std::string GetWholeBuffer() { return m_sGeneratedString; } size_t GetStringPosition() { return m_uiPos; } private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Find the next word in the generated string buffer. * This does NOT return that string, which is why this is not a public * facing method. It only updates the current string to be presented. * * @warning Ensure that this is called whenever m_sGeneratedString is * remade or whenever the current word is actually presented * to a client. */ void FindNextWord(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * The current word we're looking at. This is the next word that * will be returned when GetNextWord is called. */ std::string m_sCurrentWord; /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * Flag for whether there are words left in this model. */ bool m_bWordsLeft; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index 1806e9d..8304735 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,100 +1,102 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. GTEST_DIR = ../gtest # Where to find user code. USER_DIR = . -# Where to find dasher source code and object files -DASHER_DIR = ../../dasher-sandbox/Src +# Where to find dasher object files +DASHER_SANDBOX_DIR = ../../dasher-sandbox/Src + +DASHER_DIR = ../../Src # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include -I$(DASHER_DIR)/DasherCore # Flags passed to the C++ compiler. CXXFLAGS += -g -Wall -Wextra # All tests produced by this Makefile. Remember to add new tests you # created to the list. TESTS = EventTest \ FileWordGenTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. A test should link with either gtest.a or # gtest_main.a, depending on whether it defines its own main() # function. #sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc #sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ # $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc #sample1_unittest : sample1.o sample1_unittest.o gtest_main.a # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ FileWordGenTest : FileWordGenTest.o gtest_main.a $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ FileWordGenTest.o : $(USER_DIR)/FileWordGenTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/FileWordGenTest.cpp EventTest : EventTest.o gtest_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DASHER_DIR)/DasherCore/FileWordGenerator.o -lpthread $^ -o $@ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DASHER_SANDBOX_DIR)/DasherCore/FileWordGenerator.o -lpthread $^ -o $@ EventTest.o : $(USER_DIR)/EventTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp
rgee/HFOSS-Dasher
be42d52734c63b431719200640ac779d379ac8e3
Added testing getters to FileWordGenerator. Wrote test for file opening.
diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index 1c73923..411fbff 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,139 +1,143 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE * kept open for the lifetime of this object and the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all * at once. */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string sPath, int iRegen) : m_sPath(sPath), m_sCurrentWord(""), CWordGeneratorBase(iRegen) {Generate();} CFileWordGenerator(std::string sPath) : m_sPath(sPath), m_sCurrentWord(""), CWordGeneratorBase(0) {Generate();} virtual ~CFileWordGenerator() { m_sFileHandle.close(); } /** * The generator function. In this implementation, it reads from a * file to produce strings.In this implementation, failure means file * io has failed for some reason. * @see CWordGeneratorBase::Generate */ virtual bool Generate(); /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter * @return The actual name of the file being read from */ std::string GetFilename(); /** * Prefix increment operator. * * Moves the generator one word ahead. */ virtual CWordGeneratorBase& operator++(); + + std::ifstream GetFileHandle() { return m_sFileHandle; } + std::string GetWholeBuffer() { return m_sGeneratedString; } + size_t GetStringPosition() { return m_uiPos; } private: /* --------------------------------------------------------------------- * Private Methods * --------------------------------------------------------------------- */ /** * Find the next word in the generated string buffer. * This does NOT return that string, which is why this is not a public * facing method. It only updates the current string to be presented. * * @warning Ensure that this is called whenever m_sGeneratedString is * remade or whenever the current word is actually presented * to a client. */ void FindNextWord(); /* --------------------------------------------------------------------- * Member Variables * --------------------------------------------------------------------- */ /** * The current word we're looking at. This is the next word that * will be returned when GetNextWord is called. */ std::string m_sCurrentWord; /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * Flag for whether there are words left in this model. */ bool m_bWordsLeft; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Testing/dasher_tests/FileWordGenTest.cpp b/Testing/dasher_tests/FileWordGenTest.cpp index 8664894..115da89 100644 --- a/Testing/dasher_tests/FileWordGenTest.cpp +++ b/Testing/dasher_tests/FileWordGenTest.cpp @@ -1,16 +1,17 @@ #include "gtest/gtest.h" #include "FileWordGenerator.h" using namespace Dasher; class FileWordGenTest : public ::testing::Test { protected: virtual void SetUp() { gen = new CFileWordGenerator("TestData/file_loader_test_data.txt"); } CFileWordGenerator* gen; }; TEST_F(FileWordGenTest, OpensFileCorrectly) { + ASSERT_TRUE(gen->GetFileHandle().is_open()); }
rgee/HFOSS-Dasher
01f1260e02f470a1d3b88840851b55867a1dcdab
Pulled out testing branch. All tests will be done here. This is in order to add silly things like getters for private data for use in test fixtures. Changes to code that should not be part of production, but are necessary for testing.
diff --git a/Testing/dasher_tests/FileWordGenTest.cpp b/Testing/dasher_tests/FileWordGenTest.cpp new file mode 100644 index 0000000..8664894 --- /dev/null +++ b/Testing/dasher_tests/FileWordGenTest.cpp @@ -0,0 +1,16 @@ +#include "gtest/gtest.h" +#include "FileWordGenerator.h" +using namespace Dasher; + +class FileWordGenTest : public ::testing::Test { +protected: + virtual void SetUp() { + gen = new CFileWordGenerator("TestData/file_loader_test_data.txt"); + } + + CFileWordGenerator* gen; +}; + + +TEST_F(FileWordGenTest, OpensFileCorrectly) { +} diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index 7b981c5..1806e9d 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,87 +1,100 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. GTEST_DIR = ../gtest # Where to find user code. USER_DIR = . +# Where to find dasher source code and object files +DASHER_DIR = ../../dasher-sandbox/Src + # Flags passed to the preprocessor. -CPPFLAGS += -I$(GTEST_DIR)/include +CPPFLAGS += -I$(GTEST_DIR)/include -I$(DASHER_DIR)/DasherCore # Flags passed to the C++ compiler. CXXFLAGS += -g -Wall -Wextra # All tests produced by this Makefile. Remember to add new tests you # created to the list. -TESTS = EventTest +TESTS = EventTest \ + FileWordGenTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. A test should link with either gtest.a or # gtest_main.a, depending on whether it defines its own main() # function. #sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc #sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ # $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc #sample1_unittest : sample1.o sample1_unittest.o gtest_main.a # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ + +FileWordGenTest : FileWordGenTest.o gtest_main.a + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ +FileWordGenTest.o : $(USER_DIR)/FileWordGenTest.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/FileWordGenTest.cpp + EventTest : EventTest.o gtest_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DASHER_DIR)/DasherCore/FileWordGenerator.o -lpthread $^ -o $@ EventTest.o : $(USER_DIR)/EventTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp + + + diff --git a/Testing/dasher_tests/TestData/file_loader_test_data.txt b/Testing/dasher_tests/TestData/file_loader_test_data.txt new file mode 100644 index 0000000..277e809 --- /dev/null +++ b/Testing/dasher_tests/TestData/file_loader_test_data.txt @@ -0,0 +1,79 @@ +I'm a senior at Cesar Chavez high in San Francisco's sunny Mission district, and that makes me one of the most surveilled people in the world. My name is Marcus Yallow, but back when this story starts, I was going by w1n5t0n. Pronounced "Winston." + +*Not* pronounced "Double-you-one-enn-five-tee-zero-enn" -- unless you're a clueless disciplinary officer who's far enough behind the curve that you still call the Internet "the information superhighway." + +I know just such a clueless person, and his name is Fred Benson, one of three vice-principals at Cesar Chavez. He's a sucking chest wound of a human being. But if you're going to have a jailer, better a clueless one than one who's really on the ball. + +"Marcus Yallow," he said over the PA one Friday morning. The PA isn't very good to begin with, and when you combine that with Benson's habitual mumble, you get something that sounds more like someone struggling to digest a bad burrito than a school announcement. But human beings are good at picking their names out of audio confusion -- it's a survival trait. + +I grabbed my bag and folded my laptop three-quarters shut -- I didn't want to blow my downloads -- and got ready for the inevitable. + +"Report to the administration office immediately." + +My social studies teacher, Ms Galvez, rolled her eyes at me and I rolled my eyes back at her. The Man was always coming down on me, just because I go through school firewalls like wet kleenex, spoof the gait-recognition software, and nuke the snitch chips they track us with. Galvez is a good type, anyway, never holds that against me (especially when I'm helping get with her webmail so she can talk to her brother who's stationed in Iraq). + +My boy Darryl gave me a smack on the ass as I walked past. I've known Darryl since we were still in diapers and escaping from play-school, and I've been getting him into and out of trouble the whole time. I raised my arms over my head like a prizefighter and made my exit from Social Studies and began the perp-walk to the office. + +I was halfway there when my phone went. That was another no-no -- phones are muy prohibido at Chavez High -- but why should that stop me? I ducked into the toilet and shut myself in the middle stall (the furthest stall is always grossest because so many people head straight for it, hoping to escape the smell and the squick -- the smart money and good hygiene is down the middle). I checked the phone -- my home PC had sent it an email to tell it that there was something new up on Harajuku Fun Madness, which happens to be the best game ever invented. + +I grinned. Spending Fridays at school was teh suck anyway, and I was glad of the excuse to make my escape. + +I ambled the rest of the way to Benson's office and tossed him a wave as I sailed through the door. + +"If it isn't Double-you-one-enn-five-tee-zero-enn," he said. Fredrick Benson -- Social Security number 545-03-2343, date of birth August 15 1962, mother's maiden name Di Bona, hometown Petaluma -- is a lot taller than me. I'm a runty 5'8", while he stands 6'7", and his college basketball days are far enough behind him that his chest muscles have turned into saggy man-boobs that were painfully obvious through his freebie dot-com polo-shirts. He always looks like he's about to slam-dunk your ass, and he's really into raising his voice for dramatic effect. Both these start to lose their efficacy with repeated application. + +"Sorry, nope," I said. "I never heard of this R2D2 character of yours." + +"W1n5t0n," he said, spelling it out again. He gave me a hairy eyeball and waited for me to wilt. Of course it was my handle, and had been for years. It was the identity I used when I was posting on message-boards where I was making my contributions to the field of applied security research. You know, like sneaking out of school and disabling the minder-tracer on my phone. But he didn't know that this was my handle. Only a small number of people did, and I trusted them all to the end of the earth. + +"Um, not ringing any bells," I said. I'd done some pretty cool stuff around school using that handle -- I was very proud of my work on snitch-tag killers -- and if he could link the two identities, I'd be in trouble. No one at school ever called me w1n5t0n or even Winston. Not even my pals. It was Marcus or nothing. + +Benson settled down behind his desk and tapped his class-ring nervously on his blotter. He did this whenever things started to go bad for him. Poker players call stuff like this a "tell" -- something that let you know what was going on in the other guy's head. I knew Benson's tells backwards and forwards. + +"Marcus, I hope you realize how serious this is." + +"I will just as soon as you explain what this is, sir." I always say "sir" to authority figures when I'm messing with them. It's my own tell. + +He shook his head at me and looked down, another tell. Any second now, he was going to start shouting at me. "Listen, kiddo! It's time you came to grips with the fact that we know about what you've been doing, and that we're not going to be lenient about it. You're going to be lucky if you're not expelled before this meeting is through. Do you want to graduate?" + +"Mr Benson, you still haven't explained what the problem is --" + +He slammed his hand down on the desk and then pointed his finger at me. "The *problem*, Mr Yallow, is that you've been engaged in criminal conspiracy to subvert this school's security system, and you have supplied security countermeasures to your fellow students. You know that we expelled Graciella Uriarte last week for using one of your devices." Uriarte had gotten a bad rap. She'd bought a radio-jammer from a head-shop near the 16th Street BART station and it had set off the countermeasures in the school hallway. Not my doing, but I felt for her. + +"And you think I'm involved in that?" + +"We have reliable intelligence indicating that you are w1n5t0n" -- again, he spelled it out, and I began to wonder if he hadn't figured out that the 1 was an I and the 5 was an S. "We know that this w1n5t0n character is responsible for the theft of last year's standardized tests." That actually hadn't been me, but it was a sweet hack, and it was kind of flattering to hear it attributed to me. "And therefore liable for several years in prison unless you cooperate with me." + +"You have 'reliable intelligence'? I'd like to see it." + +He glowered at me. "Your attitude isn't going to help you." + +"If there's evidence, sir, I think you should call the police and turn it over to them. It sounds like this is a very serious matter, and I wouldn't want to stand in the way of a proper investigation by the duly constituted authorities." + +"You want me to call the police." + +"And my parents, I think. That would be for the best." + +We stared at each other across the desk. He'd clearly expected me to fold the second he dropped the bomb on me. I don't fold. I have a trick for staring down people like Benson. I look slightly to the left of their heads, and think about the lyrics to old Irish folk songs, the kinds with three hundred verses. It makes me look perfectly composed and unworried. + +*And the wing was on the bird and the bird was on the egg and the egg was in the nest and the nest was on the leaf and the leaf was on the twig and the twig was on the branch and the branch was on the limb and the limb was in the tree and the tree was in the bog -- the bog down in the valley-oh! High-ho the rattlin' bog, the bog down in the valley-oh --* + +"You can return to class now," he said. "I'll call on you once the police are ready to speak to you." + +"Are you going to call them now?" + +"The procedure for calling in the police is complicated. I'd hoped that we could settle this fairly and quickly, but since you insist --" + +"I can wait while you call them is all," I said. "I don't mind." + +He tapped his ring again and I braced for the blast. + +"*Go!*" he yelled. "Get the hell out of my office, you miserable little --" + +I got out, keeping my expression neutral. He wasn't going to call the cops. If he'd had enough evidence to go to the police with, he would have called them in the first place. He hated my guts. I figured he'd heard some unverified gossip and hoped to spook me into confirming it. + +I moved down the corridor lightly and sprightly, keeping my gait even and measured for the gait-recognition cameras. These had been installed only a year before, and I loved them for their sheer idiocy. Beforehand, we'd had face-recognition cameras covering nearly every public space in school, but a court ruled that was unconstitutional. So Benson and a lot of other paranoid school administrators had spent our textbook dollars on these idiot cameras that were supposed to be able to tell one person's walk from another. Yeah, right. + +I got back to class and sat down again, Ms Galvez warmly welcoming me back. I unpacked the school's standard-issue machine and got back into classroom mode. The SchoolBooks were the snitchiest technology of them all, logging every keystroke, watching all the network traffic for suspicious keywords, counting every click, keeping track of every fleeting thought you put out over the net. We'd gotten them in my junior year, and it only took a couple months for the shininess to wear off. Once people figured out that these "free" laptops worked for the man -- and showed a never-ending parade of obnoxious ads to boot -- they suddenly started to feel very heavy and burdensome. + +Cracking my SchoolBook had been easy. The crack was online within a month of the machine showing up, and there was nothing to it -- just download a DVD image, burn it, stick it in the SchoolBook, and boot it while holding down a bunch of different keys at the same time. The DVD did the rest, installing a whole bunch of hidden programs on the machine, programs that would stay hidden even when the Board of Ed did its daily remote integrity checks of the machines. Every now and again I had to get an update for the software to get around the Board's latest tests, but it was a small price to pay to get a little control over the box.
rgee/HFOSS-Dasher
819ff3b965f9a397b056d9ee9315e69008b62872
Fixed event handler test makefile
diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile index c03d350..7b981c5 100644 --- a/Testing/dasher_tests/Makefile +++ b/Testing/dasher_tests/Makefile @@ -1,87 +1,87 @@ # A sample Makefile for building Google Test and using it in user # tests. Please tweak it to suit your environment and project. You # may want to move it to your project's root directory. # # SYNOPSIS: # # make [all] - makes everything. # make TARGET - makes the given target. # make clean - removes all files generated by make. # Please tweak the following variable definitions as needed by your # project, except GTEST_HEADERS, which you can use in your own targets # but shouldn't modify. # Points to the root of Google Test, relative to where this file is. # Remember to tweak this if you move this file. -GTEST_DIR = ../gtest-1.5.0 +GTEST_DIR = ../gtest # Where to find user code. USER_DIR = . # Flags passed to the preprocessor. CPPFLAGS += -I$(GTEST_DIR)/include # Flags passed to the C++ compiler. CXXFLAGS += -g -Wall -Wextra # All tests produced by this Makefile. Remember to add new tests you # created to the list. TESTS = EventTest # All Google Test headers. Usually you shouldn't change this # definition. GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ $(GTEST_DIR)/include/gtest/internal/*.h # House-keeping build targets. all : $(TESTS) clean : rm -f $(TESTS) gtest.a gtest_main.a *.o # Builds gtest.a and gtest_main.a. # Usually you shouldn't tweak such internal variables, indicated by a # trailing _. GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # For simplicity and to avoid depending on Google Test's # implementation details, the dependencies specified below are # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ gtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. A test should link with either gtest.a or # gtest_main.a, depending on whether it defines its own main() # function. #sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc #sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ # $(USER_DIR)/sample1.h $(GTEST_HEADERS) # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc #sample1_unittest : sample1.o sample1_unittest.o gtest_main.a # $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ EventTest : EventTest.o gtest_main.a $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ EventTest.o : $(USER_DIR)/EventTest.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp