Skip to content

Commit

Permalink
Send files to GitHub
Browse files Browse the repository at this point in the history
  • Loading branch information
ruifontes committed Mar 24, 2019
1 parent 7dae056 commit 438bd5f
Show file tree
Hide file tree
Showing 12 changed files with 806 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Set default behaviour, in case users don't have core.autocrlf set.
* text=auto

# Try to ensure that po files in the repo does not include
# source code line numbers.
# Every person expected to commit po files should change their personal config file as described here:
# https://mail.gnome.org/archives/kupfer-list/2010-June/msg00002.html
*.po filter=cleanpo
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
addon/doc/*.css
addon/doc/en/
*_docHandler.py
*.html
*.ini
*.mo
*.pot
*.py[co]
*.nvda-addon
.sconsign.dblite
340 changes: 340 additions & 0 deletions COPYING.txt

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions addon/doc/pt/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@


# Contar palavras

## Autores: Oriol Gómez <[email protected]> e Rui Fontes <[email protected]>

Este extra serve para anunciar o número de palavras do texto seleccionado, pressionando NVDA+Control+W
40 changes: 40 additions & 0 deletions addon/globalPlugins/word-count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# coding=utf-8
# Copyright (C) 2019 Oriol Gómez <[email protected]> and Rui Fontes <[email protected]>
# This file is covered by the GNU General Public License.

import globalPluginHandler
import scriptHandler
import textInfos
import NVDAObjects
from ui import message
import api
import winUser
from globalCommands import SCRCAT_CONFIG
import addonHandler
addonHandler.initTranslation()

class GlobalPlugin(globalPluginHandler.GlobalPlugin):
def script_wordCount(self,gesture):
obj=api.getFocusObject()
treeInterceptor=obj.treeInterceptor
if hasattr(treeInterceptor,'TextInfo') and not treeInterceptor.passThrough:
obj=treeInterceptor
try:
info=obj.makeTextInfo(textInfos.POSITION_SELECTION)
except (RuntimeError, NotImplementedError):
info=None
if not info or info.isCollapsed:
message(_("select some text first."))
else:
wordcount=0
str=info.text
words=str.split()
wordcount+=len(words)
message(_("%s words")%wordcount)

script_wordCount.__doc__ = _("Announces how many words are in the selected text.")
script_wordCount.category = _("Word count")

__gestures={
"kb:NVDA+control+w": "wordCount",
}
73 changes: 73 additions & 0 deletions addon/locale/pt/LC_MESSAGES/nvda.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
msgid ""
msgstr ""
"Project-Id-Version: WordCount\n"
"POT-Creation-Date: 2019-03-24 16:56+0000\n"
"PO-Revision-Date: 2019-03-24 16:57+0000\n"
"Last-Translator: Ângelo Miguel Abrantes <[email protected]>\n"
"Language-Team: Equipa portuguesa do NVDA: Ângelo Abrantes <ampa4374@gmail."
"com> e Rui Fontes <[email protected]>\n"
"Language: pt_PT\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.2.1\n"
"X-Poedit-Basepath: ../../../globalPlugins\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-SearchPath-0: .\n"

#: word-count.py:27
msgid "select some text first."
msgstr "Seleccione algum texto primeiro..."

#: word-count.py:33
#, python-format
msgid "%s words"
msgstr "%s palavras"

#: word-count.py:35
msgid "Announces how many words are in the selected text."
msgstr "Anuncia o número de palavras no texto seleccionado"

#: word-count.py:36
msgid "Word count"
msgstr "Contar palavras"

#~ msgid "Source text"
#~ msgstr "Texto fonte"

#~ msgid "Translated text"
#~ msgstr "Texto traduzido"

#~ msgid "Retranslated text"
#~ msgstr "Texto retro traduzido"

#~ msgid "Translation menu"
#~ msgstr "Menu de tradução"

#~ msgid "Translate from:"
#~ msgstr "Traduzir de"

#~ msgid "Swap languages"
#~ msgstr "Alternar idiomas"

#~ msgid "Translate into:"
#~ msgstr "Traduzir para"

#~ msgid "Favorite"
#~ msgstr "favorito"

#~ msgid "Play translation"
#~ msgstr "Reproduzir a tradução"

#~ msgid "Play source"
#~ msgstr "Reproduzir a fonte"

#~ msgid "Tools menu"
#~ msgstr "Menu de ferramentas"

#~ msgid "New"
#~ msgstr "Novo"

#~ msgid "Speech"
#~ msgstr "Voz"
49 changes: 49 additions & 0 deletions buildVars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding: UTF-8 -*-

# Build customizations
# Change this file instead of sconstruct or manifest files, whenever possible.

# Full getext (please don't change)
_ = lambda x : x

# Add-on information variables
addon_info = {
# for previously unpublished addons, please follow the community guidelines at:
# https://bitbucket.org/nvdaaddonteam/todo/raw/master/guideLines.txt
# add-on Name, internal for nvda
"addon_name" : "wordCount",
# Add-on summary, usually the user visible name of the addon.
# Translators: Summary for this add-on to be shown on installation and add-on information.
"addon_summary" : _("Addon Word count"),
# Add-on description
# Translators: Long description to be shown for this add-on on add-on information from add-ons manager
"addon_description" : _("""Count the words of the selected text when you select some text and press NVDA control w."""),
# version
"addon_version" : "1.1",
# Author(s)
"addon_author" : u"Oriol Gómez <[email protected]> and Rui Fontes <[email protected]>",
# URL for the add-on documentation support
"addon_url" : https://github.com/ruifontes/wordCount,
# Documentation file name
"addon_docFileName" : "readme.html",
# Minimum NVDA version supported (e.g. "2018.3.0")
"addon_minimumNVDAVersion" : 2017.2.0,
# Last NVDA version supported/tested (e.g. "2018.4.0", ideally more recent than minimum version)
"addon_lastTestedNVDAVersion" : 2019.1.0,
# Add-on update channel (default is stable or None)
"addon_updateChannel" : None,
}


import os.path

# Define the python files that are the sources of your add-on.
# You can use glob expressions here, they will be expanded.
pythonSources = ["addon/globalPlugins/*.py", "addon/*.py"]

# Files that contain strings for translation. Usually your python sources
i18nSources = pythonSources + ["buildVars.py"]

# Files that will be ignored when building the nvda-addon file
# Paths are relative to the addon directory, not to the root directory of your addon sources.
excludedFiles = []
2 changes: 2 additions & 0 deletions manifest-translated.ini.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
summary = "{addon_summary}"
description = """{addon_description}"""
10 changes: 10 additions & 0 deletions manifest.ini.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name = {addon_name}
summary = "{addon_summary}"
description = """{addon_description}"""
author = "{addon_author}"
url = {addon_url}
version = {addon_version}
docFileName = {addon_docFileName}
minimumNVDAVersion = {addon_minimumNVDAVersion}
lastTestedNVDAVersion = {addon_lastTestedNVDAVersion}
updateChannel = {addon_updateChannel}
188 changes: 188 additions & 0 deletions sconstruct
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
# NVDA add-on template SCONSTRUCT file
#Copyright (C) 2012, 2014 Rui Batista <[email protected]>
#This file is covered by the GNU General Public License.
#See the file COPYING.txt for more details.

import codecs
import gettext
import os
import os.path
import zipfile

import buildVars

def md2html(source, dest):
import markdown
lang = os.path.basename(os.path.dirname(source)).replace('_', '-')
title="{addonSummary} {addonVersion}".format(addonSummary=buildVars.addon_info["addon_summary"], addonVersion=buildVars.addon_info["addon_version"])
headerDic = {
"[[!meta title=\"": "# ",
"\"]]": " #",
}
with codecs.open(source, "r", "utf-8") as f:
mdText = f.read()
for k, v in headerDic.iteritems():
mdText = mdText.replace(k, v, 1)
htmlText = markdown.markdown(mdText)
with codecs.open(dest, "w", "utf-8") as f:
f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" +
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"%s\" lang=\"%s\">\n" % (lang, lang) +
"<head>\n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"../style.css\" media=\"screen\"/>\n" +
"<title>%s</title>\n" % title +
"</head>\n<body>\n"
)
f.write(htmlText)
f.write("\n</body>\n</html>")

def mdTool(env):
mdAction=env.Action(
lambda target,source,env: md2html(source[0].path, target[0].path),
lambda target,source,env: 'Generating %s'%target[0],
)
mdBuilder=env.Builder(
action=mdAction,
suffix='.html',
src_suffix='.md',
)
env['BUILDERS']['markdown']=mdBuilder

vars = Variables()
vars.Add("version", "The version of this build", buildVars.addon_info["addon_version"])
vars.Add(BoolVariable("dev", "Whether this is a daily development version", False))
vars.Add("channel", "Update channel for this build", buildVars.addon_info["addon_updateChannel"])

env = Environment(variables=vars, ENV=os.environ, tools=['gettexttool', mdTool])
env.Append(**buildVars.addon_info)

if env["dev"]:
import datetime
buildDate = datetime.datetime.now()
year, month, day = str(buildDate.year), str(buildDate.month), str(buildDate.day)
env["addon_version"] = "".join([year, month.zfill(2), day.zfill(2), "-dev"])
env["channel"] = "dev"
elif env["version"] is not None:
env["addon_version"] = env["version"]
if "channel" in env and env["channel"] is not None:
env["addon_updateChannel"] = env["channel"]

addonFile = env.File("${addon_name}-${addon_version}.nvda-addon")

def addonGenerator(target, source, env, for_signature):
action = env.Action(lambda target, source, env : createAddonBundleFromPath(source[0].abspath, target[0].abspath) and None,
lambda target, source, env : "Generating Addon %s" % target[0])
return action

def manifestGenerator(target, source, env, for_signature):
action = env.Action(lambda target, source, env : generateManifest(source[0].abspath, target[0].abspath) and None,
lambda target, source, env : "Generating manifest %s" % target[0])
return action

def translatedManifestGenerator(target, source, env, for_signature):
dir = os.path.abspath(os.path.join(os.path.dirname(str(source[0])), ".."))
lang = os.path.basename(dir)
action = env.Action(lambda target, source, env : generateTranslatedManifest(source[1].abspath, lang, target[0].abspath) and None,
lambda target, source, env : "Generating translated manifest %s" % target[0])
return action

env['BUILDERS']['NVDAAddon'] = Builder(generator=addonGenerator)
env['BUILDERS']['NVDAManifest'] = Builder(generator=manifestGenerator)
env['BUILDERS']['NVDATranslatedManifest'] = Builder(generator=translatedManifestGenerator)

def createAddonHelp(dir):
docsDir = os.path.join(dir, "doc")
if os.path.isfile("style.css"):
cssPath = os.path.join(docsDir, "style.css")
cssTarget = env.Command(cssPath, "style.css", Copy("$TARGET", "$SOURCE"))
env.Depends(addon, cssTarget)
if os.path.isfile("readme.md"):
readmePath = os.path.join(docsDir, "en", "readme.md")
readmeTarget = env.Command(readmePath, "readme.md", Copy("$TARGET", "$SOURCE"))
env.Depends(addon, readmeTarget)

def createAddonBundleFromPath(path, dest):
""" Creates a bundle from a directory that contains an addon manifest file."""
basedir = os.path.abspath(path)
with zipfile.ZipFile(dest, 'w', zipfile.ZIP_DEFLATED) as z:
# FIXME: the include/exclude feature may or may not be useful. Also python files can be pre-compiled.
for dir, dirnames, filenames in os.walk(basedir):
relativePath = os.path.relpath(dir, basedir)
for filename in filenames:
pathInBundle = os.path.join(relativePath, filename)
absPath = os.path.join(dir, filename)
if pathInBundle not in buildVars.excludedFiles: z.write(absPath, pathInBundle)
return dest

def generateManifest(source, dest):
addon_info = buildVars.addon_info
addon_info["addon_version"] = env["addon_version"]
addon_info["addon_updateChannel"] = env["addon_updateChannel"]
with codecs.open(source, "r", "utf-8") as f:
manifest_template = f.read()
manifest = manifest_template.format(**addon_info)
with codecs.open(dest, "w", "utf-8") as f:
f.write(manifest)

def generateTranslatedManifest(source, language, out):
_ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[language]).ugettext
vars = {}
for var in ("addon_summary", "addon_description"):
vars[var] = _(buildVars.addon_info[var])
with codecs.open(source, "r", "utf-8") as f:
manifest_template = f.read()
result = manifest_template.format(**vars)
with codecs.open(out, "w", "utf-8") as f:
f.write(result)

def expandGlobs(files):
return [f for pattern in files for f in env.Glob(pattern)]

addon = env.NVDAAddon(addonFile, env.Dir('addon'))

langDirs = [f for f in env.Glob(os.path.join("addon", "locale", "*"))]

#Allow all NVDA's gettext po files to be compiled in source/locale, and manifest files to be generated
for dir in langDirs:
poFile = dir.File(os.path.join("LC_MESSAGES", "nvda.po"))
moFile=env.gettextMoFile(poFile)
env.Depends(moFile, poFile)
translatedManifest = env.NVDATranslatedManifest(dir.File("manifest.ini"), [moFile, os.path.join("manifest-translated.ini.tpl")])
env.Depends(translatedManifest, ["buildVars.py"])
env.Depends(addon, [translatedManifest, moFile])

pythonFiles = expandGlobs(buildVars.pythonSources)
for file in pythonFiles:
env.Depends(addon, file)

#Convert markdown files to html
createAddonHelp("addon") # We need at least doc in English and should enable the Help button for the add-on in Add-ons Manager
for mdFile in env.Glob(os.path.join('addon', 'doc', '*', '*.md')):
htmlFile = env.markdown(mdFile)
env.Depends(htmlFile, mdFile)
env.Depends(addon, htmlFile)

# Pot target
i18nFiles = expandGlobs(buildVars.i18nSources)
gettextvars={
'gettext_package_bugs_address' : '[email protected]',
'gettext_package_name' : buildVars.addon_info['addon_name'],
'gettext_package_version' : buildVars.addon_info['addon_version']
}

pot = env.gettextPotFile("${addon_name}.pot", i18nFiles, **gettextvars)
env.Alias('pot', pot)
env.Depends(pot, i18nFiles)
mergePot = env.gettextMergePotFile("${addon_name}-merge.pot", i18nFiles, **gettextvars)
env.Alias('mergePot', mergePot)
env.Depends(mergePot, i18nFiles)

# Generate Manifest path
manifest = env.NVDAManifest(os.path.join("addon", "manifest.ini"), os.path.join("manifest.ini.tpl"))
# Ensure manifest is rebuilt if buildVars is updated.
env.Depends(manifest, "buildVars.py")

env.Depends(addon, manifest)
env.Default(addon)
Loading

0 comments on commit 438bd5f

Please sign in to comment.