diff --git a/.gitignore b/.gitignore index e1c409cc4..fed3570b0 100644 --- a/.gitignore +++ b/.gitignore @@ -39,10 +39,9 @@ src/runtime/c/sg/.dirstamp src/runtime/c/stamp-h1 src/runtime/java/.libs/ src/runtime/python/build/ -src/ui/android/libs/ -src/ui/android/obj/ .cabal-sandbox cabal.sandbox.config +.stack-work DATA_DIR # Generated documentation (not exhaustive) diff --git a/LICENSE b/LICENSE index 451984bf4..ed35bf27f 100644 --- a/LICENSE +++ b/LICENSE @@ -8,24 +8,9 @@ other. For this reason the different components have different licenses. In summary: - the GF compiler in the folder src/compiler and the PGF Web service in src/server -are under the GNU GENERAL PUBLIC LICENSE. +are under the GNU GENERAL PUBLIC LICENSE. - - the GF runtime in src/runtime is under dual GNU LESSER GENERAL PUBLIC LICENSE -and BSD LICENSE - - - the resource grammar library in lib/src is under GNU LESSER GENERAL PUBLIC LICENSE. -However the user have the right to choose any license for any application grammar -derived from the resource grammar by using the grammar API. - - - the resource grammar library also includes large coverage lexicons for some languages. -Since these lexicons are derived from external sources they might be under different licenses. -Look at the source file for every lexicon for details. The lexicons that we currently have -are: - - lib/src/bulgarian/ DictBul.gf DictBulAbs.gf for Bulgarian - lib/src/english/ DictEng.gf DictEngAbs.gf for English - lib/src/turkish/ DictTur.gf DictTurAbs.gf for Turkish - lib/src/swedish/ DictSwe.gf DictSweAbs.gf for Swedish + - the GF runtime in src/runtime is under dual GNU LESSER GENERAL PUBLIC LICENSE and BSD LICENSE The rest of this document contains copies of the GPL, LGPL and BSD licenses which are applicable to the different components of Grammatical Framework diff --git a/css/style0.css b/css/style0.css index 3c53c5378..a0eb9c561 100644 --- a/css/style0.css +++ b/css/style0.css @@ -17,10 +17,7 @@ h1 img.nofloat { float: none; } img.right { float: right; } ol.languages { - display: flex; - flex-direction: column; - flex-wrap: wrap; - height: 12em; + column-width: 12em; } .grow { diff --git a/download/index-3.9.t2t b/download/index-3.9.t2t index da96f238c..aa5b1c5de 100644 --- a/download/index-3.9.t2t +++ b/download/index-3.9.t2t @@ -171,6 +171,11 @@ The above notes for installing from source apply also in these cases. For more info on working with the GF source code, see the [GF Developers Guide ../doc/gf-developers.html]. +==Using Stack== + +You can also use [Stack https://www.haskellstack.org] to compile GF, just replace ``cabal install`` above +with ``stack install`` (assuming you already have Stack set up). + ==Older releases== - [GF 3.8 index-3.8.html] (June 2016) diff --git a/gf.cabal b/gf.cabal index bd1b04171..494f483eb 100644 --- a/gf.cabal +++ b/gf.cabal @@ -1,5 +1,5 @@ name: gf -version: 3.9-git +version: 3.10 cabal-version: >= 1.22 build-type: Custom @@ -42,7 +42,7 @@ data-files: custom-setup setup-depends: base, - Cabal >=1.4.0.0, + Cabal >=1.22.0.0, directory, filepath, process >=1.0.1.1 @@ -67,11 +67,6 @@ flag network-uri -- Description: Make -new-comp the default -- Default: True -flag custom-binary - Description: Use a customised version of the binary package - Default: True - Manual: True - flag c-runtime Description: Include functionality from the C run-time library (which must be installed already) Default: False @@ -89,17 +84,14 @@ Library exceptions hs-source-dirs: src/runtime/haskell - if flag(custom-binary) - other-modules: - -- not really part of GF but I have changed the original binary library - -- and we have to keep the copy for now. - Data.Binary - Data.Binary.Put - Data.Binary.Get - Data.Binary.Builder - Data.Binary.IEEE754 - else - build-depends: binary, data-binary-ieee754 + other-modules: + -- not really part of GF but I have changed the original binary library + -- and we have to keep the copy for now. + Data.Binary + Data.Binary.Put + Data.Binary.Get + Data.Binary.Builder + Data.Binary.IEEE754 --ghc-options: -fwarn-unused-imports --if impl(ghc>=7.8) diff --git a/src/compiler/GF/Infra/Option.hs b/src/compiler/GF/Infra/Option.hs index 27aa1c256..fa0e91980 100644 --- a/src/compiler/GF/Infra/Option.hs +++ b/src/compiler/GF/Infra/Option.hs @@ -373,8 +373,6 @@ optDescr = "Enable or disable global grammar optimization. This could significantly reduce the size of the final PGF file", Option [] ["split-pgf"] (NoArg (splitPGF True)) "Split the PGF into one file per language. This allows the runtime to load only individual languages", - Option [] ["stem"] (onOff (toggleOptimize OptStem) True) "Perform stem-suffix analysis (default on).", - Option [] ["cse"] (onOff (toggleOptimize OptCSE) True) "Perform common sub-expression elimination (default on).", Option [] ["cfg"] (ReqArg cfgTransform "TRANS") "Enable or disable specific CFG transformations. TRANS = merge, no-merge, bottomup, no-bottomup, ...", Option [] ["heuristic_search_factor"] (ReqArg (readDouble (\d o -> o { optHeuristicFactor = Just d })) "FACTOR") "Set the heuristic search factor for statistical parsing", Option [] ["case_sensitive"] (onOff (\v -> set $ \o -> o{optCaseSensitive=v}) True) "Set the parser in case-sensitive/insensitive mode [sensitive by default]", @@ -448,8 +446,6 @@ optDescr = optimize_pgf x = set $ \o -> o { optOptimizePGF = x } splitPGF x = set $ \o -> o { optSplitPGF = x } - toggleOptimize x b = set $ setOptimization' x b - cfgTransform x = let (x', b) = case x of 'n':'o':'-':rest -> (rest, False) _ -> (x, True) diff --git a/src/example-based/ExampleDemo.hs b/src/example-based/ExampleDemo.hs deleted file mode 100644 index fe4eb501d..000000000 --- a/src/example-based/ExampleDemo.hs +++ /dev/null @@ -1,553 +0,0 @@ -module ExampleDemo (Environ,initial,getNext, provideExample, testThis,mkFuncWithArg,searchGoodTree,isMeta) - where - -import PGF ---import System.IO -import Data.List ---import Control.Monad -import qualified Data.Map as Map ---import qualified Data.IntMap as IntMap -import qualified Data.Set as Set -import Data.Maybe ---import System.Environment (getArgs) -import System.Random (RandomGen) --newStdGen - - -type MyType = CId -- name of the categories from the program -type ConcType = CId -- categories from the resource grammar, that we parse on -type MyFunc = CId -- functions that we need to implement ---type FuncWithArg = ((MyFunc, MyType), Expr) -- function with arguments -type InterInstr = [String] -- lincats that were generated but not written to the file - - - -data FuncWithArg = FuncWithArg - {getName :: MyFunc, -- name of the function to generate - getType :: MyType, -- return type of the function - getTypeArgs :: [MyType] -- types of arguments - } - deriving (Show,Eq,Ord) - --- we assume that it's for English for the moment - - -type TypeMap = Map.Map MyType ConcType -- mapping found from a file - -type ConcMap = Map.Map MyFunc Expr -- concrete expression after parsing - -data Environ = Env {getTypeMap :: TypeMap, -- mapping between a category in the grammar and a concrete type from RGL - getConcMap :: ConcMap, -- concrete expression after parsing - getSigs :: Map.Map MyType [FuncWithArg], -- functions for which we have the concrete syntax already with args - getAll :: [FuncWithArg] -- all the functions with arguments - } - - -getNext :: Environ -> Environ -> ([MyFunc],[MyFunc]) -getNext env example_env = - let sgs = getSigs env - allfuncs = getAll env - names = Set.fromList $ map getName $ concat $ Map.elems sgs - exampleable = filter (\x -> (isJust $ getNameExpr x env) - && - (not $ Set.member x names) -- maybe drop this if you want to also rewrite from examples... - ) $ map getName allfuncs - testeable = filter (\x -> (isJust $ getNameExpr x env ) - && - (Set.member x names) - ) $ map getName allfuncs - - in (exampleable,testeable) - - -provideExample :: RandomGen gen => gen -> Environ -> MyFunc -> PGF -> PGF -> Language -> Maybe (Expr,String) -provideExample gen env myfunc parsePGF pgfFile lang = - fmap giveExample $ getNameExpr myfunc env - where - giveExample e_ = - let newexpr = head $ generateRandomFromDepth gen pgfFile e_ (Just 5) -- change here with the new random generator - ty = getType $ head $ filter (\x -> getName x == myfunc) $ getAll env - embeddedExpr = maybe "" (\x -> ", as in: " ++ q (linearize pgfFile lang x)) (embedInStart (getAll env) (Map.fromList [(ty,e_)])) - lexpr = linearize pgfFile lang newexpr - q s = sq++s++sq - sq = "\"" - in (newexpr,q lexpr ++ embeddedExpr) --- question, you need the IO monad for the random generator, how to do otherwise ?? --- question can you make the expression bold/italic - somehow distinguishable from the rest ? - - - -testThis :: Environ -> MyFunc -> PGF -> Language -> Maybe String -testThis env myfunc parsePGF lang = - fmap (linearize parsePGF lang . mapToResource env . llin env) $ - getNameExpr myfunc env - - --- we assume that even the functions linearized by the user will still be in getSigs along with their linearization - - --- fill in the blancs of an expression that we want to linearize for testing purposes ---------------------------------------------------------------------------- - -llin :: Environ -> Expr -> Expr -llin env expr = - let - (id,args) = fromJust $ unApp expr - --cexpr = fromJust $ Map.lookup id (getConcMap env) - in - if any isMeta args - then let - sigs = concat $ Map.elems $ getSigs env - tys = findExprWhich sigs id - in replaceConcArg 1 tys expr env - else mkApp id $ map (llin env) args - - --- argument of the meta variable to replace, list of arguments left, expression to replace, environment, current replace expression -replaceConcArg :: Int -> [MyType] -> Expr -> Environ -> Expr -replaceConcArg i [] expr env = expr -replaceConcArg i (t:ts) expr env = -- TO DO : insert randomness here !! - let ss = fromJust $ Map.lookup t $ getSigs env - args = filter (null . getTypeArgs) ss - finArg = if null args then let l = last ss in llin env (mkApp (getName l) [mkMeta j | j <- [1..(length $ getTypeArgs l)]]) - else mkApp (getName $ last args) [] - in - let newe = replaceOne i finArg expr - in replaceConcArg (i+1) ts newe env - --- replace a certain metavariable with a certain expression in another expression - return updated expression -replaceOne :: Int -> Expr -> Expr -> Expr -replaceOne i erep expr = - if isMeta expr && ((fromJust $ unMeta expr) == i) - then erep - else if isMeta expr then expr - else let (id,args) = fromJust $ unApp expr - in - mkApp id $ map (replaceOne i erep) args - - -findExprWhich :: [FuncWithArg] -> MyFunc -> [MyType] -findExprWhich lst f = getTypeArgs $ head $ filter (\x -> getName x == f) lst - - -mapToResource :: Environ -> Expr -> Expr -mapToResource env expr = - let (id,args) = maybe (error $ "tried to unwrap " ++ showExpr [] expr) (\x -> x) (unApp expr) - cmap = getConcMap env - cexp = maybe (error $ "didn't find " ++ showCId id ++ " in "++ show cmap) (\x -> x) (Map.lookup id cmap) - in - if null args then cexp - else let newargs = map (mapToResource env) args - in replaceAllArgs cexp 1 newargs - where - replaceAllArgs expr i [] = expr - replaceAllArgs expr i (x:xs) = replaceAllArgs (replaceOne i x expr) (i+1) xs - - - ------------------------------------------------ - --- embed expression in another one from the start category - -embedInStart :: [FuncWithArg] -> Map.Map MyType Expr -> Maybe Expr -embedInStart fss cs = - let currset = Map.toList cs - nextset = Map.fromList $ concat [ if elem myt (getTypeArgs farg) - then connectWithArg (myt,exp) farg else [] - | (myt,exp) <- currset, farg <- fss] - nextmap = Map.union cs nextset - maybeExpr = Map.lookup startCateg nextset - in if isNothing maybeExpr then - if Map.size nextmap == Map.size cs then Nothing --error $ "could't build " ++ show startCateg ++ "with " ++ show fss - else embedInStart fss nextmap - else return $ fromJust maybeExpr - where - connectWithArg (myt,exp) farg = - let ind = head $ elemIndices myt (getTypeArgs farg) - in [(getType farg, mkApp (getName farg) $ [mkMeta i | i <- [1..ind]] ++ [exp] ++ [mkMeta i | i <- [(ind + 1)..((length $ getTypeArgs farg) - 1)]])] - - - - - ------------------------------------------------ -{- -updateConcMap :: Environ -> MyFunc -> Expr -> Environ -updateConcMap env myf expr = - Env (getTypeMap env) (Map.insert myf expr (getConcMap env)) (getSigs env) (getAll env) - - -updateInterInstr :: Environ -> MyType -> FuncWithArg -> Environ -updateInterInstr env myt myf = - let ii = getSigs env - newInterInstr = - maybe (Map.insert myt [myf] ii) (\x -> Map.insert myt (myf:x) ii) $ Map.lookup myt ii - in Env (getTypeMap env) (getConcMap env) newInterInstr (getAll env) - - -putSignatures :: Environ -> [FuncWithArg] -> Environ -putSignatures env fss = - Env (getTypeMap env) (getConcMap env) (mkSigs fss) (getAll env) - - -updateEnv :: Environ -> FuncWithArg -> MyType -> Expr -> Environ -updateEnv env myf myt expr = - let ii = getSigs env - nn = getName myf - newInterInstr = - maybe (Map.insert myt [myf] ii) (\x -> Map.insert myt (myf:x) ii) $ Map.lookup myt ii - in Env (getTypeMap env) (Map.insert nn expr (getConcMap env)) newInterInstr (getAll env) --} - -mkSigs :: [FuncWithArg] -> Map.Map MyType [FuncWithArg] -mkSigs fss = Map.fromListWith (++) $ zip (map getType fss) (map (\x -> [x]) fss) - - - -{------------------------------------ -lang :: String -lang = "Eng" - - -parseLang :: Language -parseLang = fromJust $ readLanguage "ParseEng" - - -parsePGFfile :: String -parsePGFfile = "ParseEngAbs.pgf" -------------------------------------} - - - - - -searchGoodTree :: Environ -> Expr -> [Expr] -> IO (Maybe (Expr,Expr)) -searchGoodTree env expr [] = return Nothing -searchGoodTree env expr (e:es) = - do val <- debugReplaceArgs expr e env - maybe (searchGoodTree env expr es) (\x -> return $ Just (x,e)) val - - - -getNameExpr :: MyFunc -> Environ -> Maybe Expr -getNameExpr myfunc env = - let allfunc = filter (\x -> getName x == myfunc) $ getAll env - in - if null allfunc then Nothing - else getExpr (head allfunc) env - --- find an expression to generate where we have all the other elements available -getExpr :: FuncWithArg -> Environ -> Maybe Expr -getExpr farg env = - let tys = getTypeArgs farg - ctx = getSigs env - lst = getConcTypes ctx tys 1 - in if (all isJust lst) then Just $ mkApp (getName farg) (map fromJust lst) - else Nothing - where getConcTypes context [] i = [] - getConcTypes context (ty:types) i = - let pos = Map.lookup ty context - in - if isNothing pos || (null $ fromJust pos) then [Nothing] - else - let mm = last $ fromJust pos - mmargs = getTypeArgs mm - newi = i + length mmargs - 1 - lst = getConcTypes (Map.insert ty (init $ (fromJust pos)) context) types (newi+1) - in - if (all isJust lst) then -- i..newi - (Just $ mkApp (getName mm) [mkMeta j | j <- [1..(length mmargs)]]) : lst - else [Nothing] - - - - - --- only covers simple expressions with meta variables, not the rest... -isGeneralizationOf :: Expr -> Expr -> Bool -isGeneralizationOf genExpr testExpr = - if isMeta genExpr then True - else if isMeta testExpr then False - else let genUnwrap = unApp genExpr - testUnwrap = unApp testExpr - in if isNothing genUnwrap || isNothing testUnwrap then False -- see if you can generalize here - else let (gencid, genargs) = fromJust genUnwrap - (testcid, testargs) = fromJust testUnwrap - in - (gencid == testcid) && (length genargs == length testargs) - && (and [isGeneralizationOf g t | (g,t) <- (zip genargs testargs)]) - -{-do lst <- getConcTypes context types (i+1) - return $ mkMeta i : lst -} - -debugReplaceArgs :: Expr -> Expr -> Environ -> IO (Maybe Expr) -debugReplaceArgs aexpr cexpr env = - if isNothing $ unApp aexpr then return Nothing - else if any isNothing $ map unApp $ snd $ fromJust $ unApp aexpr then return Nothing - else - let args = map (fst.fromJust.unApp) $ snd $ fromJust $ unApp aexpr - concExprs = map (\x -> fromJust $ Map.lookup x $ getConcMap env) args - in startReplace 1 cexpr concExprs - where - startReplace i cex [] = return $ Just cex - startReplace i cex (a:as) = do val <- debugReplaceConc cex i a - maybe ( --do putStrLn $ "didn't find "++ showExpr [] a ++ " in " ++showExpr [] cexpr - return Nothing) - (\x -> --do putStrLn $ "found it, the current expression is "++ showExpr [] x - startReplace (i+1) x as) - val - -debugReplaceConc :: Expr -> Int -> Expr -> IO (Maybe Expr) -debugReplaceConc expr i e = - let (newe,isThere) = searchArg expr - in if isThere then return $ Just newe else return $ Nothing - where - searchArg e_ = - if isGeneralizationOf e e_ then (mkMeta i, True) - else maybe (e_,False) (\(cid,args) -> let repargs = map searchArg args - in (mkApp cid (map fst repargs), or $ map snd repargs)) $ unApp e_ - - -{- --- replaceArgs : Original expression to parse (from abstract syntax) -> Concrete expression (parsed) -replaceArgs :: Expr -> Expr -> Environ -> Maybe Expr -replaceArgs aexpr cexpr env = - if isNothing $ unApp aexpr then error $ "could't unwrap this "++ show aexpr - else if any isNothing $ map unApp $ snd $ fromJust $ unApp aexpr then error $ "couldn't unwrap more this : "++ show aexpr - else - let args = map (fst.fromJust.unApp) $ snd $ fromJust $ unApp aexpr - concExprs = map (\x -> fromJust $ Map.lookup x $ getConcMap env) args - in startReplace 1 cexpr concExprs - where - startReplace i cex [] = return cex - startReplace i cex (a:as) = maybe Nothing (\x -> startReplace (i+1) x as) $ replaceConc cex i a - - - -replaceConc :: Expr -> Int -> Expr -> Maybe Expr -replaceConc expr i e = - let (newe,isThere) = searchArg expr - in if isThere then return newe else Nothing - where - searchArg e_ = - if isGeneralizationOf e e_ then (mkMeta i, True) - else maybe (e_,False) (\(cid,args) -> let repargs = map searchArg args - in (mkApp cid (map fst repargs), or $ map snd repargs)) $ unApp e_ - - - -writeResults :: Environ -> String -> IO () -writeResults env fileName = - let cmap = getConcMap env - lincats = unlines $ map (\(x,y) -> "lincat " ++ showCId x ++ " = " ++ showCId y ++ " ; " ) $ Map.toList $ getTypeMap env - sigs = unlines $ map - (\x -> let n = getName x - no = length $ getTypeArgs x - oargs = unwords $ ("lin " ++ showCId n) : ["o"++show i | i <- [1..no]] - in (oargs ++ " = " ++ (simpleReplace $ showExpr [] $ fromJust $ Map.lookup n cmap) ++ " ; ")) $ concat $ Map.elems $ getSigs env - in - writeFile fileName ("\n" ++ lincats ++ "\n\n" ++ sigs) - - -simpleReplace :: String -> String -simpleReplace [] = [] -simpleReplace ('?':xs) = 'o' : simpleReplace xs -simpleReplace (x:xs) = x : simpleReplace xs --} - -isMeta :: Expr -> Bool -isMeta = isJust.unMeta - --- works with utf-8 characters also, as it seems - - -mkFuncWithArg :: ((CId,CId),[CId]) -> FuncWithArg -mkFuncWithArg ((c1,c2),cids) = FuncWithArg c1 c2 cids - - ---------------------------------------------------------------------------------- - -initial :: TypeMap -> ConcMap -> [FuncWithArg] -> [FuncWithArg] -> Environ -initial tm cm fss allfs = Env tm cm (mkSigs fss) allfs -{- -testInit :: [FuncWithArg] -> Environ -testInit allfs = initial lTypes Map.empty [] allfs - -lTypes = Map.fromList [(mkCId "Comment", mkCId "S"),(mkCId "Item", mkCId "NP"), (mkCId "Kind", mkCId "CN"), (mkCId "Quality", mkCId "AP")] --} -startCateg = mkCId "Comment" --- question about either to give the startcat or not ... - - - - - ----------------------------------------------------------------------------------------------------------- -{- -main = - do args <- getArgs - case args of - [pgfFile] -> - do pgf <- readPGF pgfFile - parsePGF <- readPGF parsePGFfile - fsWithArg <- forExample pgf - let funcsWithArg = map (map mkFuncWithArg) fsWithArg - let morpho = buildMorpho parsePGF parseLang - let fss = concat funcsWithArg - let fileName = takeWhile (/='.') pgfFile ++ lang ++ ".gf" - env <- start parsePGF pgf morpho (testInit fss) fss - putStrLn $ "Should I write the results to a file ? yes/no" - ans <-getLine - if ans == "yes" then do writeResults env fileName - putStrLn $ "Wrote file " ++ fileName - else return () - _ -> fail "usage : Testing " - - - -start :: PGF -> PGF -> Morpho -> Environ -> [FuncWithArg] -> IO Environ -start parsePGF pgfFile morpho env lst = - do putStrLn "Do you want examples from another language ? (no/concrete syntax name otherwise)" - ans1 <- getLine - putStrLn "Do you want testing mode ? (yes/no)" - ans2 <- getLine - case (ans1,ans2) of - ("no","no") -> do putStrLn "no extra language, just the abstract syntax tree" - interact env lst False Nothing - (_,"no") -> interact env lst False (readLanguage ans1) - ("no","yes") -> do putStrLn "no extra language, just the abstract syntax tree" - interact env lst True Nothing - (_,"yes") -> interact env lst True (readLanguage ans1) - ("no",_) -> do putStrLn "no extra language, just the abstract syntax tree" - putStrLn $ "I assume you don't want the testing mode ... " - interact env lst False Nothing - (_,_) -> do putStrLn $ "I assume you don't want the testing mode ... " - interact env lst False (readLanguage ans1) - where - - interact environ [] func _ = return environ - interact environ (farg:fargs) boo otherLang = - do - maybeEnv <- basicInter farg otherLang environ boo - if isNothing maybeEnv then return environ - else interact (fromJust maybeEnv) fargs boo otherLang - - basicInter farg js environ False = - let e_ = getExpr farg environ in - if isNothing e_ then return $ Just environ - else parseAndBuild farg js environ (getType farg) e_ Nothing - basicInter farg js environ True = - let (e_,e_test) = get2Expr farg environ in - if isNothing e_ then return $ Just environ - else if isNothing e_test then do putStrLn $ "not enough arguments "++ (showCId $ getName farg) - parseAndBuild farg js environ (getType farg) e_ Nothing - else parseAndBuild farg js environ (getType farg) e_ e_test - --- . head . generateRandomFrom gen2 pgfFile - parseAndBuild farg js environ ty e_ e_test = - do let expr = fromJust e_ - gen1 <- newStdGen - gen2 <- newStdGen - let newexpr = head $ generateRandomFrom gen1 pgfFile expr - let embeddedExpr = maybe "***" (showExpr [] ) (embedInStart (getAll environ) (Map.fromList [(ty,expr)])) - let lexpr = if isNothing js then "" else "\n-- " ++ linearize pgfFile (fromJust js) newexpr ++ " --" - putStrLn $ "Give an example for " ++ (showExpr [] expr) - ++ lexpr ++ "and now" - ++ "\n\nas in " ++ embeddedExpr ++ "\n\n" - -- - ex <- getLine - if (ex == ":q") then return Nothing - else - let ctype = fromJust $ Map.lookup (getType farg) (getTypeMap environ) in - do env' <- decypher farg ex expr environ (fromJust $ readType $ showCId ctype) e_test - return (Just env') - - decypher farg ex expr environ ty e_test = - --do putStrLn $ "We need to parse " ++ ex ++ " as " ++ show ctype - let pTrees = parse parsePGF (fromJust $ readLanguage "ParseEng") ty ex in - pickTree farg expr environ ex e_test pTrees - - -- putStrLn $ "And now for testing, \n is this also correct yes/no \n ## " ++ (linearize parsePGF parseLang $ mapToResource newenv $ llin newenv e_test) ++ " ##" - - -- select the right tree among the options given by the parser - pickTree farg expr environ ex e_test [] = - let miswords = morphoMissing morpho (words ex) - in - if null miswords then do putStrLn $ "all words known, but some syntactic construction is not covered by the grammar..." - return environ - else do putStrLn $ "the following words are unknown, please add them to the lexicon: " ++ show miswords - return environ - pickTree farg expr environ ex e_test [tree] = - do val <- searchGoodTree environ expr [tree] -- maybe order here after the probabilities for better precision - maybe (do putStrLn $ "none of the trees is consistent with the rest of the grammar, please check arguments " - return environ) - (\(x,newtree) -> let newenv = updateEnv environ farg (getType farg) x in - do putStrLn $ "the result is "++showExpr [] x - newtestenv <- testTest newenv e_test -- question ? should it belong there - there is just one possibility of a tree... - return newenv) val - pickTree farg expr environ ex e_test parseTrees = - do putStrLn $ "There is more than one possibility, do you want to choose the right tree yourself ? yes/no " - putStr " >" - ans <- getLine - if ans == "yes" then do pTree <- chooseRightTree parseTrees - processTree farg environ expr pTree e_test - else processTree farg environ expr parseTrees e_test - - -- introduce testing function, if it doesn't work, then reparse, take that tree - testTree envv e_test = return envv -- TO DO - add testing here - - testTest envv Nothing = return envv - testTest envv (Just exxpr) = testTree envv exxpr - - - -- allows the user to pick his own tree - chooseRightTree trees = return trees -- TO DO - add something clever here - - -- selects the tree from where one can abstract over the original arguments - processTree farg environ expr lsTrees e_test = - let trmes = if length lsTrees == 1 then "the tree is not consistent " else "none of the trees is consistent " in - do val <- searchGoodTree environ expr lsTrees - maybe (do putStrLn $ trmes ++ "with the rest of the grammar, please check arguments! " - return environ) - (\(x,newtree) -> let newenv = updateEnv environ farg (getType farg) x in - do putStrLn $ "the result is "++showExpr [] x - newtestenv <- testTest newenv e_test - return newenv) val - - - -------------------------------- - -get2Expr :: FuncWithArg -> Environ -> (Maybe Expr, Maybe Expr) -get2Expr farg env = - let tys = getTypeArgs farg - ctx = getSigs env - (lst1,lst2) = getConcTypes2 ctx tys 1 - arg1 = if (all isJust lst1) then Just $ mkApp (getName farg) (map fromJust lst1) else Nothing - arg2 = if (all isJust lst2) then Just $ mkApp (getName farg) (map fromJust lst2) else Nothing - in if arg1 == arg2 then (arg1, Nothing) - else (arg1,arg2) - where - getConcTypes2 context [] i = ([],[]) - getConcTypes2 context (ty:types) i = - let pos = Map.lookup ty context - in - if isNothing pos || (null $ fromJust pos) then ([Nothing],[Nothing]) - else - let (mm,tt) = (last $ fromJust pos, head $ fromJust pos) - mmargs = getTypeArgs mm - newi = i + length mmargs - 1 - (lst1,lst2) = getConcTypes2 (Map.insert ty (init (fromJust pos)) context) types (newi+1) - ttargs = getTypeArgs tt - newtti = i + length ttargs - 1 - fstArg = if (all isJust lst1) then -- i..newi - (Just $ mkApp (getName mm) [mkMeta j | j <- [1..(length mmargs)]]) : lst1 - else [Nothing] - sndArg = if (all isJust lst2) then - (Just $ mkApp (getName tt) [mkMeta j | j <- [1..(length ttargs)]]) : lst2 - else [Nothing] - in - (fstArg,sndArg) - - --} - \ No newline at end of file diff --git a/src/example-based/ExampleService.hs b/src/example-based/ExampleService.hs deleted file mode 100644 index e6312bf96..000000000 --- a/src/example-based/ExampleService.hs +++ /dev/null @@ -1,128 +0,0 @@ -module ExampleService(cgiMain,cgiMain',newPGFCache) where -import System.Random(newStdGen) -import System.FilePath((),makeRelative) -import Data.Map(fromList) -import Data.Char(isDigit) -import Data.Maybe(fromJust) -import qualified Codec.Binary.UTF8.String as UTF8 (decodeString) -import PGF -import GF.Compile.ToAPI -import Network.CGI -import Text.JSON -import CGIUtils -import Cache -import qualified ExampleDemo as E - -newPGFCache = newCache readPGF - - -cgiMain :: Cache PGF -> CGI CGIResult -cgiMain = handleErrors . handleCGIErrors . cgiMain' "." "." - -cgiMain' root cwd cache = - do command <- getInp "command" - environ <- parseEnviron =<< getInp "state" - case command of - "possibilities" -> doPossibilities environ - "provide_example" -> doProvideExample root cwd cache environ - "abstract_example" -> doAbstractExample cwd cache environ - "test_function" -> doTestFunction cwd cache environ - _ -> throwCGIError 400 ("Unknown command: "++command) [] - -doPossibilities environ = - do example_environ <- parseEnviron =<< getInp "example_state" - outputJSONP (E.getNext environ example_environ) - -doProvideExample root cwd cache environ = - do Just lang <- readInput "lang" - fun <- getCId "fun" - parsePGF <- readParsePGF cwd cache - let adjpath path = rootmakeRelative "/" (makeRelative root cwdpath) - pgf <- liftIO . readCache cache . adjpath =<< getInp "grammar" - gen <- liftIO newStdGen - let Just (e,s) = E.provideExample gen environ fun parsePGF pgf lang - res = (showExpr [] e,s) - liftIO $ logError $ "proveExample ... = "++show res - outputJSONP res - -doAbstractExample cwd cache environ = - do example <- getInp "input" - Just params <- readInput "params" - absstr <- getInp "abstract" - Just abs <- return $ readExpr absstr - liftIO $ logError $ "abstract = "++showExpr [] abs - Just cat <- readInput "cat" - let t = mkType [] cat [] - parsePGF <- readParsePGF cwd cache - let lang:_ = languages parsePGF - ae <- liftIO $ abstractExample parsePGF environ lang t abs example - outputJSONP (fmap (\(e,_)->(exprToAPI (instExpMeta params e),e)) ae) - -abstractExample parsePGF env lang cat abs example = - E.searchGoodTree env abs (parse parsePGF lang cat example) - -doTestFunction cwd cache environ = - do fun <- getCId "fun" - parsePGF <- readParsePGF cwd cache - let lang:_ = languages parsePGF - Just txt <- return (E.testThis environ fun parsePGF lang) - outputJSONP txt - -getCId :: String -> CGI CId -getCId name = maybe err return =<< fmap readCId (getInp name) - where err = throwCGIError 400 ("Bad "++name) [] -{- -getLimit :: CGI Int -getLimit = maybe err return =<< readInput "limit" - where err = throwCGIError 400 "Missing/bad limit" [] --} - -readParsePGF cwd cache = - do parsepgf <- getInp "parser" - liftIO $ readCache cache (cwdparsepgf) - -parseEnviron s = do state <- liftIO $ readIO s - return $ environ state - -getInp name = maybe err (return . UTF8.decodeString) =<< getInput name - where err = throwCGIError 400 ("Missing parameter: "++name) [] - - -instance JSON CId where - showJSON = showJSON . show - readJSON = (readResult =<<) . readJSON - -instance JSON Expr where - showJSON = showJSON . showExpr [] - readJSON = (m2r . readExpr =<<) . readJSON - -m2r = maybe (Error "read failed") Ok - -readResult s = case reads s of - (x,r):_ | lex r==[("","")] -> Ok x - _ -> Error "read failed" - --------------------------------------------------------------------------------- --- cat lincat fun lin fun cat cat -environ :: ([(CId, CId)],[(CId, Expr)],[((CId, CId), [CId])]) -> E.Environ -environ (lincats,lins0,funs) = - E.initial (fromList lincats) concmap fs allfs - where - concmap = fromList lins - allfs = map E.mkFuncWithArg funs - fs = [E.mkFuncWithArg f | f@((fn,_),_)<-funs, fn `elem` cns] - cns = map fst lins - lins = filter (not . E.isMeta .snd) lins0 - - -instExpMeta :: [CId] -> Expr -> Expr -instExpMeta ps = fromJust . readExpr . instMeta ps . showExpr [] - -instMeta :: [CId] -> String -> String -instMeta ps s = - case break (=='?') s of - (s1,'?':s2) -> - case span isDigit s2 of - (s21@(_:_),s22) -> s1++show (ps!!(read s21-1))++instMeta ps s22 - ("",s22) -> s1++'?':instMeta ps s22 - (_,_) -> s diff --git a/src/example-based/exb-fcgi.hs b/src/example-based/exb-fcgi.hs deleted file mode 100644 index 54f1872d0..000000000 --- a/src/example-based/exb-fcgi.hs +++ /dev/null @@ -1,15 +0,0 @@ -{-# LANGUAGE CPP #-} -import Control.Concurrent(forkIO) -import Network.FastCGI(runFastCGI,runFastCGIConcurrent') -import ExampleService(cgiMain,newPGFCache) - -main = do --stderrToFile logFile - fcgiMain =<< newPGFCache - - -fcgiMain cache = -#ifndef mingw32_HOST_OS - runFastCGIConcurrent' forkIO 100 (cgiMain cache) -#else - runFastCGI (cgiMain cache) -#endif diff --git a/src/example-based/gf-exb.cabal b/src/example-based/gf-exb.cabal deleted file mode 100644 index 1366e75da..000000000 --- a/src/example-based/gf-exb.cabal +++ /dev/null @@ -1,25 +0,0 @@ -Name: gf-exb -Version: 1.0 -Cabal-version: >= 1.8 -Build-type: Simple -License: GPL -Synopsis: Example-based grammar writing for the Grammatical Framework - -executable exb.fcgi - main-is: exb-fcgi.hs - Hs-source-dirs: . ../server ../compiler ../runtime/haskell - other-modules: ExampleService ExampleDemo - FastCGIUtils Cache GF.Compile.ToAPI - -- and a lot more... - ghc-options: -threaded - if impl(ghc>=7.0) - ghc-options: -rtsopts - - build-depends: base >=4.2 && <5, json, cgi, fastcgi, random, - containers, old-time, directory, bytestring, utf8-string, - pretty, array, mtl, fst, filepath - - if os(windows) - ghc-options: -optl-mwindows - else - build-depends: unix diff --git a/src/example-based/todo.txt b/src/example-based/todo.txt deleted file mode 100644 index 196dbc097..000000000 --- a/src/example-based/todo.txt +++ /dev/null @@ -1,20 +0,0 @@ - -Editor improvements for example-based grammar writing: -+ Remove the same language from the example language menu -+ Send the other language environment to getNext -- Compile a new .pgf automatically when needed -- Update buttons automatically when functions are added or removed -- Switch over to using AbsParadigmsEng.pgf instead of the old exprToAPI function - -Editor support for guided construction of linearization functions -- enter api expressions by parsing them with AbsParadigmsEng.pgf in minibar -- replace simpleParseInput with one that accepts quoted string literals -- use lexcode/unlexcode in minibar -- better support for literals in minibar (completion info from the PGF - library should indicate if literals are acceptable) - -Server support for example-based grammar writing: -- Change getNext to use info from the example language -- Random generator restricted to defined functions - -- More testing diff --git a/src/pgf-binary/PGF/Data/Binary.hs b/src/pgf-binary/PGF/Data/Binary.hs deleted file mode 100644 index 7c10419b5..000000000 --- a/src/pgf-binary/PGF/Data/Binary.hs +++ /dev/null @@ -1,489 +0,0 @@ -{-# LANGUAGE FlexibleInstances, FlexibleContexts #-} --- | This is a layer on top of "Data.Binary" with its own 'Binary' class --- and customised instances for 'Word', 'Int' and 'Double'. --- The 'Int' and 'Word' instance use a variable-length encoding to save space --- for small numbers. The 'Double' instance uses the standard IEEE754 encoding. -module PGF.Data.Binary ( - - -- * The Binary class - Binary(..) - - -- * The Get and Put monads - , Get , Put, runPut - - -- * Useful helpers for writing instances - , putWord8 , getWord8 , putWord16be , getWord16be - - -- * Binary serialisation - , encode , decode - - -- * IO functions for serialisation - , encodeFile , decodeFile - - , encodeFile_ , decodeFile_ - - -- * Useful - , Word8, Word16 - - ) where - - -import Data.Word - -import qualified Data.Binary as Bin -import Data.Binary.Put -import Data.Binary.Get -import Data.Binary.IEEE754 ( putFloat64be, getFloat64be) -import Control.Monad -import Control.Exception -import Foreign -import System.IO - -import Data.ByteString.Lazy (ByteString) -import qualified Data.ByteString.Lazy as L - ---import Data.Char (chr,ord) ---import Data.List (unfoldr) - --- And needed for the instances: -import qualified Data.ByteString as B -import qualified Data.Map as Map -import qualified Data.Set as Set -import qualified Data.IntMap as IntMap -import qualified Data.IntSet as IntSet ---import qualified Data.Ratio as R - ---import qualified Data.Tree as T - -import Data.Array.Unboxed - ------------------------------------------------------------------------- - --- | The @Binary@ class provides 'put' and 'get', methods to encode and --- decode a Haskell value to a lazy ByteString. It mirrors the Read and --- Show classes for textual representation of Haskell types, and is --- suitable for serialising Haskell values to disk, over the network. --- --- For parsing and generating simple external binary formats (e.g. C --- structures), Binary may be used, but in general is not suitable --- for complex protocols. Instead use the Put and Get primitives --- directly. --- --- Instances of Binary should satisfy the following property: --- --- > decode . encode == id --- --- That is, the 'get' and 'put' methods should be the inverse of each --- other. A range of instances are provided for basic Haskell types. --- -class Binary t where - -- | Encode a value in the Put monad. - put :: t -> Put - -- | Decode a value in the Get monad - get :: Get t - ------------------------------------------------------------------------- --- Wrappers to run the underlying monad - --- | Encode a value using binary serialisation to a lazy ByteString. --- -encode :: Binary a => a -> ByteString -encode = runPut . put -{-# INLINE encode #-} - --- | Decode a value from a lazy ByteString, reconstructing the original structure. --- -decode :: Binary a => ByteString -> a -decode = runGet get - ------------------------------------------------------------------------- --- Convenience IO operations - --- | Lazily serialise a value to a file --- --- This is just a convenience function, it's defined simply as: --- --- > encodeFile f = B.writeFile f . encode --- --- So for example if you wanted to compress as well, you could use: --- --- > B.writeFile f . compress . encode --- -encodeFile :: Binary a => FilePath -> a -> IO () -encodeFile f v = L.writeFile f (encode v) - -encodeFile_ :: FilePath -> Put -> IO () -encodeFile_ f m = L.writeFile f (runPut m) - --- | Lazily reconstruct a value previously written to a file. --- --- This is just a convenience function, it's defined simply as: --- --- > decodeFile f = return . decode =<< B.readFile f --- --- So for example if you wanted to decompress as well, you could use: --- --- > return . decode . decompress =<< B.readFile f --- -decodeFile :: Binary a => FilePath -> IO a -decodeFile f = bracket (openBinaryFile f ReadMode) hClose $ \h -> do - s <- L.hGetContents h - evaluate $ runGet get s - -decodeFile_ :: FilePath -> Get a -> IO a -decodeFile_ f m = bracket (openBinaryFile f ReadMode) hClose $ \h -> do - s <- L.hGetContents h - evaluate $ runGet m s - ------------------------------------------------------------------------- --- For ground types, the standard instances can be reused, --- but for container types it would imply using --- the standard instances for all types of values in the container... - -instance Binary () where put=Bin.put; get=Bin.get -instance Binary Bool where put=Bin.put; get=Bin.get -instance Binary Word8 where put=Bin.put; get=Bin.get -instance Binary Word16 where put=Bin.put; get=Bin.get -instance Binary Char where put=Bin.put; get=Bin.get - --- -- GF doesn't need these: ---instance Binary Ordering where put=Bin.put; get=Bin.get ---instance Binary Word32 where put=Bin.put; get=Bin.get ---instance Binary Word64 where put=Bin.put; get=Bin.get ---instance Binary Int8 where put=Bin.put; get=Bin.get ---instance Binary Int16 where put=Bin.put; get=Bin.get ---instance Binary Int32 where put=Bin.put; get=Bin.get - ---instance Binary Int64 where put=Bin.put; get=Bin.get -- needed by instance Binary ByteString - ------------------------------------------------------------------------- - --- Words are written as sequence of bytes. The last bit of each --- byte indicates whether there are more bytes to be read -instance Binary Word where - put i | i <= 0x7f = do put a - | i <= 0x3fff = do put (a .|. 0x80) - put b - | i <= 0x1fffff = do put (a .|. 0x80) - put (b .|. 0x80) - put c - | i <= 0xfffffff = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put d --- -- #if WORD_SIZE_IN_BITS < 64 - | otherwise = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put e -{- --- Restricted to 32 bits even on 64-bit systems, so that negative --- Ints are written as 5 bytes instead of 10 bytes (TH 2013-02-13) ---#else - | i <= 0x7ffffffff = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put e - | i <= 0x3ffffffffff = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put (e .|. 0x80) - put f - | i <= 0x1ffffffffffff = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put (e .|. 0x80) - put (f .|. 0x80) - put g - | i <= 0xffffffffffffff = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put (e .|. 0x80) - put (f .|. 0x80) - put (g .|. 0x80) - put h - | i <= 0xffffffffffffff = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put (e .|. 0x80) - put (f .|. 0x80) - put (g .|. 0x80) - put h - | i <= 0x7fffffffffffffff = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put (e .|. 0x80) - put (f .|. 0x80) - put (g .|. 0x80) - put (h .|. 0x80) - put j - | otherwise = do put (a .|. 0x80) - put (b .|. 0x80) - put (c .|. 0x80) - put (d .|. 0x80) - put (e .|. 0x80) - put (f .|. 0x80) - put (g .|. 0x80) - put (h .|. 0x80) - put (j .|. 0x80) - put k --- #endif --} - where - a = fromIntegral ( i .&. 0x7f) :: Word8 - b = fromIntegral (shiftR i 7 .&. 0x7f) :: Word8 - c = fromIntegral (shiftR i 14 .&. 0x7f) :: Word8 - d = fromIntegral (shiftR i 21 .&. 0x7f) :: Word8 - e = fromIntegral (shiftR i 28 .&. 0x7f) :: Word8 -{- - f = fromIntegral (shiftR i 35 .&. 0x7f) :: Word8 - g = fromIntegral (shiftR i 42 .&. 0x7f) :: Word8 - h = fromIntegral (shiftR i 49 .&. 0x7f) :: Word8 - j = fromIntegral (shiftR i 56 .&. 0x7f) :: Word8 - k = fromIntegral (shiftR i 63 .&. 0x7f) :: Word8 --} - get = do i <- getWord8 - (if i <= 0x7f - then return (fromIntegral i) - else do n <- get - return $ (n `shiftL` 7) .|. (fromIntegral (i .&. 0x7f))) - --- Int has the same representation as Word -instance Binary Int where - put i = put (fromIntegral i :: Word) - get = liftM toInt32 (get :: Get Word) - where - -- restrict to 32 bits (for PGF portability, TH 2013-02-13) - toInt32 w = fromIntegral (fromIntegral w::Int32)::Int - ------------------------------------------------------------------------- --- --- Portable, and pretty efficient, serialisation of Integer --- - --- Fixed-size type for a subset of Integer ---type SmallInt = Int32 - --- Integers are encoded in two ways: if they fit inside a SmallInt, --- they're written as a byte tag, and that value. If the Integer value --- is too large to fit in a SmallInt, it is written as a byte array, --- along with a sign and length field. -{- -instance Binary Integer where - - {-# INLINE put #-} - put n | n >= lo && n <= hi = do - putWord8 0 - put (fromIntegral n :: SmallInt) -- fast path - where - lo = fromIntegral (minBound :: SmallInt) :: Integer - hi = fromIntegral (maxBound :: SmallInt) :: Integer - - put n = do - putWord8 1 - put sign - put (unroll (abs n)) -- unroll the bytes - where - sign = fromIntegral (signum n) :: Word8 - - {-# INLINE get #-} - get = do - tag <- get :: Get Word8 - case tag of - 0 -> liftM fromIntegral (get :: Get SmallInt) - _ -> do sign <- get - bytes <- get - let v = roll bytes - return $! if sign == (1 :: Word8) then v else - v - --- --- Fold and unfold an Integer to and from a list of its bytes --- -unroll :: Integer -> [Word8] -unroll = unfoldr step - where - step 0 = Nothing - step i = Just (fromIntegral i, i `shiftR` 8) - -roll :: [Word8] -> Integer -roll = foldr unstep 0 - where - unstep b a = a `shiftL` 8 .|. fromIntegral b - -instance (Binary a,Integral a) => Binary (R.Ratio a) where - put r = put (R.numerator r) >> put (R.denominator r) - get = liftM2 (R.%) get get --} - ------------------------------------------------------------------------- --- Instances for the first few tuples - -instance (Binary a, Binary b) => Binary (a,b) where - put (a,b) = put a >> put b - get = liftM2 (,) get get - -instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where - put (a,b,c) = put a >> put b >> put c - get = liftM3 (,,) get get get - -instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where - put (a,b,c,d) = put a >> put b >> put c >> put d - get = liftM4 (,,,) get get get get - -instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d,e) where - put (a,b,c,d,e) = put a >> put b >> put c >> put d >> put e - get = liftM5 (,,,,) get get get get get - --- --- and now just recurse: --- - -instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f) - => Binary (a,b,c,d,e,f) where - put (a,b,c,d,e,f) = put (a,(b,c,d,e,f)) - get = do (a,(b,c,d,e,f)) <- get ; return (a,b,c,d,e,f) - -instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f, Binary g) - => Binary (a,b,c,d,e,f,g) where - put (a,b,c,d,e,f,g) = put (a,(b,c,d,e,f,g)) - get = do (a,(b,c,d,e,f,g)) <- get ; return (a,b,c,d,e,f,g) - -instance (Binary a, Binary b, Binary c, Binary d, Binary e, - Binary f, Binary g, Binary h) - => Binary (a,b,c,d,e,f,g,h) where - put (a,b,c,d,e,f,g,h) = put (a,(b,c,d,e,f,g,h)) - get = do (a,(b,c,d,e,f,g,h)) <- get ; return (a,b,c,d,e,f,g,h) - -instance (Binary a, Binary b, Binary c, Binary d, Binary e, - Binary f, Binary g, Binary h, Binary i) - => Binary (a,b,c,d,e,f,g,h,i) where - put (a,b,c,d,e,f,g,h,i) = put (a,(b,c,d,e,f,g,h,i)) - get = do (a,(b,c,d,e,f,g,h,i)) <- get ; return (a,b,c,d,e,f,g,h,i) - -instance (Binary a, Binary b, Binary c, Binary d, Binary e, - Binary f, Binary g, Binary h, Binary i, Binary j) - => Binary (a,b,c,d,e,f,g,h,i,j) where - put (a,b,c,d,e,f,g,h,i,j) = put (a,(b,c,d,e,f,g,h,i,j)) - get = do (a,(b,c,d,e,f,g,h,i,j)) <- get ; return (a,b,c,d,e,f,g,h,i,j) - ------------------------------------------------------------------------- --- Container types - -instance Binary a => Binary [a] where - put l = put (length l) >> mapM_ put l - get = do n <- get :: Get Int - xs <- replicateM n get - return xs - -instance (Binary a) => Binary (Maybe a) where - put Nothing = putWord8 0 - put (Just x) = putWord8 1 >> put x - get = do - w <- getWord8 - case w of - 0 -> return Nothing - _ -> liftM Just get - -instance (Binary a, Binary b) => Binary (Either a b) where - put (Left a) = putWord8 0 >> put a - put (Right b) = putWord8 1 >> put b - get = do - w <- getWord8 - case w of - 0 -> liftM Left get - _ -> liftM Right get - ------------------------------------------------------------------------- --- ByteStrings (have specially efficient instances) - -instance Binary B.ByteString where - put bs = do put (B.length bs) - putByteString bs - get = get >>= getByteString - --- --- Using old versions of fps, this is a type synonym, and non portable --- --- Requires 'flexible instances' --- -{- -instance Binary ByteString where - put bs = do put (fromIntegral (L.length bs) :: Int) - putLazyByteString bs - get = get >>= getLazyByteString --} ------------------------------------------------------------------------- --- Maps and Sets - -instance (Ord a, Binary a) => Binary (Set.Set a) where - put s = put (Set.size s) >> mapM_ put (Set.toAscList s) - get = liftM Set.fromDistinctAscList get - -instance (Ord k, Binary k, Binary e) => Binary (Map.Map k e) where - put m = put (Map.size m) >> mapM_ put (Map.toAscList m) - get = liftM Map.fromDistinctAscList get - -instance Binary IntSet.IntSet where - put s = put (IntSet.size s) >> mapM_ put (IntSet.toAscList s) - get = liftM IntSet.fromDistinctAscList get - -instance (Binary e) => Binary (IntMap.IntMap e) where - put m = put (IntMap.size m) >> mapM_ put (IntMap.toAscList m) - get = liftM IntMap.fromDistinctAscList get - ------------------------------------------------------------------------- --- Floating point - --- instance Binary Double where --- put d = put (decodeFloat d) --- get = liftM2 encodeFloat get get - -instance Binary Double where - put = putFloat64be - get = getFloat64be -{- -instance Binary Float where - put f = put (decodeFloat f) - get = liftM2 encodeFloat get get --} ------------------------------------------------------------------------- --- Trees -{- -instance (Binary e) => Binary (T.Tree e) where - put (T.Node r s) = put r >> put s - get = liftM2 T.Node get get --} ------------------------------------------------------------------------- --- Arrays - -instance (Binary i, Ix i, Binary e) => Binary (Array i e) where - put a = do - put (bounds a) - put (rangeSize $ bounds a) -- write the length - mapM_ put (elems a) -- now the elems. - get = do - bs <- get - n <- get -- read the length - xs <- replicateM n get -- now the elems. - return (listArray bs xs) - --- --- The IArray UArray e constraint is non portable. Requires flexible instances --- -instance (Binary i, Ix i, Binary e, IArray UArray e) => Binary (UArray i e) where - put a = do - put (bounds a) - put (rangeSize $ bounds a) -- now write the length - mapM_ put (elems a) - get = do - bs <- get - n <- get - xs <- replicateM n get - return (listArray bs xs) diff --git a/src/pgf-binary/pgf-binary.cabal b/src/pgf-binary/pgf-binary.cabal deleted file mode 100644 index 3f9bea896..000000000 --- a/src/pgf-binary/pgf-binary.cabal +++ /dev/null @@ -1,27 +0,0 @@ -name: pgf-binary -version: 0.5 - -cabal-version: >= 1.10 -build-type: Simple -license: BSD3 ---license-file: LICENSE -synopsis: Custom version of the binary-0.5 package for the PGF library -homepage: http://www.grammaticalframework.org/ ---bug-reports: http://code.google.com/p/grammatical-framework/issues/list -maintainer: Thomas Hallgren -stability: provisional -category: Data, Parsing -tested-with: GHC==7.4.2, GHC==7.8.3 - -source-repository head - type: darcs - location: http://www.grammaticalframework.org/ - -Library - default-language: Haskell2010 - build-depends: base >= 4.3 && <5, binary, data-binary-ieee754, - containers, array, bytestring - exposed-modules: PGF.Data.Binary - - ghc-options: -fwarn-unused-imports -O2 - extensions: FlexibleInstances, FlexibleContexts diff --git a/src/runtime/haskell-bind/PGF2/Internal.hsc b/src/runtime/haskell-bind/PGF2/Internal.hsc index c4aef323a..6582a9ada 100644 --- a/src/runtime/haskell-bind/PGF2/Internal.hsc +++ b/src/runtime/haskell-bind/PGF2/Internal.hsc @@ -12,6 +12,9 @@ module PGF2.Internal(-- * Access the internal structures build, eAbs, eApp, eMeta, eFun, eVar, eTyped, eImplArg, dTyp, hypo, AbstrInfo, newAbstr, ConcrInfo, newConcr, newPGF, + -- * Expose PGF and Concr for FFI with C + PGF(..), Concr(..), + -- * Write an in-memory PGF to a file writePGF ) where diff --git a/src/runtime/haskell/pgf.cabal b/src/runtime/haskell/pgf.cabal index 8a84dc278..76e12bd2c 100644 --- a/src/runtime/haskell/pgf.cabal +++ b/src/runtime/haskell/pgf.cabal @@ -1,5 +1,5 @@ name: pgf -version: 3.9.1-git +version: 3.10 cabal-version: >= 1.20 build-type: Simple @@ -12,11 +12,6 @@ bug-reports: https://github.com/GrammaticalFramework/gf-core/issues maintainer: Thomas Hallgren tested-with: GHC==7.6.3, GHC==7.8.3, GHC==7.10.3, GHC==8.0.2 -flag custom-binary - Description: Use a customised version of the binary package - Default: True - Manual: True - Library default-language: Haskell2010 build-depends: base >= 4.6 && <5, @@ -29,17 +24,14 @@ Library mtl, exceptions - if flag(custom-binary) - other-modules: - -- not really part of GF but I have changed the original binary library - -- and we have to keep the copy for now. - Data.Binary - Data.Binary.Put - Data.Binary.Get - Data.Binary.Builder - Data.Binary.IEEE754 - else - build-depends: binary, data-binary-ieee754 + other-modules: + -- not really part of GF but I have changed the original binary library + -- and we have to keep the copy for now. + Data.Binary + Data.Binary.Put + Data.Binary.Get + Data.Binary.Builder + Data.Binary.IEEE754 --ghc-options: -fwarn-unused-imports --if impl(ghc>=7.8) diff --git a/src/server/gf-server.cabal b/src/server/gf-server.cabal deleted file mode 100644 index 211f11683..000000000 --- a/src/server/gf-server.cabal +++ /dev/null @@ -1,118 +0,0 @@ -name: gf-server -version: 1.0 -cabal-version: >= 1.8 -build-type: Custom -license: GPL -license-file: ../../LICENSE -synopsis: FastCGI Server for Grammatical Framework - -flag content - Description: - Build content service (requires fastcgi and hsql-mysql packages) - (In Ubuntu: apt-get install libghc-fastcgi-dev libghc-hsql-mysql-dev) - Default: False - -flag http - Description: Build pgf-http (deprecated, replaced by gf -server) - Default: False - -flag fastcgi - Description: Build librar & pgf-service executable with fastcgi support - Default: True - -flag c-runtime - Description: Include functionality from the C run-time library (which must be installed already) - Default: False - -flag network-uri - description: Get Network.URI from the network-uri package - default: True - -Library - exposed-modules: PGFService FastCGIUtils CGIUtils ServeStaticFile RunHTTP Cache - other-modules: URLEncoding CGI Fold - hs-source-dirs: . transfer - - if flag(fastcgi) - build-depends: fastcgi >= 3001.0.2.2 - -- Install it in Ubuntu with: apt-get install libghc-fastcgi-dev - else - Buildable: False - - build-depends: base >=4.2 && <5, - time, time-compat, old-locale, - directory, - filepath, - containers, - process, - gf >= 3.6, - cgi >= 3001.1.7.3, - httpd-shed>=0.4.0.2, - mtl, - exceptions, - json >= 0.3.3, - utf8-string >= 0.3.1.1, - bytestring, - pretty, - random - - if flag(network-uri) - build-depends: network-uri>=2.6, network>=2.6 - else - build-depends: network>=2.3 && <2.6 - - ghc-options: -fwarn-unused-imports - if os(windows) - ghc-options: -optl-mwindows - else - build-depends: unix - - if flag(c-runtime) - cpp-options: -DC_RUNTIME - -executable pgf-http - main-is: pgf-http.hs - Hs-source-dirs: exec - ghc-options: -threaded - if impl(ghc>=7.0) - ghc-options: -rtsopts - - if flag(http) - buildable: True - build-depends: base >=4.2 && <5, gf-server, filepath, directory, cgi - else - buildable: False - -executable pgf-service - main-is: pgf-fcgi.hs - Hs-source-dirs: exec - ghc-options: -threaded -fwarn-unused-imports - if impl(ghc>=7.0) - ghc-options: -rtsopts - - if flag(fastcgi) - build-depends: fastcgi >= 3001.0.2.2 - -- Install it in Ubuntu with: apt-get install libghc-fastcgi-dev - else - Buildable: False - - build-depends: base >=4.2 && <5, gf-server - - if os(windows) - ghc-options: -optl-mwindows - else - build-depends: unix - -executable content-service - if flag(content) - build-depends: base >=4.2 && <5, old-locale, - fastcgi >= 3001.0.2.2, - -- In Ubuntu: apt-get install libghc-fastcgi-dev - hsql-mysql, hsql - -- In Ubuntu: apt-get install libghc-hsql-mysql-dev - buildable: True - else - buildable: False - - main-is: ContentService.hs - Hs-source-dirs: exec diff --git a/src/server/lighttpd.conf b/src/server/lighttpd.conf index a495d705b..88a016513 100644 --- a/src/server/lighttpd.conf +++ b/src/server/lighttpd.conf @@ -1,4 +1,4 @@ -# Run with (with -D for no-daemon) +# Run with (with -D for no-daemon) # /usr/sbin/lighttpd -f lighttpd.conf -D # @@ -10,8 +10,9 @@ server.modules = ( "mod_cgi" ) -var.basedir = var.CWD +var.basedir = var.CWD +# John: no longer valid after removing `src/ui` 2018-11-15 server.document-root = basedir + "/../ui/gwt/www" server.errorlog = basedir + "/error.log" @@ -96,4 +97,3 @@ static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" ) ## bind to port (default: 80) server.port = 41296 - diff --git a/src/tools/Htmls.hs b/src/tools/Htmls.hs deleted file mode 100644 index e4b7d4ccd..000000000 --- a/src/tools/Htmls.hs +++ /dev/null @@ -1,102 +0,0 @@ ----------------------------------------------------------------------- --- | --- Maintainer : AR --- Stability : (stable) --- Portability : (portable) --- --- > CVS $Date: 2005/05/16 17:07:18 $ --- > CVS $Author: aarne $ --- > CVS $Revision: 1.11 $ --- --- chop an HTML file into separate files, each linked to the next and previous. --- the names of the files are n-file, with n = 01,02,... --- the chopping is performed at each separator, here defined as @\" - -link :: FilePath -> Int -> Int -> String -link file mx n = - (if n >= mx-1 then "" else (" Next")) ++ - (if n == 1 then "" else (" Previous")) ++ - (" Contents") ++ - (" Fulltext") ++ - (" First") ++ - (" Last") - where - file_ = fileName file (n - 1) - file' = fileName file (n + 1) - file0 = fileName file 0 - file1 = fileName file 1 - file2 = fileName file (mx - 1) - -fileName :: FilePath -> Int -> FilePath -fileName file n = (if n < 10 then ('0':) else id) $ show n ++ "-" ++ file - -pageNum mx num = "

" ++ show num ++"/" ++ show (mx-1) ++ "

" - -mkIndex file = unlines . mkInd 1 where - mkInd n ss = case ss of - s : rest | (s==separator) -> mkInd (n+1) rest - s : rest -> case getHeading s of - Just (i,t) -> mkLine n i t : mkInd n rest - _ -> mkInd n rest - _ -> [] - getHeading s = case dropWhile isSpace s of - '<':h:i:_:t | isDigit i -> return (i,take (length t - 5) t) -- drop final - _ -> Nothing - mkLine _ '1' t = t ++ " : Table of Contents

" -- heading of whole document - mkLine n i t = stars i ++ link n t ++ "
" - stars i = case i of - '3' -> "

  • " - '4' -> "
  • * " - _ -> "" - link n t = "" ++ t ++ "" diff --git a/src/tools/gf-tools.cabal b/src/tools/gf-tools.cabal index 1f89f3a85..f8a9a1cde 100644 --- a/src/tools/gf-tools.cabal +++ b/src/tools/gf-tools.cabal @@ -6,7 +6,3 @@ cabal-version: >= 1.8 Executable gfdoc main-is: GFDoc.hs build-depends: base, directory>=1.2, time>=1.5, process - -Executable htmls - main-is: Htmls.hs - build-depends: base \ No newline at end of file diff --git a/src/ui/android/.classpath b/src/ui/android/.classpath deleted file mode 100644 index 7bc01d9a9..000000000 --- a/src/ui/android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/src/ui/android/.project b/src/ui/android/.project deleted file mode 100644 index abf063e43..000000000 --- a/src/ui/android/.project +++ /dev/null @@ -1,33 +0,0 @@ - - - GFTranslator - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - diff --git a/src/ui/android/AndroidManifest.xml b/src/ui/android/AndroidManifest.xml deleted file mode 100644 index 84b837a08..000000000 --- a/src/ui/android/AndroidManifest.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/LICENSE b/src/ui/android/LICENSE deleted file mode 100644 index cf90ceb14..000000000 --- a/src/ui/android/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ - BSD LICENSE - -Copyright (c) 1998, Grammatical Framework -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/src/ui/android/README b/src/ui/android/README deleted file mode 100644 index 7adb7fe50..000000000 --- a/src/ui/android/README +++ /dev/null @@ -1,68 +0,0 @@ -= Overview = - -This directory contains a sample Android app tht uses -the Android speech recognition and TTS APIs along with -JNI bindings to the C PGF runtime to implement a simple -speech translation app. - - -= Requirements = - -1. Android SDK: http://developer.android.com/sdk/ - installed in $ANDROID_SDK_LOCATION - -2. Android NDK: http://developer.android.com/tools/sdk/ndk/ - installed in $ANDROID_NDK_LOCATION - -= Building = - -Set up Android project: - -# Creates local.properties, not to be checked in -$ $ANDROID_SDK_LOCATION/tools/android update project -p . - -Build libs/libjpgf.jar: - -$ (cd ../../runtime/java && javac org/grammaticalframework/*/*.java && jar -cf ../../ui/android/libs/jpgf.jar org/grammaticalframework/*/*.class) - -Build JNI code: - -$ cd jni -$ $ANDROID_NDK_LOCATION/ndk-build - -Build the semantic database code: - -$ runghc glosses.hs - -Build APK: - -$ ant debug - - -Install on your device: - -$ ant debug install - -or: - -$ adb install -r bin/MainActivity-debug.apk - - -= Changing the grammar = - -1. Replace assets/ResourceDemo.pgf - -2. Edit Translator.java to point to the new file and include its metadata - - -= Developing in Eclipse = - -1. Install Android ADT - -2. Eclipse > File > Import > Existing Projects into Workspace > Next - -3. Select root directory... - -4. Select GF/src/ui/android - -5. Finish \ No newline at end of file diff --git a/src/ui/android/ant.properties b/src/ui/android/ant.properties deleted file mode 100644 index 59ddc9800..000000000 --- a/src/ui/android/ant.properties +++ /dev/null @@ -1,2 +0,0 @@ -key.store=/home/krasimir/dg/src/keys/dg_keystore -key.alias=dg diff --git a/src/ui/android/assets/help_content.html b/src/ui/android/assets/help_content.html deleted file mode 100644 index 279a2a963..000000000 --- a/src/ui/android/assets/help_content.html +++ /dev/null @@ -1,157 +0,0 @@ - - -

    -GF Offline Translator: -text and speech translation for 16 languages with -quality control. Version 19 April 2017 (beta). -

    -

    -Speech input: Tap microphone icon and talk while it is red. -
    -Text input: Select "keyboard" from menu, tap keyboard icon. -
    -Correction: Tap input text and edit. -
    -Alternatives: Tap output text. -
    -Grammar info: Tap any of the alternatives. -
    -Confidence: colour of output text -

      -
    • Green: semantic, probably correct (but has alternatives)
    • -
    • Yellow: syntactic, often incorrect (has alternatives)
    • -
    • Light red: chunk-based, probably incorrect (has alternatives)
    • -
    • Dark red: word-based, often very bad
    • -
    -
    -Topics (new, select from menu): Words grouped by semantic categories, with WordNet glosses. -
    -Phrasebook (new, select from menu): Conceptual authoring with the green translations. -

    - -
    - -

    More details

    -

    -GF Offline Translator is based on grammar and semantics. It is compact in size -and gives control on quality. Its technology is inspired by compilers, which are -programs that translate computer languages. -Most other translators for human language are based on -statistics and have less control of quality and are much bigger, so that -they require either an internet connection or a huge storage on your phone. -

    -The app indicates translation confidence with colours: -
      -
    • Green: - semantic translation, should be correct. - But not necessarily the only correct one. - You can tap the output to see alternatives. -
    • -
    • Yellow: - syntactic translation, should be grammatically correct. - But can be very strange in its interpretation and choice of words. -
    • -
    • Light red: - chunk translation, probably incorrect. - Builds the translation from small pieces. -
    • -
    • Dark red: - word-by-word translation, almost certainly incorrect. - Builds the translation word by word. -
    • -
    -The green translations come from a tourist phrasebook, which allows -you to translate things like "hello" and "how far is the airport from -the hotel". -

    - -

    -You can translate both speech and text, as selected in the menu in the -upper right corner. Both kinds of input can be edited with the -keyboard by first tapping at the input field. This is often needed -because of speech recognition errors. Changing words -from upper to lower case may also be needed. -At the moment, Japanese and Thai input must be separated -to words, whereas Chinese works without spaces. -

    -

    -Translation works between any of the 16 supported languages, which means 240 -language pairs in the current version. But different languages are on different levels of development. -The following table gives a rough idea of what to expect: -

    - -

    -

    - - - - - - - - - - - - - - - - - - -
    coverage quality speed speech
    Bulgarian in only
    Catalan
    Chinese
    Dutch
    English
    Estonian
    Finnish
    French
    German
    Hindi
    Italian
    Japanese*
    Russian
    Spanish
    Swedish
    Thai*
    -
    -* For translation from Japanese and Thai you need to separate each word with a space -

    -

    -The speech input and output use Google's voice services. Their status -can hence change without notice. You can make it more stable by -installing third-party speech tools, such as SVOX, which provides -output for most of the listed languages. -

    - -

    -When you tap on a translation you get a screen with alternative translations. -Tapping on each of the alternatives -gives you grammatical information: -an inflection table, if it is a single word, -and a syntax tree otherwise. -

    - -

    -The app also provides an input method which you can use as -an alternative keyboard which allows you to do translation from -other applications, for instance while you are entering SMS or e-mail. -To activate it go to Settings > Language & input. -

    - -

    -The translation works completely off-line, without -internet connection, when doing text-based translation. -Even speech works off-line in some languages, -but being on-line may give you better -speech input and output and more languages. -

    -

    -You can also install third-party off-line speech engines, such as -SVOX. -Consult the voice/language settings on your phone to find the optimal -speech engines, and restart the app after changing the settings. -

    - -

    -The GF Offline Translator is powered by -GF, Grammatical Framework. -It is open-source software, -built by support from the GF community and from Digital Grammars. -

    - -

    -Digital Grammars is a company that can tailor this app to you needs and provide good -translation for the kind of vocabulary you need. Just tell us what you want to see - in the green area! -

    - - - diff --git a/src/ui/android/assets/phrases.xml b/src/ui/android/assets/phrases.xml deleted file mode 100644 index 847339135..000000000 --- a/src/ui/android/assets/phrases.xml +++ /dev/null @@ -1,1035 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/build.xml b/src/ui/android/build.xml deleted file mode 100644 index d60bf62f2..000000000 --- a/src/ui/android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/gf-translator-alignment.dot b/src/ui/android/gf-translator-alignment.dot deleted file mode 100644 index 8eaaa72a5..000000000 --- a/src/ui/android/gf-translator-alignment.dot +++ /dev/null @@ -1,60 +0,0 @@ -digraph { - rankdir=LR ; - node [shape = record] ; - bgcolor = "#FFFFFF00" ; - - struct0[label = "твоÑÑ‚ | телефон | може | да | превежда"] ; - struct0:n0:e -> struct1:n0:w ; - struct0:n1:e -> struct1:n1:w ; - struct0:n2:e -> struct1:n2:w ; - struct0:n4:e -> struct1:n3:w ; - struct1[label = "el teu | telèfon | sap | traduir"] ; - struct1:n0:e -> struct2:n0:w ; - struct1:n1:e -> struct2:n2:w ; - struct1:n2:e -> struct2:n3:w ; - struct1:n3:e -> struct2:n4:w ; - struct2[label = "ä½  | çš„ | 电 è¯ | 会 | ç¿» 译"] ; - struct2:n0:e -> struct3:n0:w ; - struct2:n2:e -> struct3:n1:w ; - struct2:n3:e -> struct3:n2:w ; - struct2:n4:e -> struct3:n3:w ; - struct3[label = "je | telefoon | kan | vertalen"] ; - struct3:n0:e -> struct4:n0:w ; - struct3:n1:e -> struct4:n1:w ; - struct3:n2:e -> struct4:n2:w ; - struct3:n3:e -> struct4:n3:w ; - struct4[label = "your | phone | can | translate"] ; - struct4:n1:e -> struct5:n1:w ; - struct4:n2:e -> struct5:n2:w ; - struct4:n3:e -> struct5:n3:w ; - struct5[label = "puhelimesi | osaa | kääntää"] ; - struct5:n1:e -> struct6:n1:w ; - struct5:n2:e -> struct6:n2:w ; - struct5:n3:e -> struct6:n3:w ; - struct6[label = "ton | téléphone | sait | traduire"] ; - struct6:n0:e -> struct7:n0:w ; - struct6:n1:e -> struct7:n1:w ; - struct6:n2:e -> struct7:n2:w ; - struct6:n3:e -> struct7:n3:w ; - struct7[label = "dein | Telefon | kann | übersetzen"] ; - struct7:n0:e -> struct8:n0:w ; - struct7:n1:e -> struct8:n1:w ; - struct7:n2:e -> struct8:n3:w ; - struct7:n3:e -> struct8:n2:w ; - struct8[label = "तà¥à¤®à¥à¤¹à¤¾à¤°à¤¾ | फोन | अनà¥à¤µà¤¾à¤¦ कर | सकता | है"] ; - struct8:n0:e -> struct9:n1:w ; - struct8:n1:e -> struct9:n2:w ; - struct8:n2:e -> struct9:n4:w ; - struct8:n3:e -> struct9:n3:w ; - struct9[label = "il | tuo | telefono | sa | tradurre"] ; - struct9:n1:e -> struct10:n0:w ; - struct9:n2:e -> struct10:n1:w ; - struct9:n3:e -> struct10:n2:w ; - struct9:n4:e -> struct10:n3:w ; - struct10[label = "tu | teléfono | sabe | traducir"] ; - struct10:n0:e -> struct11:n0:w ; - struct10:n1:e -> struct11:n1:w ; - struct10:n2:e -> struct11:n2:w ; - struct10:n3:e -> struct11:n3:w ; - struct11[label = "din | telefon | kan | översätta"] ; -} diff --git a/src/ui/android/gf-translator.svg b/src/ui/android/gf-translator.svg deleted file mode 100644 index 21eee477d..000000000 --- a/src/ui/android/gf-translator.svg +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - Offline Translation - with - Grammatical Framework - Grammatical Framework - - diff --git a/src/ui/android/glosses.hs b/src/ui/android/glosses.hs deleted file mode 100644 index 966ec90aa..000000000 --- a/src/ui/android/glosses.hs +++ /dev/null @@ -1,46 +0,0 @@ -import SG -import PGF2 -import Data.Char -import Data.List - -main = do - db <- openSG "assets/semantics.db" - inTransaction db $ do - ls <- fmap lines $ readFile "../../../lib/src/translator/Dictionary.gf" - let glosses = [x | Just (fn,gloss) <- map gloss ls, x <- glossTriples fn gloss] - topics <- fmap (map toTriple . lines) $ readFile "topics.txt" - sequence_ [insertTriple db s p o | (s,p,o) <- glosses++topics] - closeSG db - -toTriple l = - case readTriple l of - Just t -> t - Nothing -> error ("topics.txt: "++l) - -gloss l = - case words l of - ("fun":fn:_) -> case dropWhile (/='\t') l of - '\t':l -> Just (fn,l) - _ -> Nothing - _ -> Nothing - -glossTriples fn s = - (if null gs then [] else [(fn_e,gloss,mkStr (merge gs))])++ - (if null es then [] else [(fn_e,example,mkStr (merge (map (init . tail) es)))]) - where - fn_e = mkApp fn [] - gloss = mkApp "gloss" [] - example = mkApp "example" [] - (es,gs) = partition isExample (splitGloss s) - -splitGloss s = - let (xs,s') = break (==';') s - in trim xs : case s' of - ';':s -> splitGloss s - _ -> [] - where - trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace - -merge = intercalate "; " - -isExample s = not (null s) && head s == '"' && last s == '"' diff --git a/src/ui/android/hlc.svg b/src/ui/android/hlc.svg deleted file mode 100644 index e61e41c19..000000000 --- a/src/ui/android/hlc.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - Digital Grammar Logo - - - diff --git a/src/ui/android/jni/Android.mk b/src/ui/android/jni/Android.mk deleted file mode 100644 index f1f697bed..000000000 --- a/src/ui/android/jni/Android.mk +++ /dev/null @@ -1,28 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -jni_c_files := jpgf.c jsg.c jni_utils.c -sg_c_files := sg.c sqlite3Btree.c -pgf_c_files := data.c expr.c graphviz.c linearizer.c literals.c parser.c parseval.c pgf.c printer.c reader.c \ -reasoner.c evaluator.c jit.c typechecker.c lookup.c aligner.c writer.c -gu_c_files := assert.c choice.c exn.c fun.c in.c map.c out.c utf8.c \ -bits.c defs.c enum.c file.c hash.c mem.c prime.c seq.c string.c ucs.c variant.c - -LOCAL_MODULE := jpgf -LOCAL_SRC_FILES := $(addprefix ../../../runtime/java/, $(jni_c_files)) \ - $(addprefix ../../../runtime/c/sg/, $(sg_c_files)) \ - $(addprefix ../../../runtime/c/pgf/, $(pgf_c_files)) \ - $(addprefix ../../../runtime/c/gu/, $(gu_c_files)) -LOCAL_C_INCLUDES := ../../../runtime/c - -include $(BUILD_SHARED_LIBRARY) - -$(realpath ../obj/local/armeabi/objs/jpgf/__/__/__/runtime/c/pgf/jit.o): lightning -$(realpath ../obj/local/armeabi/objs-debug/jpgf/__/__/__/runtime/c/pgf/jit.o): lightning - -lightning: - ln -s -f arm/asm.h ../../../runtime/c/pgf/lightning/asm.h - ln -s -f arm/core.h ../../../runtime/c/pgf/lightning/core.h - ln -s -f arm/fp.h ../../../runtime/c/pgf/lightning/fp.h - ln -s -f arm/funcs.h ../../../runtime/c/pgf/lightning/funcs.h diff --git a/src/ui/android/jni/Application.mk b/src/ui/android/jni/Application.mk deleted file mode 100644 index 6a9876332..000000000 --- a/src/ui/android/jni/Application.mk +++ /dev/null @@ -1,3 +0,0 @@ -APP_PLATFORM := android-8 -APP_CFLAGS := -std=gnu99 -APP_OPTIM := release diff --git a/src/ui/android/proguard-project.txt b/src/ui/android/proguard-project.txt deleted file mode 100644 index f2fe1559a..000000000 --- a/src/ui/android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/src/ui/android/project.properties b/src/ui/android/project.properties deleted file mode 100644 index 6e18427a4..000000000 --- a/src/ui/android/project.properties +++ /dev/null @@ -1,14 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system edit -# "ant.properties", and override values to adapt the script to your -# project structure. -# -# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): -#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt - -# Project target. -target=android-21 diff --git a/src/ui/android/res/drawable-hdpi/btn_close.png b/src/ui/android/res/drawable-hdpi/btn_close.png deleted file mode 100644 index 47f11e5bf..000000000 Binary files a/src/ui/android/res/drawable-hdpi/btn_close.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/close_arrow.png b/src/ui/android/res/drawable-hdpi/close_arrow.png deleted file mode 100644 index bf280a05a..000000000 Binary files a/src/ui/android/res/drawable-hdpi/close_arrow.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/ic_action_switch.png b/src/ui/android/res/drawable-hdpi/ic_action_switch.png deleted file mode 100644 index 5449a32b8..000000000 Binary files a/src/ui/android/res/drawable-hdpi/ic_action_switch.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/ic_app.png b/src/ui/android/res/drawable-hdpi/ic_app.png deleted file mode 100644 index 8d9bdd820..000000000 Binary files a/src/ui/android/res/drawable-hdpi/ic_app.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/ic_drawer.png b/src/ui/android/res/drawable-hdpi/ic_drawer.png deleted file mode 100644 index c59f601ca..000000000 Binary files a/src/ui/android/res/drawable-hdpi/ic_drawer.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/ic_keyboard.png b/src/ui/android/res/drawable-hdpi/ic_keyboard.png deleted file mode 100644 index ce257a269..000000000 Binary files a/src/ui/android/res/drawable-hdpi/ic_keyboard.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/ic_mic.png b/src/ui/android/res/drawable-hdpi/ic_mic.png deleted file mode 100644 index f79ff489b..000000000 Binary files a/src/ui/android/res/drawable-hdpi/ic_mic.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/ic_search_black_24dp.png b/src/ui/android/res/drawable-hdpi/ic_search_black_24dp.png deleted file mode 100644 index c593e7ad8..000000000 Binary files a/src/ui/android/res/drawable-hdpi/ic_search_black_24dp.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/open_arrow.png b/src/ui/android/res/drawable-hdpi/open_arrow.png deleted file mode 100644 index ec7453797..000000000 Binary files a/src/ui/android/res/drawable-hdpi/open_arrow.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/sym_keyboard_delete.png b/src/ui/android/res/drawable-hdpi/sym_keyboard_delete.png deleted file mode 100644 index 5139c7179..000000000 Binary files a/src/ui/android/res/drawable-hdpi/sym_keyboard_delete.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/sym_keyboard_return.png b/src/ui/android/res/drawable-hdpi/sym_keyboard_return.png deleted file mode 100644 index 5a5670c32..000000000 Binary files a/src/ui/android/res/drawable-hdpi/sym_keyboard_return.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/sym_keyboard_search.png b/src/ui/android/res/drawable-hdpi/sym_keyboard_search.png deleted file mode 100644 index e72cde3bb..000000000 Binary files a/src/ui/android/res/drawable-hdpi/sym_keyboard_search.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/sym_keyboard_shift.png b/src/ui/android/res/drawable-hdpi/sym_keyboard_shift.png deleted file mode 100644 index 275769618..000000000 Binary files a/src/ui/android/res/drawable-hdpi/sym_keyboard_shift.png and /dev/null differ diff --git a/src/ui/android/res/drawable-hdpi/sym_keyboard_space.png b/src/ui/android/res/drawable-hdpi/sym_keyboard_space.png deleted file mode 100644 index cef2daa5d..000000000 Binary files a/src/ui/android/res/drawable-hdpi/sym_keyboard_space.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/ic_action_switch.png b/src/ui/android/res/drawable-mdpi/ic_action_switch.png deleted file mode 100644 index ecf7d0347..000000000 Binary files a/src/ui/android/res/drawable-mdpi/ic_action_switch.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/ic_app.png b/src/ui/android/res/drawable-mdpi/ic_app.png deleted file mode 100644 index 923d0fe91..000000000 Binary files a/src/ui/android/res/drawable-mdpi/ic_app.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/ic_drawer.png b/src/ui/android/res/drawable-mdpi/ic_drawer.png deleted file mode 100644 index 1ed2c56ee..000000000 Binary files a/src/ui/android/res/drawable-mdpi/ic_drawer.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/ic_mic.png b/src/ui/android/res/drawable-mdpi/ic_mic.png deleted file mode 100644 index 8f7f55cf9..000000000 Binary files a/src/ui/android/res/drawable-mdpi/ic_mic.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/ic_search_black_24dp.png b/src/ui/android/res/drawable-mdpi/ic_search_black_24dp.png deleted file mode 100644 index 6b1634323..000000000 Binary files a/src/ui/android/res/drawable-mdpi/ic_search_black_24dp.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/sym_keyboard_delete.png b/src/ui/android/res/drawable-mdpi/sym_keyboard_delete.png deleted file mode 100644 index 6cee59682..000000000 Binary files a/src/ui/android/res/drawable-mdpi/sym_keyboard_delete.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/sym_keyboard_done.png b/src/ui/android/res/drawable-mdpi/sym_keyboard_done.png deleted file mode 100644 index c0d6d1394..000000000 Binary files a/src/ui/android/res/drawable-mdpi/sym_keyboard_done.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/sym_keyboard_return.png b/src/ui/android/res/drawable-mdpi/sym_keyboard_return.png deleted file mode 100644 index cbe2b152f..000000000 Binary files a/src/ui/android/res/drawable-mdpi/sym_keyboard_return.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/sym_keyboard_search.png b/src/ui/android/res/drawable-mdpi/sym_keyboard_search.png deleted file mode 100644 index 127755d6b..000000000 Binary files a/src/ui/android/res/drawable-mdpi/sym_keyboard_search.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/sym_keyboard_shift.png b/src/ui/android/res/drawable-mdpi/sym_keyboard_shift.png deleted file mode 100644 index d05962846..000000000 Binary files a/src/ui/android/res/drawable-mdpi/sym_keyboard_shift.png and /dev/null differ diff --git a/src/ui/android/res/drawable-mdpi/sym_keyboard_space.png b/src/ui/android/res/drawable-mdpi/sym_keyboard_space.png deleted file mode 100644 index 09b94d9e6..000000000 Binary files a/src/ui/android/res/drawable-mdpi/sym_keyboard_space.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xhdpi/ic_action_switch.png b/src/ui/android/res/drawable-xhdpi/ic_action_switch.png deleted file mode 100644 index b5da00fb2..000000000 Binary files a/src/ui/android/res/drawable-xhdpi/ic_action_switch.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xhdpi/ic_app.png b/src/ui/android/res/drawable-xhdpi/ic_app.png deleted file mode 100644 index f7eb06682..000000000 Binary files a/src/ui/android/res/drawable-xhdpi/ic_app.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xhdpi/ic_dictionary.png b/src/ui/android/res/drawable-xhdpi/ic_dictionary.png deleted file mode 100644 index 985644ebd..000000000 Binary files a/src/ui/android/res/drawable-xhdpi/ic_dictionary.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xhdpi/ic_drawer.png b/src/ui/android/res/drawable-xhdpi/ic_drawer.png deleted file mode 100644 index a5fa74def..000000000 Binary files a/src/ui/android/res/drawable-xhdpi/ic_drawer.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xhdpi/ic_mic.png b/src/ui/android/res/drawable-xhdpi/ic_mic.png deleted file mode 100644 index 13d21274a..000000000 Binary files a/src/ui/android/res/drawable-xhdpi/ic_mic.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xhdpi/ic_search_black_24dp.png b/src/ui/android/res/drawable-xhdpi/ic_search_black_24dp.png deleted file mode 100644 index 638190268..000000000 Binary files a/src/ui/android/res/drawable-xhdpi/ic_search_black_24dp.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xxhdpi/ic_app.png b/src/ui/android/res/drawable-xxhdpi/ic_app.png deleted file mode 100644 index 6154d852a..000000000 Binary files a/src/ui/android/res/drawable-xxhdpi/ic_app.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xxhdpi/ic_drawer.png b/src/ui/android/res/drawable-xxhdpi/ic_drawer.png deleted file mode 100644 index 9c4685d6e..000000000 Binary files a/src/ui/android/res/drawable-xxhdpi/ic_drawer.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xxhdpi/ic_search_black_24dp.png b/src/ui/android/res/drawable-xxhdpi/ic_search_black_24dp.png deleted file mode 100644 index 3ae490ef9..000000000 Binary files a/src/ui/android/res/drawable-xxhdpi/ic_search_black_24dp.png and /dev/null differ diff --git a/src/ui/android/res/drawable-xxxhdpi/ic_search_black_24dp.png b/src/ui/android/res/drawable-xxxhdpi/ic_search_black_24dp.png deleted file mode 100644 index 21be57299..000000000 Binary files a/src/ui/android/res/drawable-xxxhdpi/ic_search_black_24dp.png and /dev/null differ diff --git a/src/ui/android/res/drawable/first_person_utterance_bg.xml b/src/ui/android/res/drawable/first_person_utterance_bg.xml deleted file mode 100644 index acdf9ab92..000000000 --- a/src/ui/android/res/drawable/first_person_utterance_bg.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/ui/android/res/drawable/grid_phrasebook_button.xml b/src/ui/android/res/drawable/grid_phrasebook_button.xml deleted file mode 100644 index 21a6ac127..000000000 --- a/src/ui/android/res/drawable/grid_phrasebook_button.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/ui/android/res/drawable/ic_volume_up_black_18dp.png b/src/ui/android/res/drawable/ic_volume_up_black_18dp.png deleted file mode 100644 index 992d2c452..000000000 Binary files a/src/ui/android/res/drawable/ic_volume_up_black_18dp.png and /dev/null differ diff --git a/src/ui/android/res/drawable/second_person_best_utterance_bg.xml b/src/ui/android/res/drawable/second_person_best_utterance_bg.xml deleted file mode 100644 index 0c60864b9..000000000 --- a/src/ui/android/res/drawable/second_person_best_utterance_bg.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/ui/android/res/drawable/second_person_chunk_utterance_bg.xml b/src/ui/android/res/drawable/second_person_chunk_utterance_bg.xml deleted file mode 100644 index d10d67122..000000000 --- a/src/ui/android/res/drawable/second_person_chunk_utterance_bg.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/ui/android/res/drawable/second_person_utterance_bg.xml b/src/ui/android/res/drawable/second_person_utterance_bg.xml deleted file mode 100644 index e07cc10b3..000000000 --- a/src/ui/android/res/drawable/second_person_utterance_bg.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/ui/android/res/drawable/second_person_worst_utterance_bg.xml b/src/ui/android/res/drawable/second_person_worst_utterance_bg.xml deleted file mode 100644 index f4effe3bc..000000000 --- a/src/ui/android/res/drawable/second_person_worst_utterance_bg.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/ui/android/res/layout/activity_help.xml b/src/ui/android/res/layout/activity_help.xml deleted file mode 100644 index 3cb88a569..000000000 --- a/src/ui/android/res/layout/activity_help.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - diff --git a/src/ui/android/res/layout/activity_lexical_entry.xml b/src/ui/android/res/layout/activity_lexical_entry.xml deleted file mode 100644 index fa49f252b..000000000 --- a/src/ui/android/res/layout/activity_lexical_entry.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/layout/activity_main.xml b/src/ui/android/res/layout/activity_main.xml deleted file mode 100644 index b77fe5857..000000000 --- a/src/ui/android/res/layout/activity_main.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ui/android/res/layout/activity_navigation.xml b/src/ui/android/res/layout/activity_navigation.xml deleted file mode 100644 index 44311b90d..000000000 --- a/src/ui/android/res/layout/activity_navigation.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - diff --git a/src/ui/android/res/layout/activity_semantic_graph.xml b/src/ui/android/res/layout/activity_semantic_graph.xml deleted file mode 100644 index 004e22a7c..000000000 --- a/src/ui/android/res/layout/activity_semantic_graph.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/layout/alternative_item.xml b/src/ui/android/res/layout/alternative_item.xml deleted file mode 100644 index f35d1b938..000000000 --- a/src/ui/android/res/layout/alternative_item.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/src/ui/android/res/layout/checkbox_input_list_item.xml b/src/ui/android/res/layout/checkbox_input_list_item.xml deleted file mode 100644 index 255d0ae8d..000000000 --- a/src/ui/android/res/layout/checkbox_input_list_item.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/src/ui/android/res/layout/first_person_utterance.xml b/src/ui/android/res/layout/first_person_utterance.xml deleted file mode 100644 index 97171149c..000000000 --- a/src/ui/android/res/layout/first_person_utterance.xml +++ /dev/null @@ -1,11 +0,0 @@ - - diff --git a/src/ui/android/res/layout/fragment_phrase_list.xml b/src/ui/android/res/layout/fragment_phrase_list.xml deleted file mode 100644 index 1868da31c..000000000 --- a/src/ui/android/res/layout/fragment_phrase_list.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - diff --git a/src/ui/android/res/layout/fragment_translator.xml b/src/ui/android/res/layout/fragment_translator.xml deleted file mode 100644 index 6b6584f98..000000000 --- a/src/ui/android/res/layout/fragment_translator.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/layout/input.xml b/src/ui/android/res/layout/input.xml deleted file mode 100644 index fdef07a53..000000000 --- a/src/ui/android/res/layout/input.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/src/ui/android/res/layout/keyboard_languages_options.xml b/src/ui/android/res/layout/keyboard_languages_options.xml deleted file mode 100644 index 17512df19..000000000 --- a/src/ui/android/res/layout/keyboard_languages_options.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/ui/android/res/layout/languages_item.xml b/src/ui/android/res/layout/languages_item.xml deleted file mode 100644 index d5f47ab27..000000000 --- a/src/ui/android/res/layout/languages_item.xml +++ /dev/null @@ -1,8 +0,0 @@ - - diff --git a/src/ui/android/res/layout/lexical_item.xml b/src/ui/android/res/layout/lexical_item.xml deleted file mode 100644 index 1d3835e54..000000000 --- a/src/ui/android/res/layout/lexical_item.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - diff --git a/src/ui/android/res/layout/number_input_list_item.xml b/src/ui/android/res/layout/number_input_list_item.xml deleted file mode 100644 index a3cfa07e5..000000000 --- a/src/ui/android/res/layout/number_input_list_item.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/src/ui/android/res/layout/phrase_list_item.xml b/src/ui/android/res/layout/phrase_list_item.xml deleted file mode 100644 index f812ad871..000000000 --- a/src/ui/android/res/layout/phrase_list_item.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - diff --git a/src/ui/android/res/layout/second_person_utterance.xml b/src/ui/android/res/layout/second_person_utterance.xml deleted file mode 100644 index 416d85328..000000000 --- a/src/ui/android/res/layout/second_person_utterance.xml +++ /dev/null @@ -1,12 +0,0 @@ - - diff --git a/src/ui/android/res/layout/spinner_input_list_item.xml b/src/ui/android/res/layout/spinner_input_list_item.xml deleted file mode 100644 index be07004f4..000000000 --- a/src/ui/android/res/layout/spinner_input_list_item.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - diff --git a/src/ui/android/res/menu/main.xml b/src/ui/android/res/menu/main.xml deleted file mode 100644 index f36095749..000000000 --- a/src/ui/android/res/menu/main.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - diff --git a/src/ui/android/res/values-sw600dp/dimens.xml b/src/ui/android/res/values-sw600dp/dimens.xml deleted file mode 100644 index 44f01db75..000000000 --- a/src/ui/android/res/values-sw600dp/dimens.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - diff --git a/src/ui/android/res/values-sw720dp-land/dimens.xml b/src/ui/android/res/values-sw720dp-land/dimens.xml deleted file mode 100644 index 61e3fa8fb..000000000 --- a/src/ui/android/res/values-sw720dp-land/dimens.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - 128dp - - diff --git a/src/ui/android/res/values-v11/styles.xml b/src/ui/android/res/values-v11/styles.xml deleted file mode 100644 index 3c02242ad..000000000 --- a/src/ui/android/res/values-v11/styles.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - diff --git a/src/ui/android/res/values-v14/styles.xml b/src/ui/android/res/values-v14/styles.xml deleted file mode 100644 index a91fd0372..000000000 --- a/src/ui/android/res/values-v14/styles.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/src/ui/android/res/values/attrs.xml b/src/ui/android/res/values/attrs.xml deleted file mode 100644 index debd08fa0..000000000 --- a/src/ui/android/res/values/attrs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/src/ui/android/res/values/colors.xml b/src/ui/android/res/values/colors.xml deleted file mode 100644 index e7dbbada4..000000000 --- a/src/ui/android/res/values/colors.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - #FF000000 - #FFE35900 - #ff808080 - #ffffffff - #75CD75 - #616161 - diff --git a/src/ui/android/res/values/dimens.xml b/src/ui/android/res/values/dimens.xml deleted file mode 100644 index 04289dc79..000000000 --- a/src/ui/android/res/values/dimens.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - 16dp - 16dp - 50dip - 25sp - 6sp - - diff --git a/src/ui/android/res/values/strings.xml b/src/ui/android/res/values/strings.xml deleted file mode 100644 index 8281a1353..000000000 --- a/src/ui/android/res/values/strings.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - GF Offline Translator - - Microphone - Switch languages - Opening - Speech Input - Keyboard Input - Semantic Graph - Help - org.grammaticalframework.ui.android.GLOBAL_PREFERENCES - - authority_key - source_key - target_key - alternatives_key - - - Done - Go - Next - Previous - Send - - - normalKeyboardMode - internalKeyboardMode - - Search word: - Search for words in the lexicon - - Topics - Open topics - Close topics - - Phrasebook - diff --git a/src/ui/android/res/values/styles.xml b/src/ui/android/res/values/styles.xml deleted file mode 100644 index c839d30a9..000000000 --- a/src/ui/android/res/values/styles.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - diff --git a/src/ui/android/res/xml/cyrillic.xml b/src/ui/android/res/xml/cyrillic.xml deleted file mode 100644 index b699d9c19..000000000 --- a/src/ui/android/res/xml/cyrillic.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/xml/devanagari_page1.xml b/src/ui/android/res/xml/devanagari_page1.xml deleted file mode 100644 index 14e87a4f3..000000000 --- a/src/ui/android/res/xml/devanagari_page1.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ui/android/res/xml/devanagari_page2.xml b/src/ui/android/res/xml/devanagari_page2.xml deleted file mode 100644 index 982adb277..000000000 --- a/src/ui/android/res/xml/devanagari_page2.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - "आ" - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ui/android/res/xml/method.xml b/src/ui/android/res/xml/method.xml deleted file mode 100644 index af83761ca..000000000 --- a/src/ui/android/res/xml/method.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/src/ui/android/res/xml/nordic.xml b/src/ui/android/res/xml/nordic.xml deleted file mode 100644 index 80b1d6e51..000000000 --- a/src/ui/android/res/xml/nordic.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/xml/popup_keyboard.xml b/src/ui/android/res/xml/popup_keyboard.xml deleted file mode 100644 index 521d3d278..000000000 --- a/src/ui/android/res/xml/popup_keyboard.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - \ No newline at end of file diff --git a/src/ui/android/res/xml/qwerty.xml b/src/ui/android/res/xml/qwerty.xml deleted file mode 100644 index a0021d4b4..000000000 --- a/src/ui/android/res/xml/qwerty.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/xml/searchable.xml b/src/ui/android/res/xml/searchable.xml deleted file mode 100644 index 7e7b6a846..000000000 --- a/src/ui/android/res/xml/searchable.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/src/ui/android/res/xml/symbols_page1.xml b/src/ui/android/res/xml/symbols_page1.xml deleted file mode 100644 index 509bb79ae..000000000 --- a/src/ui/android/res/xml/symbols_page1.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ui/android/res/xml/symbols_page2.xml b/src/ui/android/res/xml/symbols_page2.xml deleted file mode 100644 index b55e6f521..000000000 --- a/src/ui/android/res/xml/symbols_page2.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/xml/thai_page1.xml b/src/ui/android/res/xml/thai_page1.xml deleted file mode 100644 index bcc2aee39..000000000 --- a/src/ui/android/res/xml/thai_page1.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/res/xml/thai_page2.xml b/src/ui/android/res/xml/thai_page2.xml deleted file mode 100644 index 00e76f525..000000000 --- a/src/ui/android/res/xml/thai_page2.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/ASR.java b/src/ui/android/src/org/grammaticalframework/ui/android/ASR.java deleted file mode 100644 index 8d683e1f5..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/ASR.java +++ /dev/null @@ -1,240 +0,0 @@ - -package org.grammaticalframework.ui.android; - -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.speech.RecognitionListener; -import android.speech.RecognizerIntent; -import android.speech.SpeechRecognizer; -import android.text.TextUtils; -import android.util.Log; - -import java.util.ArrayList; - -/** - * Convenience wrapper around the {@link SpeechRecognizer} API. - */ -public class ASR { - - private static final boolean DBG = false; - private static final String TAG = "ASR"; - - private final Context mContext; - - private SpeechRecognizer mSpeechRecognizer; - - private String mLanguage = null; - - private State mState = State.IDLE; - - private Listener mListener; - - public static enum State { - IDLE, INITIALIZING, WAITING_FOR_SPEECH, RECORDING, WAITING_FOR_RESULTS; - } - - public ASR(Context context) { - mContext = context; - if (SpeechRecognizer.isRecognitionAvailable(context)) { - mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(context); - mSpeechRecognizer.setRecognitionListener(new MyRecognitionListener()); - } - } - - public void setListener(Listener listener) { - mListener = listener; - } - - public void setLanguage(String language) { - mLanguage = language; - } - - public void startRecognition() { - Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); - if (!TextUtils.isEmpty(mLanguage)) { - intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, mLanguage); - } - intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, - RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); - intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 2); - intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); - // Weird, this shouldn't be required, but on ICS it seems to be - intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, - mContext.getPackageName()); - - mSpeechRecognizer.startListening(intent); - setState(State.INITIALIZING); - } - - public void stopRecognition() { - mSpeechRecognizer.stopListening(); - setState(State.IDLE); - } - - public boolean isRunning() { - return mState != State.IDLE; - } - - private void setState(State newState) { - if (DBG) Log.d(TAG, "Entering state: " + newState); - mState = newState; - if (mListener != null) { - mListener.onStateChanged(mState); - } - } - - public State getState() { - return mState; - } - - public void destroy() { - if (mSpeechRecognizer != null) { - mSpeechRecognizer.destroy(); - mSpeechRecognizer = null; - } - } - - private void handlePartialInput(String text) { - if (mListener != null) { - mListener.onPartialInput(text); - } - } - - private void handleSpeechInput(String text) { - if (mListener != null) { - mListener.onSpeechInput(text); - } - } - - private class MyRecognitionListener implements RecognitionListener { - @Override - public void onReadyForSpeech(Bundle params) { - if (DBG) Log.d(TAG, "onReadyForSpeech"); - setState(State.WAITING_FOR_SPEECH); - } - - @Override - public void onBeginningOfSpeech() { - if (DBG) Log.d(TAG, "onBeginningOfSpeech"); - setState(State.RECORDING); - } - - @Override - public void onBufferReceived(byte[] buffer) { - // Ignore - } - - @Override - public void onRmsChanged(float rmsdB) { - if (DBG) Log.d(TAG, "onRmsChanged(" + rmsdB + ")"); - } - - @Override - public void onEndOfSpeech() { - if (DBG) Log.d(TAG, "onEndOfSpeech"); - setState(State.WAITING_FOR_RESULTS); - } - - @Override - public void onError(int error) { - if (DBG) Log.d(TAG, "Error: " + errorMessage(error) + " (" + error + ")"); - setState(State.IDLE); - } - - private String errorMessage(int speechRecognizerError) { - switch(speechRecognizerError) { - case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: - return "network timeout"; - case SpeechRecognizer.ERROR_NETWORK: - return "network"; - case SpeechRecognizer.ERROR_AUDIO: - return "audio"; - case SpeechRecognizer.ERROR_SERVER: - return "server"; - case SpeechRecognizer.ERROR_CLIENT: - return "client"; - case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: - return "timeout waiting for speech"; - case SpeechRecognizer.ERROR_NO_MATCH: - return "no match found"; - case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: - return "recognizer busy"; - case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: - return "insufficient permissions (missing RECORD_AUDIO?)"; - default: - return "unknown"; - } - } - - @Override - public void onEvent(int eventType, Bundle params) { - if (DBG) Log.d(TAG, "onEvent(" + eventType + ")"); - } - - @Override - public void onPartialResults(Bundle bundle) { - if (DBG) { - StringBuilder sb = new StringBuilder(); - sb.append("onPartialResults:"); - appendResults(sb, bundle); - Log.d(TAG, sb.toString()); - } - - String result = getResult(bundle); - if (!TextUtils.isEmpty(result)) { - handlePartialInput(result); - } - } - - @Override - public void onResults(Bundle bundle) { - if (DBG) { - StringBuilder sb = new StringBuilder(); - sb.append("onResults:"); - appendResults(sb, bundle); - Log.d(TAG, sb.toString()); - } - - setState(State.IDLE); - - String result = getResult(bundle); - if (!TextUtils.isEmpty(result)) { - handleSpeechInput(result); - } - } - - private String getResult(Bundle bundle) { - ArrayList results = - bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); - if (results != null && !results.isEmpty()) { - return results.get(0); - } else { - return null; - } - } - - private void appendResults(StringBuilder sb, Bundle bundle) { - ArrayList results = - bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); - float[] scores = bundle.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES); - - if (results != null) { - int size = results.size(); - for (int i = 0; i < size; i++) { - sb.append("\n> ").append(results.get(i)); - if (scores != null && i < scores.length) { - sb.append(" [").append(scores[i]).append("]"); - } - } - } - } - } - - public interface Listener { - void onPartialInput(String input); - void onSpeechInput(String input); - void onStateChanged(State newState); - } - -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/AlternativesActivity.java b/src/ui/android/src/org/grammaticalframework/ui/android/AlternativesActivity.java deleted file mode 100644 index 4f39a04e1..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/AlternativesActivity.java +++ /dev/null @@ -1,674 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.util.*; - -import android.app.Activity; -import android.app.ListActivity; -import android.content.Context; -import android.content.res.Configuration; -import android.os.AsyncTask; -import android.os.Bundle; -import android.view.*; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; -import android.view.MenuItem; -import android.view.LayoutInflater; -import android.webkit.WebView; -import android.widget.BaseAdapter; -import android.widget.ListAdapter; -import android.widget.ArrayAdapter; -import android.widget.ImageView; -import android.widget.RelativeLayout; -import android.widget.TextView; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.ListView; -import android.widget.AdapterView; -import android.util.Log; -import android.support.v4.widget.DrawerLayout; -import android.support.v4.app.ActionBarDrawerToggle; - -import org.grammaticalframework.pgf.*; -import org.grammaticalframework.ui.android.LanguageSelector.OnLanguageSelectedListener; - -public class AlternativesActivity extends ListActivity { - - private Translator mTranslator; - private LanguageSelector mShowLanguageView; - private View mProgressBarView = null; - private AlternativesAdapter mAdapter = null; - private DrawerLayout mDrawerLayout; - private ListView mDrawerList; - private ActionBarDrawerToggle mDrawerToggle; - - /** Called when the activity is first created. */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_lexical_entry); - - mTranslator = ((GFTranslator) getApplicationContext()).getTranslator(); - - mShowLanguageView = (LanguageSelector) findViewById(R.id.show_language); - mShowLanguageView.setLanguages(mTranslator.getAvailableLanguages()); - mShowLanguageView.setOnLanguageSelectedListener(new OnLanguageSelectedListener() { - @Override - public void onLanguageSelected(final Language language) { - new AsyncTask() { - @Override - protected void onPreExecute() { - showProgressBar(); - } - - @Override - protected Void doInBackground(Void... params) { - mTranslator.setTargetLanguage(language); - mTranslator.isTargetLanguageLoaded(); - return null; - } - - @Override - protected void onPostExecute(Void result) { - mAdapter.notifyDataSetChanged(); - collapse(); - hideProgressBar(); - } - }.execute(); - } - }); - - mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); - mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, - R.drawable.ic_drawer, - R.string.topics_open, - R.string.topics_close); - mDrawerLayout.setDrawerListener(mDrawerToggle); - - getActionBar().setDisplayHomeAsUpEnabled(true); - getActionBar().setHomeButtonEnabled(true); - - TextView descrView = (TextView) findViewById(R.id.lexical_desc); - - if (getIntent().getData() != null) { - String authority = getIntent().getData().getAuthority(); - String source = getIntent().getData().getQueryParameter("source"); - - List analyses = new ArrayList(); - for (String an : getIntent().getData().getQueryParameters("alternative")) { - analyses.add(Expr.readExpr(an)); - } - descrView.setText(source); - - mAdapter = new AlternativesAdapter(this, authority, analyses); - } else { - mDrawerLayout.openDrawer(Gravity.LEFT); - - mAdapter = new AlternativesAdapter(this, Translator.WORDS); - } - - expandedView = null; - setListAdapter(mAdapter); - - mDrawerList = (ListView) findViewById(R.id.topics_list); - mDrawerList.setAdapter(mAdapter.getTopicsAdapter()); - - mProgressBarView = findViewById(R.id.progressBarView); - } - - @Override - protected void onResume() { - super.onResume(); - - mShowLanguageView.setSelectedLanguage(mTranslator.getTargetLanguage()); - } - - private void showProgressBar() { - mProgressBarView.setVisibility(View.VISIBLE); - } - - private void hideProgressBar() { - mProgressBarView.setVisibility(View.GONE); - } - - private View expandedView; - - private void collapse() { - if (expandedView == null) - return; - - ImageView arrow = (ImageView) expandedView.findViewById(R.id.arrow); - arrow.setImageResource(R.drawable.open_arrow); - - View view = (View) expandedView.findViewById(R.id.desc_details); - ((RelativeLayout) expandedView).removeView(view); - - TextView textView = (TextView) expandedView.findViewById(R.id.abstract_tree); - if (textView != null) - ((RelativeLayout) expandedView).removeView(textView); - - expandedView = null; - } - - private void expandWord(View view, Expr lemma) { - String html = mTranslator.getInflectionTable(lemma); - if (html == null) - return; - - ImageView arrow = (ImageView) view.findViewById(R.id.arrow); - arrow.setImageResource(R.drawable.close_arrow); - - WebView inflectionView = (WebView) view.findViewById(R.id.desc_details); - if (inflectionView == null) { - inflectionView = new WebView(this); - inflectionView.setId(R.id.desc_details); - RelativeLayout.LayoutParams params = - new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); - params.addRule(RelativeLayout.BELOW, R.id.lexical_desc); - ((RelativeLayout) view).addView(inflectionView, params); - } - - inflectionView.loadData(html, "text/html; charset=UTF-8", null); - - expandedView = view; - } - - private void expandSentence(View view, Expr expr) { - ImageView arrow = (ImageView) view.findViewById(R.id.arrow); - arrow.setImageResource(R.drawable.close_arrow); - - ParseTreeView parseView = (ParseTreeView) view.findViewById(R.id.desc_details); - if (parseView == null) { - parseView = new ParseTreeView(this); - parseView.setId(R.id.desc_details); - RelativeLayout.LayoutParams params = - new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); - params.addRule(RelativeLayout.BELOW, R.id.alternative_desc); - ((RelativeLayout) view).addView(parseView, params); - } - - Object[] brackets = mTranslator.bracketedLinearize(expr); - if (brackets[0] instanceof Bracket) { - Bracket b = (Bracket) brackets[0]; - if (b.children[0].equals("*") || - b.children[0].equals("+")) { - Object[] children = new Object[b.children.length-1]; - for (int i = 1; i < b.children.length; i++) - children[i-1] = b.children[i]; - b = new Bracket(b.cat, b.fun, b.fid, b.lindex, children); - brackets[0] = b; - } - } - parseView.setBrackets(brackets); - - TextView textView = (TextView) view.findViewById(R.id.abstract_tree); - if (textView == null) { - textView = new TextView(this); - textView.setId(R.id.abstract_tree); - textView.setTextSize(15); - RelativeLayout.LayoutParams params = - new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); - params.addRule(RelativeLayout.BELOW, R.id.desc_details); - ((RelativeLayout) view).addView(textView, params); - } - textView.setText(expr.toString()); - - expandedView = view; - } - - private class Topic { - public String name; - public Expr expr; - public boolean isChecked; - public boolean isAvailable; - - public Topic(String name, Expr expr) { - this.name = name; - this.expr = expr; - this.isChecked = false; - this.isAvailable = true; - } - } - - private class AlternativesAdapter extends BaseAdapter implements ListAdapter { - /** - * Contains the list of objects that represent the alternatives - */ - private List mAlternatives; - - private Context mContext; - - // A copy of the original mAlternatives array, initialized from and then used instead as soon as - // a topic filtering is applied. mAlternatives will then only contain the filtered values. - private ArrayList mOriginalAlternatives; - - private LayoutInflater mInflater; - - private String mAuthority; - - /** - * A list of lists of topics. Each element in this list contains - * the list of topics for the correponding item in - * mAlternatives/mOriginalAlternatives - */ - private List> mTopics; - - private Map mTopicMap; - private Topic[] mAllTopics; - private Topic[] mOriginalAllTopics; - - private Topic mOtherTopic; - private Topic mSourceTopic; - - private TopicsAdapter mTopicsAdapter; - - public AlternativesAdapter(Context context, String authority, List alternatives) { - mContext = context; - mAuthority = authority; - mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - mAlternatives = alternatives; - - boolean addOther = false; - mTopics = new ArrayList>(); - mTopicMap = new TreeMap(); - for (Expr e : mAlternatives) { - List topics = new ArrayList(); - for (Expr topicExpr : mTranslator.getTopicsOf(e)) { - String name = mTranslator.linearizeSource(topicExpr); - String key = name.toLowerCase(); - Topic topic = mTopicMap.get(key); - if (topic == null) { - topic = new Topic(name, topicExpr); - mTopicMap.put(key,topic); - } - topics.add(topic); - } - mTopics.add(topics); - - if (topics.size() == 0) - addOther = true; - } - - int i = 0; - mAllTopics = new Topic[mTopicMap.size() + (addOther ? 1 : 0)]; - for (Map.Entry entry : mTopicMap.entrySet()) { - mAllTopics[i++] = entry.getValue(); - } - if (addOther) { - Expr topicExpr = Expr.readExpr("other_A"); - String name = mTranslator.linearizeSource(topicExpr); - mOtherTopic = new Topic(name, topicExpr); - mAllTopics[i++] = mOtherTopic; - } - - mOriginalAllTopics = mAllTopics; - - mTopicsAdapter = new TopicsAdapter(); - } - - public AlternativesAdapter(Context context, String authority) { - mContext = context; - mAuthority = authority; - mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - mAlternatives = null; - - mTopics = null; - - int i = 0; - mTopicMap = new TreeMap(); - for (Expr topicExpr : mTranslator.getTopicsOf(null)) { - String name = mTranslator.linearizeSource(topicExpr); - String key = name.toLowerCase(); - Topic topic = mTopicMap.get(key); - if (topic == null) { - topic = new Topic(name, topicExpr); - mTopicMap.put(key,topic); - } - } - mAllTopics = new Topic[mTopicMap.size()]; - for (Map.Entry entry : mTopicMap.entrySet()) { - mAllTopics[i++] = entry.getValue(); - } - - mOriginalAllTopics = mAllTopics; - - mTopicsAdapter = new TopicsAdapter(); - } - - /** - * Returns the context associated with this array adapter. The context is used - * to create views from the resource passed to the constructor. - * - * @return The Context associated with this adapter. - */ - public Context getContext() { - return mContext; - } - - public String getAuthority() { - return mAuthority; - } - - /** - * {@inheritDoc} - */ - public int getCount() { - if (mAlternatives == null) - return 0; - else - return mAlternatives.size(); - } - - /** - * {@inheritDoc} - */ - public Expr getItem(int position) { - return mAlternatives.get(position); - } - - /** - * Returns the position of the specified item in the array. - * - * @param item The item to retrieve the position of. - * - * @return The position of the specified item. - */ - public int getPosition(Expr item) { - if (mAlternatives == null) - return -1; - else - return mAlternatives.indexOf(item); - } - - /** - * {@inheritDoc} - */ - public long getItemId(int position) { - return position; - } - - public View getView(int position, View convertView, ViewGroup parent) { - final Expr expr = getItem(position); - - if (mAuthority.equals(Translator.WORDS)) { - if (convertView == null) { - convertView = mInflater.inflate(R.layout.lexical_item, null); - } - - TextView descView = (TextView) - convertView.findViewById(R.id.lexical_desc); - - String phrase = mTranslator.generateLexiconEntry(expr); - descView.setText(phrase); - - convertView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - if (expandedView == view) - collapse(); - else if (expandedView == null) - expandWord(view, expr); - else { - collapse(); - expandWord(view, expr); - } - } - }); - } else if (mAuthority.equals(Translator.SENTENCES)) { - if (convertView == null) { - convertView = mInflater.inflate(R.layout.alternative_item, null); - - View treeView = (View) convertView.findViewById(R.id.desc_details); - ((RelativeLayout) convertView).removeView(treeView); - - TextView textView = (TextView) convertView.findViewById(R.id.abstract_tree); - ((RelativeLayout) convertView).removeView(textView); - } - - TextView descView = (TextView) - convertView.findViewById(R.id.alternative_desc); - - String phrase = mTranslator.linearize(expr); - - // parse by words, marked by %, darkest red color - if (phrase.charAt(0) == '%') { - descView.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_worst_utterance_bg)); - phrase = phrase.substring(2); - } - - // parse by chunks, marked by *, red color - else if (phrase.charAt(0) == '*') { - descView.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_chunk_utterance_bg)); - phrase = phrase.substring(2); - } - - // parse error or unknown translations (in []) present, darkest red color - else if (phrase.contains("parse error:") || phrase.contains("[")) { - descView.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_worst_utterance_bg)); - } - - // parse by domain grammar, marked by +, green color - else if (phrase.charAt(0) == '+') { - descView.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_best_utterance_bg)); - phrase = phrase.substring(2); - } - - else { - descView.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_utterance_bg)); - } - - descView.setText(phrase); - - convertView.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - if (expandedView == view) - collapse(); - else if (expandedView == null) - expandSentence(view, expr); - else { - collapse(); - expandSentence(view, expr); - } - } - }); - } - - return convertView; - } - - public boolean areAllItemsEnabled() { - return true; - } - - public boolean isEnabled(int position) { - return true; - } - - public TopicsAdapter getTopicsAdapter() { - return mTopicsAdapter; - } - - void filterOnTopics(List selected_topics) { - if (mSourceTopic != null && !selected_topics.contains(mSourceTopic)) { - mAlternatives = null; - mOriginalAlternatives = null; - mTopics = null; - mAllTopics = mOriginalAllTopics; - } - - if (mAlternatives == null) { - if (selected_topics.size() == 0) { - notifyDataSetChanged(); - return; - } - - mSourceTopic = selected_topics.get(0); - mAlternatives = mTranslator.getTopicWords(mSourceTopic.expr); - - mTopics = new ArrayList>(); - for (Expr e : mAlternatives) { - List topics = new ArrayList(); - for (Expr topicExpr : mTranslator.getTopicsOf(e)) { - String name = mTranslator.linearizeSource(topicExpr); - String key = name.toLowerCase(); - topics.add(mTopicMap.get(key)); - } - mTopics.add(topics); - } - } - - if (mOriginalAlternatives == null) { - mOriginalAlternatives = new ArrayList(mAlternatives); - } - - mAlternatives = new ArrayList(); - List> topics = new ArrayList>(); - - for (Topic topic : mOriginalAllTopics) { - topic.isAvailable = false; - } - - int count = 0; - for (int i = 0; i < mOriginalAlternatives.size(); i++) { - boolean match = true; - for (Topic topic : selected_topics) { - if (topic == mOtherTopic) { - if (mTopics.get(i).size() > 0) { - match = false; - break; - } - } else if (!mTopics.get(i).contains(topic)) { - match = false; - break; - } - } - if (match) { - mAlternatives.add(mOriginalAlternatives.get(i)); - if (mTopics.get(i).size() == 0) { - if (!mOtherTopic.isAvailable) - count++; - mOtherTopic.isAvailable = true; - } else { - for (Topic topic : mTopics.get(i)) { - if (!topic.isAvailable) - count++; - topic.isAvailable = true; - } - } - } - } - - int i = 0; - mAllTopics = new Topic[count]; - for (Topic topic : mOriginalAllTopics) { - if (topic.isAvailable) - mAllTopics[i++] = topic; - } - - notifyDataSetChanged(); - } - } - - private class TopicsAdapter extends BaseAdapter implements ListAdapter { - public TopicsAdapter() { - } - - public Context getContext() { - return mAdapter.getContext(); - } - - public int getCount() { - return mAdapter.mAllTopics.length; - } - - public Topic getItem(int position) { - return mAdapter.mAllTopics[position]; - } - - public int getPosition(Topic topic) { - for (int i = 0; i < mAdapter.mAllTopics.length; i++) { - if (mAdapter.mAllTopics[i] == topic) - return i; - } - return -1; - } - - public long getItemId(int position) { - return position; - } - - // Shame on you Google this class should not have been here - // but unfortuantely CheckBox.setChecked doesn't work and here - // we need a workarround. Since the class is there now it is also - // used to implement OnClickListener. - private class TopicCheckBox extends CheckBox implements OnClickListener { - private Topic mTopic; - - public TopicCheckBox(Context context, Topic topic) { - super(context); - mTopic = topic; - setOnClickListener(this); - } - - @Override - public boolean isChecked() { - if (mTopic == null) - return false; - else - return mTopic.isChecked; - } - - @Override - public void onClick(View view) { - mTopic.isChecked = !mTopic.isChecked; - filterOnTopics(); - notifyDataSetChanged(); - } - } - - private void filterOnTopics() { - List selected_topics = new ArrayList(); - for (int i = 0; i < getCount(); i++) { - Topic topic = getItem(i); - if (topic.isChecked) - selected_topics.add(topic); - } - mAdapter.filterOnTopics(selected_topics); - } - - public View getView(int position, View convertView, ViewGroup parent) { - Topic entry = getItem(position); - - CheckBox checkBox = new TopicCheckBox(getContext(), entry); - checkBox.setText(entry.name); - checkBox.setTextSize(25); - checkBox.setTextColor(android.graphics.Color.parseColor("#808080")); - return checkBox; - } - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - // Sync the toggle state after onRestoreInstanceState has occurred. - mDrawerToggle.syncState(); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - mDrawerToggle.onConfigurationChanged(newConfig); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Pass the event to ActionBarDrawerToggle, if it returns - // true, then it has handled the app icon touch event - if (mDrawerToggle.onOptionsItemSelected(item)) { - return true; - } - return super.onOptionsItemSelected(item); - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/CompletionsView.java b/src/ui/android/src/org/grammaticalframework/ui/android/CompletionsView.java deleted file mode 100644 index c59dbfe86..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/CompletionsView.java +++ /dev/null @@ -1,291 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.res.Resources; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; -import android.view.inputmethod.CompletionInfo; - -import java.util.ArrayList; -import java.util.List; - -public class CompletionsView extends View { - - private static final int OUT_OF_BOUNDS = -1; - - private TranslatorInputMethodService mService; - private CompletionInfo[] mSuggestions; - private int mSelectedIndex; - private int mTouchX = OUT_OF_BOUNDS; - private Drawable mSelectionHighlight; - private boolean mTypedWordValid; - - private Rect mBgPadding; - - private static final int MAX_SUGGESTIONS = 32; - private static final int SCROLL_PIXELS = 20; - - private int[] mWordWidth = new int[MAX_SUGGESTIONS]; - private int[] mWordX = new int[MAX_SUGGESTIONS]; - - private static final int X_GAP = 10; - - private int mColorNormal; - private int mColorRecommended; - private int mColorOther; - private int mVerticalPadding; - private Paint mPaint; - private boolean mScrolled; - private int mTargetScrollX; - - private int mTotalWidth; - - private GestureDetector mGestureDetector; - - /** - * Construct a CandidateView for showing suggested words for completion. - * @param context - * @param attrs - */ - public CompletionsView(Context context) { - super(context); - mSelectionHighlight = context.getResources().getDrawable( - android.R.drawable.list_selector_background); - mSelectionHighlight.setState(new int[] { - android.R.attr.state_enabled, - android.R.attr.state_focused, - android.R.attr.state_window_focused, - android.R.attr.state_pressed - }); - - Resources r = context.getResources(); - - setBackgroundColor(r.getColor(R.color.candidate_background)); - - mColorNormal = r.getColor(R.color.candidate_normal); - mColorRecommended = r.getColor(R.color.candidate_recommended); - mColorOther = r.getColor(R.color.candidate_other); - mVerticalPadding = r.getDimensionPixelSize(R.dimen.candidate_vertical_padding); - - mPaint = new Paint(); - mPaint.setColor(mColorNormal); - mPaint.setAntiAlias(true); - mPaint.setTextSize(r.getDimensionPixelSize(R.dimen.candidate_font_height)); - mPaint.setStrokeWidth(0); - - mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { - @Override - public boolean onScroll(MotionEvent e1, MotionEvent e2, - float distanceX, float distanceY) { - mScrolled = true; - int sx = getScrollX(); - sx += distanceX; - if (sx < 0) { - sx = 0; - } - if (sx + getWidth() > mTotalWidth) { - sx -= distanceX; - } - mTargetScrollX = sx; - scrollTo(sx, getScrollY()); - invalidate(); - return true; - } - }); - setHorizontalFadingEdgeEnabled(true); - setWillNotDraw(false); - setHorizontalScrollBarEnabled(false); - setVerticalScrollBarEnabled(false); - } - - /** - * A connection back to the service to communicate with the text field - * @param listener - */ - public void setService(TranslatorInputMethodService listener) { - mService = listener; - } - - @Override - public int computeHorizontalScrollRange() { - return mTotalWidth; - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int measuredWidth = resolveSize(50, widthMeasureSpec); - - // Get the desired height of the icon menu view (last row of items does - // not have a divider below) - Rect padding = new Rect(); - mSelectionHighlight.getPadding(padding); - final int desiredHeight = ((int)mPaint.getTextSize()) + mVerticalPadding - + padding.top + padding.bottom; - - // Maximum possible width and desired height - setMeasuredDimension(measuredWidth, - resolveSize(desiredHeight, heightMeasureSpec)); - } - - /** - * If the canvas is null, then only touch calculations are performed to pick the target - * candidate. - */ - @Override - protected void onDraw(Canvas canvas) { - if (canvas != null) { - super.onDraw(canvas); - } - mTotalWidth = 0; - if (mSuggestions == null) return; - - if (mBgPadding == null) { - mBgPadding = new Rect(0, 0, 0, 0); - if (getBackground() != null) { - getBackground().getPadding(mBgPadding); - } - } - int x = 0; - final int count = mSuggestions.length; - final int height = getHeight(); - final Rect bgPadding = mBgPadding; - final Paint paint = mPaint; - final int touchX = mTouchX; - final int scrollX = getScrollX(); - final boolean scrolled = mScrolled; - final boolean typedWordValid = mTypedWordValid; - final int y = (int) (((height - mPaint.getTextSize()) / 2) - mPaint.ascent()); - - for (int i = 0; i < count; i++) { - String suggestion = mSuggestions[i].getText().toString(); - float textWidth = paint.measureText(suggestion); - final int wordWidth = (int) textWidth + X_GAP * 2; - - mWordX[i] = x; - mWordWidth[i] = wordWidth; - paint.setColor(mColorNormal); - if (touchX + scrollX >= x && touchX + scrollX < x + wordWidth && !scrolled) { - if (canvas != null) { - canvas.translate(x, 0); - mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height); - mSelectionHighlight.draw(canvas); - canvas.translate(-x, 0); - } - mSelectedIndex = i; - } - - if (canvas != null) { - if ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid)) { - paint.setFakeBoldText(true); - paint.setColor(mColorRecommended); - } else if (i != 0) { - paint.setColor(mColorOther); - } - canvas.drawText(suggestion, x + X_GAP, y, paint); - paint.setColor(mColorOther); - canvas.drawLine(x + wordWidth + 0.5f, bgPadding.top, - x + wordWidth + 0.5f, height + 1, paint); - paint.setFakeBoldText(false); - } - x += wordWidth; - } - mTotalWidth = x; - if (mTargetScrollX != getScrollX()) { - scrollToTarget(); - } - } - - private void scrollToTarget() { - int sx = getScrollX(); - if (mTargetScrollX > sx) { - sx += SCROLL_PIXELS; - if (sx >= mTargetScrollX) { - sx = mTargetScrollX; - requestLayout(); - } - } else { - sx -= SCROLL_PIXELS; - if (sx <= mTargetScrollX) { - sx = mTargetScrollX; - requestLayout(); - } - } - scrollTo(sx, getScrollY()); - invalidate(); - } - - @SuppressLint("WrongCall") - public void setSuggestions(CompletionInfo[] suggestions, boolean completions, - boolean typedWordValid) { - clear(); - if (suggestions != null) { - mSuggestions = suggestions; - } - mTypedWordValid = typedWordValid; - scrollTo(0, 0); - mTargetScrollX = 0; - // Compute the total width - onDraw(null); - invalidate(); - requestLayout(); - } - - public void clear() { - mSuggestions = new CompletionInfo[0]; - mTouchX = OUT_OF_BOUNDS; - mSelectedIndex = -1; - invalidate(); - } - - @Override - public boolean onTouchEvent(MotionEvent me) { - - if (mGestureDetector.onTouchEvent(me)) { - return true; - } - - int action = me.getAction(); - int x = (int) me.getX(); - int y = (int) me.getY(); - mTouchX = x; - - switch (action) { - case MotionEvent.ACTION_DOWN: - mScrolled = false; - invalidate(); - break; - case MotionEvent.ACTION_MOVE: - if (y <= 0) { - // Fling up!? - if (mSelectedIndex >= 0) { - mService.pickSuggestionManually(mSelectedIndex); - mSelectedIndex = -1; - } - } - invalidate(); - break; - case MotionEvent.ACTION_UP: - if (!mScrolled) { - if (mSelectedIndex >= 0) { - mService.pickSuggestionManually(mSelectedIndex); - } - } - mSelectedIndex = -1; - removeHighlight(); - requestLayout(); - break; - } - return true; - } - - private void removeHighlight() { - mTouchX = OUT_OF_BOUNDS; - invalidate(); - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/ConversationView.java b/src/ui/android/src/org/grammaticalframework/ui/android/ConversationView.java deleted file mode 100644 index b7d118e7c..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/ConversationView.java +++ /dev/null @@ -1,242 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.io.Serializable; -import java.util.*; - -import android.content.Context; -import android.os.Bundle; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.view.inputmethod.InputMethodManager; -import android.view.KeyEvent; -import android.widget.EditText; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.TextView.OnEditorActionListener; - -import org.grammaticalframework.pgf.Expr; - -public class ConversationView extends ScrollView { - - private LayoutInflater mInflater; - - private ViewGroup mContent; - - private OnClickListener mAlternativesListener; - private ASR.Listener mSpeechListener; - - public ConversationView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } - - public ConversationView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public ConversationView(Context context) { - super(context); - } - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - mContent = (ViewGroup) findViewById(R.id.conversation_content); - mInflater = LayoutInflater.from(getContext()); - } - - private class EditorListener implements OnEditorActionListener, OnClickListener { - @Override - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if ((actionId & EditorInfo.IME_MASK_ACTION) != 0) { - CharSequence text = v.getText(); - InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - if (inputMethodManager != null) { - inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); - } - v.setFocusable(false); - mLastUtterance = v; - if (mSpeechListener != null) - mSpeechListener.onSpeechInput(text.toString().trim()); - return true; - } - return false; - } - - @Override - public void onClick(View v) { - v.setFocusableInTouchMode(true); - v.requestFocus(); - InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT); - } - }; - - private EditorListener mEditorListener = new EditorListener(); - private TextView mLastUtterance = null; - - public void addFirstPersonUtterance(CharSequence text, boolean focused) { - EditText edittext = (EditText) - mInflater.inflate(R.layout.first_person_utterance, mContent, false); - edittext.setText(text); - edittext.setOnEditorActionListener(mEditorListener); - edittext.setOnClickListener(mEditorListener); - edittext.setHorizontallyScrolling(false); - edittext.setMaxLines(Integer.MAX_VALUE); - Bundle extras = edittext.getInputExtras(true); - extras.putBoolean("show_language_toggle", false); - mContent.addView(edittext); - - if (focused) { - edittext.requestFocus(); - InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.showSoftInput(edittext, InputMethodManager.SHOW_IMPLICIT); - } else { - edittext.setFocusable(false); - } - - post(new Runnable() { - public void run() { - fullScroll(FOCUS_DOWN); - } - }); - - mLastUtterance = edittext; - } - - @SuppressWarnings("deprecation") - public CharSequence addSecondPersonUtterance(String authority, CharSequence source, CharSequence target, List alternatives) { - TextView view; - if (mLastUtterance != null && mLastUtterance.getTag() != null) - view = (TextView) mLastUtterance.getTag(); - else { - view = (TextView) - mInflater.inflate(R.layout.second_person_utterance, mContent, false); - if (mAlternativesListener != null) - view.setOnClickListener(mAlternativesListener); - mContent.addView(view); - post(new Runnable() { - public void run() { - fullScroll(FOCUS_DOWN); - } - }); - - mLastUtterance.setTag(view); - } - - view.setTag(R.string.authority_key, authority); - view.setTag(R.string.source_key, source); - view.setTag(R.string.target_key, target); - view.setTag(R.string.alternatives_key, alternatives); - - // parse by words, marked by %, darkest red color - if (target.charAt(0) == '%') { - view.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_worst_utterance_bg)); - target = target.subSequence(1, target.length()).toString().trim(); - } - - // parse by chunks, marked by *, red color - else if (target.charAt(0) == '*') { - view.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_chunk_utterance_bg)); - target = target.subSequence(1, target.length()).toString().trim(); - } - - // parse error: darkest red color - else if (target.toString().contains("parse error:")) { - view.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_worst_utterance_bg)); - } - - // unknown linearizations in output: darkest red color. But replace [ ] by spaces and remove _ for better speech synthesis - else if (target.toString().contains("[")) { - view.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_worst_utterance_bg)); - } - - // parse by domain grammar, marked by +, green color - else if (target.charAt(0) == '+') { - view.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_best_utterance_bg)); - target = target.subSequence(1, target.length()).toString().trim(); - } - - else { - view.setBackgroundDrawable(getResources().getDrawable(R.drawable.second_person_utterance_bg)); - } - - view.setText(target); - return target; - } - - public void updateLastUtterance(CharSequence text) { - if (mLastUtterance != null) - mLastUtterance.setText(text); - } - - public void setOnAlternativesListener(final OnAlternativesListener listener) { - if (listener == null) - mAlternativesListener = null; - else - mAlternativesListener = new OnClickListener() { - @Override - public void onClick(View v) { - String authority = v.getTag(R.string.authority_key).toString(); - String source = v.getTag(R.string.source_key).toString(); - List alternatives = (List) v.getTag(R.string.alternatives_key); - listener.onAlternativesSelected(authority, source, alternatives); - } - }; - } - - public void setSpeechInputListener(ASR.Listener listener) { - mSpeechListener = listener; - } - - public interface OnAlternativesListener { - public void onAlternativesSelected(CharSequence authority, CharSequence word, List althernatives); - } - - public void saveConversation(Bundle state) { - ArrayList authorities = new ArrayList(); - ArrayList firstPersonUtterances = new ArrayList(); - ArrayList secondPersonUtterances = new ArrayList(); - ArrayList translationAlternatives = new ArrayList(); - - int childCount = mContent.getChildCount(); - for (int i = 0; i < childCount; i++) { - View child = mContent.getChildAt(i); - if (child.getClass() == TextView.class) { - authorities.add(child.getTag(R.string.authority_key).toString()); - firstPersonUtterances.add(child.getTag(R.string.source_key).toString()); - secondPersonUtterances.add(child.getTag(R.string.target_key).toString()); - translationAlternatives.add(child.getTag(R.string.alternatives_key)); - } - } - - state.putStringArrayList("authorities", authorities); - state.putStringArrayList("first_person_uterances", firstPersonUtterances); - state.putStringArrayList("second_person_uterances", secondPersonUtterances); - state.putSerializable("translation_alternatives",(Serializable) translationAlternatives); - } - - public void restoreConversation(Bundle state) { - ArrayList authorities = state.getStringArrayList("authorities"); - ArrayList firstPersonUtterances = state.getStringArrayList("first_person_uterances"); - ArrayList secondPersonUtterances = state.getStringArrayList("second_person_uterances"); - ArrayList> translationAlternatives= (ArrayList>) state.getSerializable("translation_alternatives"); - - int i = 0; - while (i < authorities.size() && - i < firstPersonUtterances.size() && - i < Math.min(secondPersonUtterances.size(), translationAlternatives.size())) { - String text = firstPersonUtterances.get(i); - addFirstPersonUtterance(text, false); - - String authority = authorities.get(i); - String translation = secondPersonUtterances.get(i); - List alternatives = translationAlternatives.get(i); - addSecondPersonUtterance(authority, text, translation, alternatives); - - i++; - } - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/GFTranslator.java b/src/ui/android/src/org/grammaticalframework/ui/android/GFTranslator.java deleted file mode 100644 index 8900b2415..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/GFTranslator.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.app.Application; - -public class GFTranslator extends Application { - private Translator mTranslator; - private static GFTranslator instance; - - @Override - public void onCreate() { - mTranslator = new Translator(this); - instance = this; - } - - public Translator getTranslator() { - return mTranslator; - } - - public static GFTranslator get() { - return instance; - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/HelpActivity.java b/src/ui/android/src/org/grammaticalframework/ui/android/HelpActivity.java deleted file mode 100644 index c6a822484..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/HelpActivity.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.app.Activity; -import android.os.Bundle; -import android.webkit.WebView; - -public class HelpActivity extends Activity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_help); - WebView wv = (WebView) findViewById(R.id.help_content); - wv.loadUrl("file:///android_asset/help_content.html"); - } -} \ No newline at end of file diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/Language.java b/src/ui/android/src/org/grammaticalframework/ui/android/Language.java deleted file mode 100644 index 000206045..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/Language.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.io.Serializable; - -public class Language implements Serializable { - private static final long serialVersionUID = 1L; - - private final String mLangCode; - private final String mLangName; - private final String mConcrete; - private final int mKeyboardPage1Resource; - private final int mKeyboardPage2Resource; - - public Language(String langCode, String langName, String concrete, - int keyboardResource) { - mLangCode = langCode; - mLangName = langName; - mConcrete = concrete; - mKeyboardPage1Resource = keyboardResource; - mKeyboardPage2Resource = keyboardResource; - } - - public Language(String langCode, String langName, String concrete, - int keyboardPage1Resource, int keyboardPage2Resource) { - mLangCode = langCode; - mLangName = langName; - mConcrete = concrete; - mKeyboardPage1Resource = keyboardPage1Resource; - mKeyboardPage2Resource = keyboardPage2Resource; - } - - public String getLangCode() { - return mLangCode; - } - - public String getLangName() { - return mLangName; - } - - public int getKeyboardPage1Resource() { - return mKeyboardPage1Resource; - } - - public int getKeyboardPage2Resource() { - return mKeyboardPage2Resource; - } - - String getConcrete() { - return mConcrete; - } - - @Override - public String toString() { - return getLangName(); - } - - @Override - public boolean equals(Object o) { - Language other = (Language) o; - return mLangCode.equals(other.mLangCode); - } -} \ No newline at end of file diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/LanguageSelector.java b/src/ui/android/src/org/grammaticalframework/ui/android/LanguageSelector.java deleted file mode 100644 index de628b2b5..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/LanguageSelector.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.View; -import android.widget.AdapterView; -import android.widget.Spinner; - -import java.util.List; - -public class LanguageSelector extends Spinner { - - public LanguageSelector(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } - - public LanguageSelector(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public LanguageSelector(Context context) { - super(context); - } - - public void setLanguages(List languages) { - setAdapter(new LanguagesAdapter(getContext(), languages)); - } - - public void setSelectedLanguage(Language selected) { - setSelection(((LanguagesAdapter) getAdapter()).getPosition(selected)); - } - - public Language getSelectedLanguage() { - return (Language) getSelectedItem(); - } - - public void setOnLanguageSelectedListener(final OnLanguageSelectedListener listener) { - setOnItemSelectedListener(new OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (listener != null) { - listener.onLanguageSelected((Language) parent.getItemAtPosition(position)); - } - } - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - } - - public interface OnLanguageSelectedListener { - void onLanguageSelected(Language language); - } - -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/LanguagesAdapter.java b/src/ui/android/src/org/grammaticalframework/ui/android/LanguagesAdapter.java deleted file mode 100644 index e39ed7bd9..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/LanguagesAdapter.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.content.Context; -import android.widget.ArrayAdapter; -import android.widget.SpinnerAdapter; - - -import java.util.List; - -public class LanguagesAdapter extends ArrayAdapter implements SpinnerAdapter { - - public LanguagesAdapter(Context context, List objects) { - super(context, R.layout.languages_item, objects); - } - -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/LexiconSuggestionProvider.java b/src/ui/android/src/org/grammaticalframework/ui/android/LexiconSuggestionProvider.java deleted file mode 100644 index 7b9813b7d..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/LexiconSuggestionProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.content.ContentProvider; -import android.content.ContentValues; -import android.provider.BaseColumns; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.app.SearchManager; -import android.net.Uri; -import android.util.Log; -import android.view.inputmethod.CompletionInfo; - -public class LexiconSuggestionProvider extends ContentProvider { - private Translator mTranslator; - - public boolean onCreate() { - return true; - } - - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { - mTranslator = ((GFTranslator) getContext().getApplicationContext()).getTranslator(); - String[] columns = new String[] { - BaseColumns._ID, - SearchManager.SUGGEST_COLUMN_TEXT_1, - SearchManager.SUGGEST_COLUMN_QUERY - }; - - String query = uri.getLastPathSegment(); - MatrixCursor cursor = new MatrixCursor(columns, 100); - for (CompletionInfo info : mTranslator.lookupWordPrefix(query)) { - cursor.addRow(new String[] {Long.toString(info.getId()),info.getText().toString(),info.getText().toString()}); - } - - return cursor; - } - - public Uri insert (Uri uri, ContentValues values) { - throw new UnsupportedOperationException(); - } - - public int update (Uri uri, ContentValues values, String selection, String[] selectionArgs) { - throw new UnsupportedOperationException(); - } - - public int delete (Uri uri, String selection, String[] selectionArgs) { - throw new UnsupportedOperationException(); - } - - public String getType (Uri uri) { - return null; - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/LocaleUtils.java b/src/ui/android/src/org/grammaticalframework/ui/android/LocaleUtils.java deleted file mode 100644 index 9fb048908..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/LocaleUtils.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.text.TextUtils; - -import java.util.Locale; - -/** - * Collections of utils to handle locales. - */ -public class LocaleUtils { - - /** - * Parses a locale string formatted by {@link Locale#toString()}. - * - * @return the parsed {@code Locale} or {@code defaultLocale} if the input was null or empty. - */ - public static Locale parseJavaLocale(String localeString, Locale defaultLocale) { - if (TextUtils.isEmpty(localeString)) { - return defaultLocale; - } - final char separator = '_'; - int pos1 = localeString.indexOf(separator); - if (pos1 == -1) { - return new Locale(localeString); - } - String language = localeString.substring(0, pos1); - - int start2 = pos1 + 1; - int pos2 = localeString.indexOf(separator, start2); - if (pos2 == -1) { - return new Locale(language, localeString.substring(start2)); - } - String country = localeString.substring(start2, pos2); - - int start3 = pos2 + 1; - int pos3 = localeString.indexOf(separator, start3); - String variant = (pos3 == -1) - ? localeString.substring(start3) - : localeString.substring(start3, pos3); - return new Locale(language, country, variant); - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/MainActivity.java b/src/ui/android/src/org/grammaticalframework/ui/android/MainActivity.java deleted file mode 100644 index 369e542e9..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/MainActivity.java +++ /dev/null @@ -1,377 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.io.*; -import java.util.*; - -import android.app.Activity; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.AsyncTask; -import android.os.Bundle; -import android.speech.SpeechRecognizer; -import android.net.Uri; -import android.util.Log; -import android.util.Pair; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.View.OnTouchListener; -import android.widget.ImageView; - -import org.grammaticalframework.ui.android.ASR.State; -import org.grammaticalframework.ui.android.LanguageSelector.OnLanguageSelectedListener; -import org.grammaticalframework.ui.android.ConversationView.OnAlternativesListener; -import org.grammaticalframework.pgf.*; - -public class MainActivity extends Activity { - - private static final boolean DBG = true; - private static final String TAG = "MainActivity"; - - private ImageView mStartStopButton; - - private ConversationView mConversationView; - - private LanguageSelector mSourceLanguageView; - - private LanguageSelector mTargetLanguageView; - - private ImageView mSwitchLanguagesButton; - - private ASR mAsr; - - private TTS mTts; - - private Translator mTranslator; - - private boolean input_mode; - - private SpeechInputListener mSpeechListener; - - private View mProgressBarView = null; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - mStartStopButton = (ImageView) findViewById(R.id.start_stop); - mConversationView = (ConversationView) findViewById(R.id.conversation); - mSourceLanguageView = (LanguageSelector) findViewById(R.id.source_language); - mTargetLanguageView = (LanguageSelector) findViewById(R.id.target_language); - mSwitchLanguagesButton = (ImageView) findViewById(R.id.switch_languages); - mProgressBarView = findViewById(R.id.progressBarView); - - mStartStopButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - if (mAsr.isRunning()) { - stopRecognition(); - } else { - startRecognition(); - } - } - }); - - SharedPreferences pref = getPreferences(MODE_PRIVATE); - input_mode = pref.getBoolean("input_mode", true); - if (!SpeechRecognizer.isRecognitionAvailable(this)) { - input_mode = false; - } - mStartStopButton.setImageResource(input_mode ? R.drawable.ic_mic : R.drawable.ic_keyboard); - - mSpeechListener = new SpeechInputListener(); - - mConversationView.setOnAlternativesListener(new OnAlternativesListener() { - @Override - public void onAlternativesSelected(CharSequence authority, CharSequence input, List alternatives) { - Uri.Builder builder = new Uri.Builder(); - builder.scheme("gf-translator"); - builder.authority(authority.toString()); - builder.appendQueryParameter("source", input.toString()); - for (Expr e : alternatives) { - builder.appendQueryParameter("alternative", e.toString()); - } - - Intent myIntent = new Intent(Intent.ACTION_VIEW, builder.build()); - MainActivity.this.startActivity(myIntent); - } - }); - mConversationView.setSpeechInputListener(mSpeechListener); - - mAsr = new ASR(this); - mAsr.setListener(mSpeechListener); - - mTts = new TTS(this); - - mTranslator = ((GFTranslator) getApplicationContext()).getTranslator(); - - mSourceLanguageView.setLanguages(mTranslator.getAvailableLanguages()); - mSourceLanguageView.setOnLanguageSelectedListener(new OnLanguageSelectedListener() { - @Override - public void onLanguageSelected(Language language) { - onSourceLanguageSelected(language); - } - }); - mTargetLanguageView.setLanguages(mTranslator.getAvailableLanguages()); - mTargetLanguageView.setOnLanguageSelectedListener(new OnLanguageSelectedListener() { - @Override - public void onLanguageSelected(Language language) { - onTargetLanguageSelected(language); - } - }); - - mSwitchLanguagesButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - onSwitchLanguages(); - } - }); - - if (savedInstanceState != null) { - mConversationView.restoreConversation(savedInstanceState); - } - } - - @Override - protected void onResume() { - super.onResume(); - - mSourceLanguageView.setSelectedLanguage(mTranslator.getSourceLanguage()); - mTargetLanguageView.setSelectedLanguage(mTranslator.getTargetLanguage()); - } - - private void showProgressBar() { - mProgressBarView.setVisibility(View.VISIBLE); - } - - private void hideProgressBar() { - mProgressBarView.setVisibility(View.GONE); - } - - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - mConversationView.saveConversation(outState); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.main, menu); - - menu.getItem(0).setTitle(input_mode ? R.string.keyboard_input : R.string.mic_input); - - if (!SpeechRecognizer.isRecognitionAvailable(this)) { - menu.getItem(0).setEnabled(false); - } - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Handle item selection - switch (item.getItemId()) { - case R.id.input_mode: - if (input_mode) { - item.setTitle(R.string.mic_input); - mStartStopButton.setImageResource(R.drawable.ic_keyboard); - input_mode = false; - } else { - item.setTitle(R.string.keyboard_input); - mStartStopButton.setImageResource(R.drawable.ic_mic); - input_mode = true; - } - - SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); - editor.putBoolean("input_mode", input_mode); - editor.commit(); - - return true; - case R.id.phrasebook: { - Intent myIntent = new Intent(MainActivity.this, se.chalmers.phrasebook.gui.activities.NavigationActivity.class); - MainActivity.this.startActivity(myIntent); - return true; - } - case R.id.topics: { - Intent myIntent = new Intent(MainActivity.this, AlternativesActivity.class); - MainActivity.this.startActivity(myIntent); - return true; - } - case R.id.help: { - Intent myIntent = new Intent(MainActivity.this, HelpActivity.class); - MainActivity.this.startActivity(myIntent); - return true; - } - default: - return super.onOptionsItemSelected(item); - } - } - - @Override - protected void onDestroy() { - if (mAsr != null) { - mAsr.destroy(); - mAsr = null; - } - if (mTts != null) { - mTts.destroy(); - mTts = null; - } - super.onDestroy(); - } - - void onSourceLanguageSelected(Language language) { - mTranslator.setSourceLanguage(language); - if (TranslatorInputMethodService.getInstance() != null) { - TranslatorInputMethodService.getInstance().handleChangeSourceLanguage(language); - } - } - - void onTargetLanguageSelected(Language language) { - mTranslator.setTargetLanguage(language); - if (TranslatorInputMethodService.getInstance() != null) { - TranslatorInputMethodService.getInstance().handleChangeTargetLanguage(language); - } - } - - public String getSourceLanguageCode() { - return mTranslator.getSourceLanguage().getLangCode(); - } - - public String getTargetLanguageCode() { - return mTranslator.getTargetLanguage().getLangCode(); - } - - void onSwitchLanguages() { - mTranslator.switchLanguages(); - mSourceLanguageView.setSelectedLanguage(mTranslator.getSourceLanguage()); - mTargetLanguageView.setSelectedLanguage(mTranslator.getTargetLanguage()); - - if (TranslatorInputMethodService.getInstance() != null) { - TranslatorInputMethodService.getInstance().handleSwitchLanguages(); - } - } - - private void startRecognition() { - if (input_mode) { - mConversationView.addFirstPersonUtterance("...", false); - mAsr.setLanguage(getSourceLanguageCode()); - mAsr.startRecognition(); - } else { - mConversationView.addFirstPersonUtterance("", true); - } - } - - private void stopRecognition() { - mAsr.stopRecognition(); - } - - private void handlePartialSpeechInput(String input) { - mConversationView.updateLastUtterance(input); - } - - private void handleSpeechInput(final String input) { - final List list = mTranslator.lookupMorpho(input); - - mConversationView.updateLastUtterance(input); - new AsyncTask>>() { - @Override - protected void onPreExecute() { - showProgressBar(); - } - - @Override - protected Pair> doInBackground(Void... params) { - return mTranslator.translate(input); - } - - @Override - protected void onPostExecute(Pair> res) { - String text = res.first; - List transl = res.second; - - List alts = null; - String authority = null; - - // filter out duplicates - int i = 0; - if (list.size() > 0) { - alts = new ArrayList(list.size()); - authority = Translator.WORDS; - - while (i < list.size()) { - MorphoAnalysis an = list.get(i); - boolean found = false; - for (int j = 0; j < i; j++) { - if (list.get(j).getLemma().equals(an.getLemma())) { - found = true; - break; - } - } - - if (!found) { - alts.add(Expr.readExpr(an.getLemma())); - } - - i++; - } - } else { - alts = new ArrayList(transl.size()); - authority = Translator.SENTENCES; - - Set strings = new HashSet(); - while (i < transl.size()) { - String s = mTranslator.linearize(transl.get(i).getExpr()); - if (s.length() > 0 && - (s.charAt(0) == '%' || s.charAt(0) == '*' || s.charAt(0) == '+')) { - s = s.substring(2); - } - - if (!strings.contains(s)) { - strings.add(s); - alts.add(transl.get(i).getExpr()); - } - - i++; - } - } - - if (DBG) Log.d(TAG, "Speaking: " + res.first); - CharSequence text2 = - mConversationView.addSecondPersonUtterance(authority, input, text, alts); - text2 = text2.toString().replace('[',' ').replace(']',' ').replaceAll("_","").trim(); - mTts.speak(getTargetLanguageCode(), text2.toString()); - - hideProgressBar(); - } - }.execute(); - } - - private class SpeechInputListener implements ASR.Listener { - - @Override - public void onPartialInput(String input) { - handlePartialSpeechInput(input); - } - - @Override - public void onSpeechInput(String input) { - handleSpeechInput(input); - } - - @Override - public void onStateChanged(State newState) { - if (newState == ASR.State.IDLE) { - //clear the overlay - mStartStopButton.getDrawable().clearColorFilter(); - } else { - mStartStopButton.getDrawable().setColorFilter(0xffff0000,android.graphics.PorterDuff.Mode.SRC_ATOP); - } - mStartStopButton.invalidate(); - } - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/ParseTreeView.java b/src/ui/android/src/org/grammaticalframework/ui/android/ParseTreeView.java deleted file mode 100644 index b2ff74183..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/ParseTreeView.java +++ /dev/null @@ -1,270 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.PointF; -import android.graphics.Rect; -import android.util.AttributeSet; -import android.util.SparseArray; -import android.view.MotionEvent; -import android.view.View; - -import org.grammaticalframework.pgf.Bracket; - - -public class ParseTreeView extends View { - private static final float SISTER_SKIP = 25; - private static final float PARENT_SKIP = 0.5f; - private static final float ABOVE_LINE_SKIP = 0.1f; - private static final float BELOW_LINE_SKIP = 0.1f; - - private Paint paint; - private Object[] brackets; - - private float lastMotionX; - private float scrollRange; - - public ParseTreeView(Context context) { - this(context, null); - } - - public ParseTreeView(Context context, AttributeSet attrs) { - super(context, attrs, R.attr.parseTreeViewStyle); - - paint = new Paint(); - paint.setTextSize(60); - brackets = null; - scrollRange = 0; - } - - public Object[] getBrackets() { - return brackets; - } - - public void setBrackets(Object[] brackets) { - this.brackets = brackets; - awakenScrollBars(); - } - - static class MeasureResult { - float width = 0.0f; - float height = 0.0f; - float nodeTab = 0.0f; - float nodeCenter = 0.0f; - float childTab = 0.0f; - float localWidth = 0.0f; - float localHeight = 0.0f; - } - - private MeasureResult mr = new MeasureResult(); - private SparseArray coords = new SparseArray(); - private PointF zeroPoint = new PointF(); - - private void measureTree(Object o) { - if (o instanceof Bracket) { - Bracket bracket = (Bracket) o; - - Rect bounds = new Rect(); - paint.getTextBounds(bracket.cat,0,bracket.cat.length(),bounds); - float localWidth = bounds.width(); - float localHeight = bounds.height(); - float layerHeight = localHeight * (1.0f + BELOW_LINE_SKIP + ABOVE_LINE_SKIP + PARENT_SKIP); - - PointF local = coords.get(bracket.fid); - if (local == null) { - coords.put(bracket.fid, zeroPoint); - } else { - localWidth = 0; - } - - float subWidth = 0.0f; - float subHeight = 0.0f; - float nodeCenter = 0.0f; - for (int i = 0; i < bracket.children.length; i++) { - measureTree(bracket.children[i]); - - if (i == 0) { - nodeCenter += (subWidth + mr.nodeCenter) / 2.0; - } - if (i == bracket.children.length - 1) { - nodeCenter += (subWidth + mr.nodeCenter) / 2.0; - } - - subWidth += mr.width; - if (i < bracket.children.length - 1) { - subWidth += SISTER_SKIP; - } - - if (subHeight < mr.height) - subHeight = mr.height; - } - float localLeft = localWidth / 2.0f; - float subLeft = nodeCenter; - float totalLeft = Math.max(localLeft, subLeft); - float localRight = localWidth / 2.0f; - float subRight = subWidth - nodeCenter; - float totalRight = Math.max(localRight, subRight); - mr.width = totalLeft + totalRight; - mr.height = layerHeight + subHeight; - mr.childTab = totalLeft - subLeft; - mr.nodeTab = totalLeft - localLeft; - mr.nodeCenter = nodeCenter + mr.childTab; - mr.localWidth = localWidth; - mr.localHeight = localHeight; - } else { - String word = o.toString(); - - Rect bounds = new Rect(); - paint.getTextBounds(word,0,word.length(),bounds); - mr.width = bounds.width(); - mr.height = bounds.height(); - mr.nodeTab = 0.0f; - mr.nodeCenter = bounds.width() / 2.0f; - mr.childTab = 0.0f; - mr.localWidth = bounds.width(); - mr.localHeight = bounds.height(); - } - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - if (brackets == null) { - setMeasuredDimension(0, 0); - return; - } - - coords.clear(); - - float width = 0.0f; - float height = 0.0f; - for (int i = 0; i < brackets.length; i++) { - measureTree(brackets[i]); - - width += mr.width; - if (i < brackets.length - 1) { - width += SISTER_SKIP; - } - - if (height < mr.height) - height = mr.height; - } - - height += paint.getFontMetrics().descent; - - int w = getPaddingLeft() + (int) width + getPaddingRight(); - int h = getPaddingTop() + (int) height + getPaddingBottom(); - - scrollRange = w; - - int widthReq = MeasureSpec.getSize(widthMeasureSpec); - if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY || - (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST && w > widthReq)) { - w = widthReq; - } - int heightReq = MeasureSpec.getSize(heightMeasureSpec); - if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY || - (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST && h > heightReq)) { - h = heightReq; - } - - setMeasuredDimension(w, h); - } - - private void drawTree(Canvas canvas, - float x, float y, float bottom, PointF parentPoint, - Object o) { - if (o instanceof Bracket) { - Bracket bracket = (Bracket) o; - - PointF lineStart = coords.get(bracket.fid); - if (lineStart == null) { - lineStart = new PointF(x + mr.nodeCenter, y + mr.localHeight * (1.0f + BELOW_LINE_SKIP)); - coords.put(bracket.fid, lineStart); - - if (parentPoint != null) { - float lineEndX = x + mr.nodeCenter; - float lineEndY = y; - canvas.drawLine(parentPoint.x, parentPoint.y, lineEndX, lineEndY, paint); - } - - canvas.drawText(bracket.cat, x+mr.nodeTab, y+mr.localHeight, paint); - } - - float layerMultiplier = (1.0f + BELOW_LINE_SKIP + ABOVE_LINE_SKIP + PARENT_SKIP); - float layerHeight = mr.localHeight * layerMultiplier; - float childStartX = x + mr.childTab; - float childStartY = y + layerHeight; - for (int i = 0; i < bracket.children.length; i++) { - Object child = bracket.children[i]; - SparseArray copy = coords.clone(); - measureTree(child); - coords = copy; - float w = mr.width; - drawTree(canvas, childStartX, childStartY, bottom, lineStart, child); - childStartX += w + SISTER_SKIP; - } - } else { - float lineEndX = x + mr.nodeCenter; - float lineEndY = bottom - mr.height; - canvas.drawLine(parentPoint.x, parentPoint.y, lineEndX, lineEndY, paint); - canvas.drawText(o.toString(), x, bottom, paint); - } - } - - @Override - protected void onDraw (Canvas canvas) { - super.onDraw(canvas); - - if (brackets == null) { - return; - } - - coords.clear(); - - float startX = getPaddingLeft(); - for (int i = 0; i < brackets.length; i++) { - Object child = brackets[i]; - - SparseArray copy = coords.clone(); - measureTree(child); - coords = copy; - float w = mr.width; - drawTree(canvas, startX, getPaddingTop(), getPaddingTop()+mr.height, null, child); - startX += w + SISTER_SKIP; - } - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - switch (ev.getAction()) { - case MotionEvent.ACTION_DOWN: - // Remember where the motion event started - lastMotionX = ev.getX(); - break; - case MotionEvent.ACTION_MOVE: - // Scroll to follow the motion event - float x = ev.getX(); - final int deltaX = (int) (lastMotionX - x); - lastMotionX = x; - int offset = computeHorizontalScrollOffset() + deltaX; - int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); - if (range > 0) { - if (offset < 0) - offset = 0; - if (offset > range) - offset = range; - scrollTo(offset, 0); - } - break; - case MotionEvent.ACTION_UP: - break; - } - return true; - } - - @Override - protected int computeHorizontalScrollRange() { - return (int) scrollRange; - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/RotationGestureDetector.java b/src/ui/android/src/org/grammaticalframework/ui/android/RotationGestureDetector.java deleted file mode 100644 index d077db1bc..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/RotationGestureDetector.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.view.MotionEvent; - -public class RotationGestureDetector { - - private static final int INVALID_POINTER_ID = -1; - private float fX, fY, sX, sY, focalX, focalY; - private int ptrID1, ptrID2; - private float mAngle; - private boolean firstTouch; - - private OnRotationGestureListener mListener; - - public RotationGestureDetector(OnRotationGestureListener listener) { - mListener = listener; - ptrID1 = INVALID_POINTER_ID; - ptrID2 = INVALID_POINTER_ID; - } - - public float getAngle() { - return mAngle; - } - - public boolean onTouchEvent(MotionEvent event){ - switch (event.getActionMasked()) { - case MotionEvent.ACTION_DOWN: - sX = event.getX(); - sY = event.getY(); - ptrID1 = event.getPointerId(0); - mAngle = 0; - firstTouch = true; - break; - case MotionEvent.ACTION_POINTER_DOWN: - fX = event.getX(); - fY = event.getY(); - focalX = getMidpoint(fX, sX); - focalY = getMidpoint(fY, sY); - ptrID2 = event.getPointerId(event.getActionIndex()); - mAngle = 0; - firstTouch = true; - break; - case MotionEvent.ACTION_MOVE: - if(ptrID1 != INVALID_POINTER_ID && ptrID2 != INVALID_POINTER_ID) { - float nfX, nfY, nsX, nsY; - nsX = event.getX(event.findPointerIndex(ptrID1)); - nsY = event.getY(event.findPointerIndex(ptrID1)); - nfX = event.getX(event.findPointerIndex(ptrID2)); - nfY = event.getY(event.findPointerIndex(ptrID2)); - if (firstTouch) { - mAngle = 0; - firstTouch = false; - } else { - mAngle = angleBetweenLines(fX, fY, sX, sY, nfX, nfY, nsX, nsY); - } - - if (mListener != null) { - mListener.OnRotation(this); - } - fX = nfX; - fY = nfY; - sX = nsX; - sY = nsY; - } - break; - case MotionEvent.ACTION_UP: - ptrID1 = INVALID_POINTER_ID; - break; - case MotionEvent.ACTION_POINTER_UP: - ptrID2 = INVALID_POINTER_ID; - break; - } - return true; - } - - private float getMidpoint(float a, float b) { - return (a + b) / 2; - } - - private float findAngleDelta(float angle1, float angle2) - { - angle2 = angle2 % 360.0f; - angle1 = angle1 % 360.0f; - - float dist = angle1 - angle2; - if (dist < -180.0f) - { - dist += 360.0f; - } - else if (dist > 180.0f) - { - dist -= 360.0f; - } - - return dist; - } - - private float angleBetweenLines(float fx1, float fy1, float fx2, float fy2, float sx1, float sy1, float sx2, float sy2) - { - float angle1 = (float) Math.atan2((fy1 - fy2), (fx1 - fx2)); - float angle2 = (float) Math.atan2((sy1 - sy2), (sx1 - sx2)); - - return findAngleDelta((float)Math.toDegrees(angle1),(float)Math.toDegrees(angle2)); - } - - public static interface OnRotationGestureListener { - public boolean OnRotation(RotationGestureDetector detector); - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraph.java b/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraph.java deleted file mode 100644 index 0033404c9..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraph.java +++ /dev/null @@ -1,235 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.util.*; - -public class SemanticGraph { - private Map nodes; - private List edges; - - private float layoutMinX; - private float layoutMaxX; - private float layoutMinY; - private float layoutMaxY; - - public SemanticGraph() { - nodes = new HashMap(); - edges = new ArrayList(); - - layoutMinX = 0; - layoutMaxX = 0; - layoutMinY = 0; - layoutMaxY = 0; - } - - public Node addNode(String lemma, List senses) { - Node n = nodes.get(lemma); - if (n == null) { - n = new Node(lemma, senses); - } - nodes.put(lemma,n); - return n; - } - - public Node getNode(String lemma) { - return nodes.get(lemma); - } - - public Collection getNodes() { - return Collections.unmodifiableCollection(nodes.values()); - } - - public Edge addEdge(Node node1, Node node2) { - Edge edge = new Edge(node1, node2); - edges.add(edge); - return edge; - } - - private static final int LAYOUT_ITERATIONS = 500; - private static final float LAYOUT_K = 2; - private static final float LAYOUT_C = 0.01f; - private static final float LAYOUT_MAX_VERTEX_MOVEMENT = 0.5f; - private static final float LAYOUT_MAX_REPULSIVE_FORCE_DISTANCE = 6; - - public void layout() { - layoutPrepare(); - for (int i = 0; i < LAYOUT_ITERATIONS; i++) { - layoutIteration(); - } - layoutCalcBounds(); - } - - public float getLayoutMinX() { - return layoutMinX; - } - - public float getLayoutMaxX() { - return layoutMaxX; - } - - public float getLayoutMinY() { - return layoutMinY; - } - - public float getLayoutMaxY() { - return layoutMaxY; - } - - private void layoutPrepare() { - for (Node node : nodes.values()) { - node.layoutForceX = 0; - node.layoutForceY = 0; - } - } - - private void layoutIteration() { - List prev = new ArrayList(); - for(Node node1 : this.nodes.values()) { - for (Node node2 : prev) { - layoutRepulsive(node1, node2); - } - prev.add(node1); - } - - // Forces on nodes due to edge attractions - for (Edge edge : edges) { - layoutAttractive(edge); - } - - // Move by the given force - for (Node node : nodes.values()) { - float xmove = LAYOUT_C * node.layoutForceX; - float ymove = LAYOUT_C * node.layoutForceY; - - float max = LAYOUT_MAX_VERTEX_MOVEMENT; - if (xmove > max) xmove = max; - if (xmove < -max) xmove = -max; - if (ymove > max) ymove = max; - if (ymove < -max) ymove = -max; - - node.layoutPosX += xmove; - node.layoutPosY += ymove; - node.layoutForceX = 0; - node.layoutForceY = 0; - } - } - - private void layoutRepulsive(Node node1, Node node2) { - float dx = node2.layoutPosX - node1.layoutPosX; - float dy = node2.layoutPosY - node1.layoutPosY; - float d2 = dx * dx + dy * dy; - if (d2 < 0.01) { - dx = (float) (0.1 * Math.random() + 0.1); - dy = (float) (0.1 * Math.random() + 0.1); - d2 = dx * dx + dy * dy; - } - float d = (float) Math.sqrt(d2); - if (d < LAYOUT_MAX_REPULSIVE_FORCE_DISTANCE) { - float repulsiveForce = LAYOUT_K * LAYOUT_K / d; - node2.layoutForceX += repulsiveForce * dx / d; - node2.layoutForceY += repulsiveForce * dy / d; - node1.layoutForceX -= repulsiveForce * dx / d; - node1.layoutForceY -= repulsiveForce * dy / d; - } - } - - private void layoutAttractive(Edge edge) { - Node node1 = edge.source; - Node node2 = edge.target; - - float dx = node2.layoutPosX - node1.layoutPosX; - float dy = node2.layoutPosY - node1.layoutPosY; - float d2 = dx * dx + dy * dy; - if (d2 < 0.01) { - dx = (float) (0.1 * Math.random() + 0.1); - dy = (float) (0.1 * Math.random() + 0.1); - d2 = dx * dx + dy * dy; - } - float d = (float) Math.sqrt(d2); - if (d > LAYOUT_MAX_REPULSIVE_FORCE_DISTANCE) { - d = LAYOUT_MAX_REPULSIVE_FORCE_DISTANCE; - d2 = d * d; - } - float attractiveForce = (d2 - LAYOUT_K * LAYOUT_K) / LAYOUT_K; - attractiveForce *= Math.log(edge.attraction) * 0.5 + 1; - - node2.layoutForceX -= attractiveForce * dx / d; - node2.layoutForceY -= attractiveForce * dy / d; - node1.layoutForceX += attractiveForce * dx / d; - node1.layoutForceY += attractiveForce * dy / d; - } - - private void layoutCalcBounds() { - float minx = Float.POSITIVE_INFINITY, - maxx = Float.NEGATIVE_INFINITY, - miny = Float.POSITIVE_INFINITY, - maxy = Float.NEGATIVE_INFINITY; - - for (Node node : nodes.values()) { - float x = node.layoutPosX; - float y = node.layoutPosY; - - if (x > maxx) maxx = x; - if (x < minx) minx = x; - if (y > maxy) maxy = y; - if (y < miny) miny = y; - } - - layoutMinX = minx; - layoutMaxX = maxx; - layoutMinY = miny; - layoutMaxY = maxy; - } - - public static class Node { - private String lemma; - private List senses; - - private float layoutPosX; - private float layoutPosY; - private float layoutForceX; - private float layoutForceY; - - - private Node(String lemma, List senses) { - this.lemma = lemma; - this.senses = senses; - - layoutPosX = 0; - layoutPosY = 0; - layoutForceX = 0; - layoutForceY = 0; - } - - public String getLemma() { - return lemma; - } - - public int getSenseCount() { - return senses.size(); - } - - public Object getSenseId(int i) { - return senses.get(i); - } - - public float getLayoutX() { - return layoutPosX; - } - - public float getLayoutY() { - return layoutPosY; - } - } - - public static class Edge { - private Node source; - private Node target; - private float attraction; - - private Edge(Node source, Node target) { - this.source = source; - this.target = target; - this.attraction = 1; - } - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphActivity.java b/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphActivity.java deleted file mode 100644 index 38878cc50..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphActivity.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.util.*; - -import android.app.Activity; -import android.app.SearchManager; -import android.os.Bundle; -import android.os.AsyncTask; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.ImageView; -import android.widget.Toast; -import android.content.Intent; - -import org.grammaticalframework.pgf.MorphoAnalysis; -import org.grammaticalframework.ui.android.LanguageSelector.OnLanguageSelectedListener; - -public class SemanticGraphActivity extends Activity { - private Translator mTranslator; - - private LanguageSelector mLanguageView; - private View mProgressBarView = null; - private ImageView mAddWordButton; - private SemanticGraphView mGraphView; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_semantic_graph); - - mTranslator = ((GFTranslator) getApplicationContext()).getTranslator(); - - mLanguageView = (LanguageSelector) findViewById(R.id.show_language); - mLanguageView.setLanguages(mTranslator.getAvailableLanguages()); - mLanguageView.setOnLanguageSelectedListener(new OnLanguageSelectedListener() { - @Override - public void onLanguageSelected(final Language language) { - new AsyncTask() { - @Override - protected void onPreExecute() { - showProgressBar(); - } - - @Override - protected Void doInBackground(Void... params) { - mTranslator.setSourceLanguage(language); - mTranslator.isTargetLanguageLoaded(); - return null; - } - - @Override - protected void onPostExecute(Void result) { - hideProgressBar(); - } - }.execute(); - } - }); - - mAddWordButton = (ImageView) findViewById(R.id.add_word); - - mGraphView = (SemanticGraphView) findViewById(R.id.semantic_graph); - - mAddWordButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - onSearchRequested(); - } - }); - - mProgressBarView = findViewById(R.id.progressBarView); - } - - @Override - protected void onResume() { - super.onResume(); - - mLanguageView.setSelectedLanguage(mTranslator.getSourceLanguage()); - } - - private void showProgressBar() { - mProgressBarView.setVisibility(View.VISIBLE); - } - - private void hideProgressBar() { - mProgressBarView.setVisibility(View.GONE); - } - - @Override - protected void onNewIntent (Intent intent) { - if (Intent.ACTION_SEARCH.equals(intent.getAction())) { - String query = intent.getStringExtra(SearchManager.QUERY); - List list = mTranslator.lookupMorpho(query); - if (list == null || list.size() == 0) { - Toast toast = Toast.makeText(this, "\""+query+"\" doesn't match", Toast.LENGTH_SHORT); - toast.show(); - } else { - mGraphView.getGraph().addNode(query, list); - mGraphView.refresh(); - } - } - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphManager.java b/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphManager.java deleted file mode 100644 index f3b26a3cf..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphManager.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.io.*; -import android.content.Context; -import android.util.Log; - -import org.grammaticalframework.sg.*; -import org.grammaticalframework.pgf.*; - -public class SemanticGraphManager implements Closeable { - private final Context mContext; - private SG mDB; - - public static final String DATABASE_FILE_NAME = "semantics.db"; - - public SemanticGraphManager(Context context) { - mContext = context; - mDB = null; - } - - private void createDatabaseFromAssets() throws SGError, IOException { - if (mDB != null) - return; - - String path = mContext.getDatabasePath(DATABASE_FILE_NAME).getPath(); - - boolean exists = false; - - File file = new File(path); - if (((GFTranslator) mContext.getApplicationContext()).getTranslator().isUpgraded("db_version")) { - file.delete(); - } else { - if (file.exists()) { - exists = true; - } - } - - File dir = new File(mContext.getApplicationInfo().dataDir + "/databases"); - if (!dir.exists()) { - dir.mkdir(); - } - - if (!extractDatabase(file)) - return; - - mDB = SG.openSG(path); - if (exists) - return; - } - - private boolean extractDatabase(File outFile) { - InputStream in = null; - OutputStream out = null; - try { - in = mContext.getAssets().open(DATABASE_FILE_NAME); - out = new FileOutputStream(outFile); - copyFile(in, out); - return true; - } catch(IOException e) { - Log.e("tag", "Failed to copy asset file: " + DATABASE_FILE_NAME, e); - } - finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - // NOOP - } - } - if (out != null) { - try { - out.close(); - } catch (IOException e) { - // NOOP - } - } - } - - return false; - } - - private void copyFile(InputStream in, OutputStream out) throws IOException { - byte[] buffer = new byte[1024]; - int read; - while((read = in.read(buffer)) != -1){ - out.write(buffer, 0, read); - } - } - - public void close() { - if (mDB != null) { - mDB.close(); - mDB = null; - } - } - - public TripleResult queryTriple(Expr subj, Expr pred, Expr obj) throws IOException { - createDatabaseFromAssets(); - return mDB.queryTriple(subj, pred, obj); - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphView.java b/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphView.java deleted file mode 100644 index 81785d5ce..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/SemanticGraphView.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.view.View; -import android.view.GestureDetector; -import android.view.ScaleGestureDetector; -import android.view.MotionEvent; -import android.graphics.Paint; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Rect; -import android.content.Context; -import android.util.AttributeSet; -import android.util.Log; - -public class SemanticGraphView extends View implements GestureDetector.OnGestureListener, ScaleGestureDetector.OnScaleGestureListener, RotationGestureDetector.OnRotationGestureListener { - - private SemanticGraph mGraph = new SemanticGraph(); - - private float mStartX = 0; - private float mStartY = 0; - private float mFocusX = 0; - private float mFocusY = 0; - private float mScale = 1; - private float mAngle = 0; - - private Paint mPaint; - - private GestureDetector mGD; - private ScaleGestureDetector mSGD; - private RotationGestureDetector mRGD; - - private static final float TEXT_PAD = 10; - private static final float SENSE_POINT_RADIUS = 5; - - public SemanticGraphView(Context context, AttributeSet attrs) { - super(context, attrs); - - mPaint = new Paint(); - mPaint.setTextSize(60); - - mGD = new GestureDetector(this); - mSGD = new ScaleGestureDetector(context,this); - mRGD = new RotationGestureDetector(this); - } - - public SemanticGraph getGraph() { - return mGraph; - } - - public void refresh() { - mGraph.layout(); - invalidate(); - } - - @Override - protected void onDraw (Canvas canvas) { - super.onDraw(canvas); - - canvas.scale(mScale,mScale,mFocusX,mFocusY); - canvas.translate(mStartX, mStartY); - canvas.rotate(mAngle); - - Rect bounds = new Rect(); - - float dx = mGraph.getLayoutMinX(); - float sx = getWidth()/(mGraph.getLayoutMaxX()-mGraph.getLayoutMinX()); - float dy = mGraph.getLayoutMinY(); - float sy = getHeight()/(mGraph.getLayoutMaxY()-mGraph.getLayoutMinY()); - for (SemanticGraph.Node node : mGraph.getNodes()) { - mPaint.getTextBounds(node.getLemma().toCharArray(), 0, node.getLemma().length(), bounds); - - float left = (node.getLayoutX()-dx)*sx - TEXT_PAD; - float base = (node.getLayoutY()-dy)*sy; - float top = base - bounds.height() - TEXT_PAD; - float right = left + bounds.right + TEXT_PAD; - float bottom = base + bounds.bottom + TEXT_PAD; - float sqrt2 = (float) Math.sqrt(2); - - canvas.drawText(node.getLemma(), left + TEXT_PAD, base, mPaint); - - float pi = (float) Math.PI; - for (int i = 0; i < node.getSenseCount(); i++) { - float phi = i * 2*pi / node.getSenseCount(); - float cx = ((left+right) + (right-left)*sqrt2*((float) Math.sin(phi)))/2; - float cy = ((top+bottom) + (bottom-top)*sqrt2*((float) Math.cos(phi)))/2; - - canvas.drawCircle(cx,cy,SENSE_POINT_RADIUS,mPaint); - } - } - } - - public boolean onTouchEvent(MotionEvent ev) { - mGD.onTouchEvent(ev); - mSGD.onTouchEvent(ev); - mRGD.onTouchEvent(ev); - return true; - } - - public boolean onDown(MotionEvent e) { - return true; - } - - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - return true; - } - - public void onLongPress(MotionEvent e) { - } - - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { - mStartX -= distanceX; - mStartY -= distanceY; - invalidate(); - return true; - } - - public void onShowPress(MotionEvent e) { - } - - public boolean onSingleTapUp(MotionEvent e) { - return true; - } - - public boolean onScaleBegin(ScaleGestureDetector detector) { - return true; - } - - public boolean onScale(ScaleGestureDetector detector) { - mScale *= detector.getScaleFactor(); - mFocusX = detector.getFocusX(); - mFocusY = detector.getFocusY(); - invalidate(); - return true; - } - - public void onScaleEnd(ScaleGestureDetector detector) { - } - - public boolean OnRotation(RotationGestureDetector detector) { - mAngle -= detector.getAngle(); - invalidate(); - return true; - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/TTS.java b/src/ui/android/src/org/grammaticalframework/ui/android/TTS.java deleted file mode 100644 index 3e020f0af..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/TTS.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.content.Context; -import android.media.AudioManager; -import android.speech.tts.TextToSpeech; -import android.util.Log; - -import java.util.HashMap; -import java.util.Locale; - -public class TTS { - - private static final String TAG = "TTS"; - - private TextToSpeech mTts; - private AudioManager mAudioManager; - - public TTS(Context context) { - mTts = new TextToSpeech(context, new InitListener()); - mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); - } - - // TODO: handle speak() calls before service connects - public void speak(String language, String text) { - - - if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) { - - /* hack for missing TTS -- don't use for official release! - if (language.equals("bg-BG")) { - language = "ru-RU"; - } - if (language.equals("ca-ES")) { - language = "es-ES"; // hardly politically correct... - } - */ - - /* Google Chinese speech input has a nonstandard code. In output, yue works for Chi in Google, but SVOX uses the standard zh-CN */ - if (language.equals("cmn-Hans-CN")) { - language = "zh-CN"; - } - - Locale locale = LocaleUtils.parseJavaLocale(language.replace('-', '_'), - Locale.getDefault()); - - int result = mTts.setLanguage(locale); - if (result == TextToSpeech.LANG_MISSING_DATA || - result == TextToSpeech.LANG_NOT_SUPPORTED) { - Log.e(TAG, "Language is not available"); - } else { - HashMap params = new HashMap(); - mTts.speak(text, TextToSpeech.QUEUE_FLUSH, params); - } - } - } - - public void destroy() { - if (mTts != null) { - mTts.stop(); - mTts.shutdown(); - } - } - - private class InitListener implements TextToSpeech.OnInitListener { - @Override - public void onInit(int status) { - if (status == TextToSpeech.SUCCESS) { - Log.d(TAG, "Initialized TTS"); - } else { - Log.e(TAG, "Failed to initialize TTS"); - } - } - - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/Translator.java b/src/ui/android/src/org/grammaticalframework/ui/android/Translator.java deleted file mode 100644 index 4bfe9690a..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/Translator.java +++ /dev/null @@ -1,777 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.content.Context; -import android.content.SharedPreferences; -import android.content.pm.PackageManager.NameNotFoundException; -import android.util.Log; -import android.util.Pair; -import android.net.Uri; -import android.view.inputmethod.CompletionInfo; -import android.database.sqlite.SQLiteDatabase; -import android.database.Cursor; - -import org.grammaticalframework.sg.*; -import org.grammaticalframework.pgf.*; -import java.io.*; -import java.util.*; - -public class Translator { - - private static final String TAG = "Translator"; - - // new - - // TODO: allow changing - private String mGrammar = "App.pgf" ; - - // TODO: build dynamically? - private Language[] mLanguages = { - new Language("bg-BG", "Bulgarian", "AppBul", R.xml.cyrillic), - new Language("ca-ES", "Catalan", "AppCat", R.xml.qwerty), - new Language("cmn-Hans-CN", "Chinese", "AppChi", R.xml.qwerty), - // new Language("zh-CN", "Chinese", "AppChi", R.xml.qwerty), - // new Language("yue", "Chinese (Cantonese)", "AppChi", R.xml.qwerty), - // new Language("cmn-Hans-CN", "Chinese (Mandarin)", "AppChi", R.xml.qwerty), - new Language("nl-NL", "Dutch", "AppDut", R.xml.qwerty), - new Language("en-US", "English", "AppEng", R.xml.qwerty), - new Language("et-EE", "Estonian","AppEst", R.xml.nordic), - new Language("fi-FI", "Finnish", "AppFin", R.xml.nordic), - new Language("fr-FR", "French", "AppFre", R.xml.qwerty), //// - new Language("de-DE", "German", "AppGer", R.xml.qwerty), - new Language("hi-IN", "Hindi", "AppHin", R.xml.devanagari_page1, R.xml.devanagari_page2), - new Language("it-IT", "Italian", "AppIta", R.xml.qwerty), - new Language("ja-JP", "Japanese","AppJpn", R.xml.qwerty), - new Language("ru-RU", "Russian", "AppRus", R.xml.cyrillic), - new Language("es-ES", "Spanish", "AppSpa", R.xml.qwerty), - new Language("sv-SE", "Swedish", "AppSwe", R.xml.nordic), - new Language("th-TH", "Thai", "AppTha", R.xml.thai_page1, R.xml.thai_page2), - new Language("ur-PK", "Urdu", "AppUrd", R.xml.qwerty), // TODO language code and keyboard to check - }; - - private Context mContext; - - private GrammarLoader mGrammarLoader; - private ConcrLoader mSourceLoader; - private ConcrLoader mTargetLoader; - private ConcrLoader mOtherLoader; - private SemanticGraphManager mSGManager; - - private static final String SOURCE_LANG_KEY = "source_lang"; - private static final String TARGET_LANG_KEY = "target_lang"; - - public static final String WORDS = "words"; - public static final String SENTENCES = "sentences"; - - private static final int NUM_ALT_TRANSLATIONS = 10; - - private SharedPreferences mSharedPref; - - private Language getPrefLang(String key, int def) { - int index = mSharedPref.getInt(key, def); - if (index < 0 || index >= mLanguages.length) - index = def; - return mLanguages[index]; - } - - private void setPrefLang(String key, Language def) { - for (int index = 0; index < mLanguages.length; index++) { - if (def == mLanguages[index]) { - SharedPreferences.Editor editor = mSharedPref.edit(); - editor.putInt(key, index); - editor.commit(); - break; - } - } - } - - public Translator(Context context) { - mContext = context; - - mSharedPref = context.getSharedPreferences( - context.getString(R.string.global_preferences_key), Context.MODE_PRIVATE); - - mGrammarLoader = new GrammarLoader(); - mGrammarLoader.start(); - - Language prefSourceLang = getPrefLang(SOURCE_LANG_KEY, 0); - Language prefTargetLang = getPrefLang(TARGET_LANG_KEY, 1); - - mSourceLoader = new ConcrLoader(prefSourceLang); - mSourceLoader.start(); - - if (prefSourceLang == prefTargetLang) { - mTargetLoader = mSourceLoader; - } else { - mTargetLoader = new ConcrLoader(prefTargetLang); - mTargetLoader.start(); - } - - mOtherLoader = null; - - mSGManager = new SemanticGraphManager(context); - } - - public List getAvailableLanguages() { - return Arrays.asList(mLanguages); - } - - public Language getSourceLanguage() { - return mSourceLoader.getLanguage(); - } - - public void setSourceLanguage(Language language) { - setPrefLang(SOURCE_LANG_KEY, language); - - if (mSourceLoader.getLanguage() == language) - return; - if (mTargetLoader.getLanguage() == language) { - cacheOrUnloadLanguage(mSourceLoader); - mSourceLoader = mTargetLoader; - return; - } - if (mOtherLoader != null && - mOtherLoader.getLanguage() == language) { - ConcrLoader tmp = mSourceLoader; - mSourceLoader = mOtherLoader; - mOtherLoader = tmp; - return; - } - - try { - mSourceLoader.join(); - } catch (InterruptedException e) { - Log.e(TAG, "Loading interrupted", e); - } - - if (mSourceLoader.getLanguage() != mTargetLoader.getLanguage()) { - cacheOrUnloadLanguage(mSourceLoader); - } - - mSourceLoader = new ConcrLoader(language); - mSourceLoader.start(); - } - - public boolean isSourceLanguageLoaded() { - try { - mSourceLoader.join(); - return true; - } catch (InterruptedException e) { - Log.e(TAG, "Loading interrupted", e); - } - return false; - } - - private Concr getSourceConcr() { - try { - mSourceLoader.join(); - } catch (InterruptedException e) { - Log.e(TAG, "Loading interrupted", e); - } - return mSourceLoader.getConcr(); - } - - public Language getTargetLanguage() { - return mTargetLoader.getLanguage(); - } - - public void setTargetLanguage(Language language) { - setPrefLang(TARGET_LANG_KEY, language); - - if (mTargetLoader.getLanguage() == language) - return; - if (mSourceLoader.getLanguage() == language) { - cacheOrUnloadLanguage(mTargetLoader); - mTargetLoader = mSourceLoader; - return; - } - if (mOtherLoader != null && - mOtherLoader.getLanguage() == language) { - ConcrLoader tmp = mTargetLoader; - mTargetLoader = mOtherLoader; - mOtherLoader = tmp; - return; - } - - try { - mTargetLoader.join(); - } catch (InterruptedException e) { - Log.e(TAG, "Loading interrupted", e); - } - - if (mSourceLoader.getLanguage() != mTargetLoader.getLanguage()) { - cacheOrUnloadLanguage(mTargetLoader); - } - - mTargetLoader = new ConcrLoader(language); - mTargetLoader.start(); - } - - public boolean isTargetLanguageLoaded() { - try { - mTargetLoader.join(); - return true; - } catch (InterruptedException e) { - Log.e(TAG, "Loading interrupted", e); - } - return false; - } - - private Concr getTargetConcr() { - try { - mTargetLoader.join(); - } catch (InterruptedException e) { - Log.e(TAG, "Loading interrupted", e); - } - return mTargetLoader.getConcr(); - } - - private void cacheOrUnloadLanguage(ConcrLoader loader) { - if (mOtherLoader != null) { - mOtherLoader.getConcr().unload(); - Log.d(TAG, mOtherLoader.getLanguage().getConcrete() + ".pgf_c unloaded"); - } - mOtherLoader = loader; - } - - public void switchLanguages() { - ConcrLoader tmp = mSourceLoader; - mSourceLoader = mTargetLoader; - mTargetLoader = tmp; - } - - private static String explode(String in) { - String out = ""; - for (int i = 0; i < in.length(); i++) { - if (i > 0) - out += ' '; - out += in.charAt(i); - } - return out; - } - - private static String implode(String s) { - return s.replaceAll("(? iter = sourceLang.parse("Chunk", input).iterator(); // try parse as chunk - Expr expr = iter.next().getExpr(); - output = targetLang.linearize(expr); - return output ; - } catch (ParseError e) { // if this fails - List morphos = lookupMorpho(input) ; // lookup morphological analyses - - morphos.addAll(lookupMorpho(lowerinput)) ; // including the analyses of the lower-cased word - - for (MorphoAnalysis ana : morphos) { - if (targetLang.hasLinearization(ana.getLemma())) { // check that the word has linearization in target - output = targetLang.linearize(Expr.readExpr(ana.getLemma())) ; - break ; // if yes, don't search any more - } - } - return output ; - } - } - - private String translateByLookup(String input) { - String[] words = input.split(" ") ; - - String output = "%" ; - for (String w : words) { - output = output + " " + translateWord(w) ; - } - - return output ; - } - - // lowercase the first word if (1) it is not in the lexicon and (2) its lowercase version is in the lexicon - // otherwise it will be left uppercase and treated as a name - private String lowercaseIfBetter(String input) { - String[] words = input.split(" ") ; - - String firstword = words[0] ; - - String lowerfirstword = firstword.toLowerCase() ; - - if (lookupMorpho(firstword).isEmpty() && !(lookupMorpho(lowerfirstword).isEmpty())) { - words[0] = lowerfirstword ; - String output = "" ; - for (String w : words) { - output = output + " " + w ; - } - return output ; - } else { - return input ; - } - - } - - /** - * Takes a lot of time. Must not be called on the main thread. - */ - public Pair> translate(String input) { - if (getSourceLanguage().getLangCode().equals("cmn-Hans-CN")) { - // for Chinese we need to put space after every character - input = explode(input); - } else { - input = lowercaseIfBetter(input); - } ; - - String output = null; - List exprs = new ArrayList(); - - try { - Concr sourceLang = getSourceConcr(); - Concr targetLang = getTargetConcr(); - - Map callbacks = new HashMap(); - callbacks.put("PN", new NercLiteralCallback(mGrammarLoader.getGrammar(), sourceLang, input)); - callbacks.put("Symb", new UnknownLiteralCallback(sourceLang, input)); - - int count = NUM_ALT_TRANSLATIONS; - for (ExprProb ep : sourceLang.parseWithHeuristics(getGrammar().getStartCat(), input, -1, callbacks)) { - if (count-- <= 0) - break; - exprs.add(ep); - if (output == null) - output = targetLang.linearize(ep.getExpr()); - } - } catch (ParseError e) { - output = translateByLookup(input); - } - - if (output == null) - output = "% "; // make sure that we return something - - if (getTargetLanguage().getLangCode().equals("cmn-Hans-CN") || - getTargetLanguage().getLangCode().equals("ja-JP") || - getTargetLanguage().getLangCode().equals("th-TH")) - output = implode(output) ; - - return new Pair>(output, exprs); - } - - public String linearize(Expr expr) { - Concr targetLang = getTargetConcr(); - String s = targetLang.linearize(expr); - if (s == null) - s = "% "; // make sure that we return something - - if (getTargetLanguage().getLangCode().equals("cmn-Hans-CN") || - getTargetLanguage().getLangCode().equals("ja-JP") || - getTargetLanguage().getLangCode().equals("th-TH")) - return implode(s); - else - return s; - } - - public String linearizeSource(Expr expr) { - Concr targetLang = getSourceConcr(); - String s = targetLang.linearize(expr); - if (s == null) - s = "% "; // make sure that we return something - - if (getSourceLanguage().getLangCode().equals("cmn-Hans-CN") || - getSourceLanguage().getLangCode().equals("ja-JP") || - getSourceLanguage().getLangCode().equals("th-TH")) - return implode(s); - else - return s; - } - - public Object[] bracketedLinearize(Expr expr) { - Concr targetLang = getTargetConcr(); - return targetLang.bracketedLinearize(expr); - } - - public String generateLexiconEntry(Expr lemma) { - Concr sourceLang = getSourceConcr(); - Concr targetLang = getTargetConcr(); - String fun = lemma.toString(); - String cat = getGrammar().getFunctionType(fun).getCategory(); - - Expr e2 = Expr.readExpr("MkTag (Inflection"+cat+" "+fun+")"); - - if (targetLang.hasLinearization("Inflection"+cat)) { - if (targetLang.hasLinearization(fun)) - return sourceLang.linearize(lemma) + " - " + targetLang.linearize(e2) + ". " + targetLang.linearize(lemma); - else - return sourceLang.linearize(lemma) + " " + targetLang.linearize(e2)+"."; - } else { - if (targetLang.hasLinearization(fun)) - return sourceLang.linearize(lemma) + " - " + targetLang.linearize(lemma); - else - return sourceLang.linearize(lemma); - } - } - - private static final Expr gloss_pred = Expr.readExpr("gloss"); - private static final Expr topic_pred = Expr.readExpr("topic"); - private static final Expr example_pred = Expr.readExpr("example"); - - public Expr getDefinition(Expr lemma, boolean withExample) { - Expr gloss = null; - Expr example = null; - Map topics = new TreeMap(); - - try { - TripleResult res = mSGManager.queryTriple(lemma, null, null); - while (res.hasNext()) { - if (res.getPredicate().equals(gloss_pred)) - gloss = res.getObject(); - else if (res.getPredicate().equals(topic_pred)) - updateWordsMap(res.getObject(), topics); - else if (res.getPredicate().equals(example_pred)) - example = res.getObject(); - } - res.close(); - } catch (IOException e) { - // nothing - } catch (SGError e) { - // nothing - } - - Expr topic = null; - if (topics.size() > 0) { - StringBuilder builder = new StringBuilder(); - builder.append('('); - buildWordsHtml(topics, builder); - builder.append(')'); - topic = new Expr(builder.toString()); - } - if (gloss == null) - return topic; - else { - if (topic == null) - topic = new Expr(""); - if (withExample && example != null) - return new Expr("MkDefinitionEx", topic, gloss, example); - else - return new Expr("MkDefinition", topic, gloss); - } - } - - private void updateWordsMap(Expr expr, Map map) { - String word = getTargetConcr().linearize(expr); - - Uri.Builder builder = map.get(word); - if (builder == null) { - builder = new Uri.Builder(); - builder.scheme("gf-translator"); - builder.authority(WORDS); - builder.appendQueryParameter("source", word); - map.put(word,builder); - } - builder.appendQueryParameter("alternative", expr.toString()); - } - - private void buildWordsHtml(Map map, StringBuilder sbuilder) { - boolean first = true; - for (Map.Entry entry : map.entrySet()) { - if (first) - first = false; - else - sbuilder.append(", "); - - sbuilder.append(""+entry.getKey()+""); - } - } - - public List getTopicWords(Expr lemma) { - TripleResult res = null; - List words = new ArrayList(); - try { - res = mSGManager.queryTriple(null, topic_pred, lemma); - while (res.hasNext()) { - words.add(res.getSubject()); - } - } catch (IOException e) { - // nothing - } catch (SGError e) { - // nothing - } finally { - if (res != null) - res.close(); - } - return words; - } - - private Expr getTopicWordsHtml(Expr lemma) { - StringBuilder sbuilder = new StringBuilder(); - TripleResult res = null; - try { - res = mSGManager.queryTriple(null, topic_pred, lemma); - Map map = new TreeMap(); - while (res.hasNext()) { - updateWordsMap(res.getSubject(), map); - } - - StringBuilder builder = new StringBuilder(); - buildWordsHtml(map, builder); - return new Expr(builder.toString()); - } catch (IOException e) { - // nothing - } catch (SGError e) { - // nothing - } finally { - if (res != null) - res.close(); - } - return null; - } - - public String getInflectionTable(Expr lemma) { - boolean withExample = - (getSourceLanguage().getLangCode().equals("en-US") || - getTargetLanguage().getLangCode().equals("en-US")); - Expr def = - getDefinition(lemma, withExample); - - String fun = lemma.toString(); - Concr targetLang = getTargetConcr(); - String cat = getGrammar().getFunctionType(fun).getCategory(); - - if (targetLang.hasLinearization(fun) && - targetLang.hasLinearization("Inflection"+cat)) { - if (def == null) - def = Expr.readExpr("NoDefinition"); - - Expr e = new Expr("MkDocument", - def, - new Expr("Inflection"+cat,lemma), - getTopicWordsHtml(lemma)); - String html = - "" + - targetLang.linearize(e) + - ""; - return html; - } else if (def != null) { - String html = - "" + - targetLang.linearize(def) + - ""; - return html; - } else { - return null; - } - } - - public List getTopicsOf(Expr lemma) { - TripleResult res = null; - List topics = new ArrayList(); - try { - res = mSGManager.queryTriple(lemma, topic_pred, null); - while (res.hasNext()) { - topics.add(res.getObject()); - } - } catch (IOException e) { - // nothing - } catch (SGError e) { - // nothing - } finally { - if (res != null) - res.close(); - } - return topics; - } - - private static String escapeHtml(CharSequence text) { - StringBuilder out = new StringBuilder(); - - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - - if (c == '<') { - out.append("<"); - } else if (c == '>') { - out.append(">"); - } else if (c == '&') { - out.append("&"); - } else if (c == '"') { - out.append("""); - } else if (c > 0x7E || c < ' ') { - out.append("&#").append((int) c).append(";"); - } else if (c == ' ') { - while (i + 1 < text.length() && text.charAt(i + 1) == ' ') { - out.append(" "); - i++; - } - - out.append(' '); - } else { - out.append(c); - } - } - - return out.toString(); - } - - public List lookupMorpho(String sentence) { - List ans = getSourceConcr().lookupMorpho(sentence); - Collections.sort(ans, new Comparator() { - public int compare(MorphoAnalysis a1, MorphoAnalysis a2) { - if (a1.getProb() > a2.getProb()) - return 1; - else if (a1.getProb() < a2.getProb()) - return -1; - else - return 0; - } - }); - return ans; - } - - public CompletionInfo[] lookupWordPrefix(String prefix) { - PriorityQueue queue = - new PriorityQueue(500, new Comparator() { - @Override - public int compare(FullFormEntry lhs, FullFormEntry rhs) { - return Double.compare(lhs.getProb(), rhs.getProb()); - } - }); - for (FullFormEntry entry : getSourceConcr().lookupWordPrefix(prefix)) { - queue.add(entry); - if (queue.size() >= 1000) - break; - } - - CompletionInfo[] completions = new CompletionInfo[Math.min(queue.size(), 5)+1]; - completions[0] = new CompletionInfo(0, 0, prefix); - for (int i = 1; i < completions.length; i++) { - completions[i] = new CompletionInfo(i,i,queue.poll().getForm()); - } - - if (completions.length > 1) { - Arrays.sort(completions, 1, completions.length-1, new Comparator() { - @Override - public int compare(CompletionInfo arg0, CompletionInfo arg1) { - return ((String) arg0.getText()).compareTo((String) arg1.getText()); - } - }); - } - - return completions; - } - - private PGF getGrammar() { - try { - mGrammarLoader.join(); - } catch (InterruptedException e) { - Log.e(TAG, "Loading interrupted", e); - } - return mGrammarLoader.getGrammar(); - } - - private class GrammarLoader extends Thread { - private PGF mPGF; - - public GrammarLoader() { - mPGF = null; - } - - public PGF getGrammar() { - return mPGF; - } - - public void run() { - InputStream in = null; - - try { - in = mContext.getAssets().open(mGrammar); - Log.d(TAG, "Trying to open " + mGrammar); - long t1 = System.currentTimeMillis(); - mPGF = PGF.readPGF(in); - long t2 = System.currentTimeMillis(); - Log.d(TAG, mGrammar + " loaded ("+(t2-t1)+" ms)"); - } catch (FileNotFoundException e) { - Log.e(TAG, "File not found", e); - } catch (IOException e) { - Log.e(TAG, "Error loading grammar", e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - Log.e(TAG, "Error closing the stream", e); - } - } - } - } - } - - private class ConcrLoader extends Thread { - private Language mLanguage; - private Concr mConcr; - - public ConcrLoader(Language lang) { - this.mLanguage = lang; - this.mConcr = null; - } - - public Language getLanguage() { - return mLanguage; - } - - public Concr getConcr() { - return mConcr; - } - - public void run() { - try { - mGrammarLoader.join(); - } catch (InterruptedException e) { - Log.d(TAG, "interrupted", e); - } - - InputStream in = null; - - try { - String name = mLanguage.getConcrete()+".pgf_c"; - in = mContext.getAssets().open(name); - Log.d(TAG, "Trying to load " + name); - long t1 = System.currentTimeMillis(); - mConcr = mGrammarLoader.getGrammar().getLanguages().get(mLanguage.getConcrete()); - mConcr.load(in); - long t2 = System.currentTimeMillis(); - Log.d(TAG, name + " loaded ("+(t2-t1)+" ms)"); - } catch (FileNotFoundException e) { - Log.e(TAG, "File not found", e); - } catch (IOException e) { - Log.e(TAG, "Error loading concrete", e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - Log.e(TAG, "Error closing the stream", e); - } - } - } - } - } - - public boolean isUpgraded(String key) { - int old_code = mSharedPref.getInt(key, 0); - - int new_code = 0; - try { - new_code = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode; - } catch (NameNotFoundException e) { - // Huh? Really? - } - - SharedPreferences.Editor editor = mSharedPref.edit(); - editor.putInt(key, new_code); - editor.commit(); - - return (old_code != new_code); - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorInputMethodService.java b/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorInputMethodService.java deleted file mode 100644 index d621e2f69..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorInputMethodService.java +++ /dev/null @@ -1,666 +0,0 @@ -package org.grammaticalframework.ui.android; - -import android.inputmethodservice.InputMethodService; -import android.text.InputType; -import android.text.method.MetaKeyKeyListener; -import android.view.KeyCharacterMap; -import android.view.KeyEvent; -import android.view.View; -import android.view.inputmethod.CompletionInfo; -import android.view.inputmethod.EditorInfo; -import android.view.inputmethod.InputConnection; - - -public class TranslatorInputMethodService extends InputMethodService - implements android.inputmethodservice.KeyboardView.OnKeyboardActionListener { - - private TranslatorKeyboardView mInputView; - private CompletionsView mCandidateView; - private CompletionInfo[] mCompletions; - - private StringBuilder mComposingText = new StringBuilder(); - private StringBuilder mComposingWord = new StringBuilder(); - private boolean mPredictionOn; - private boolean mCompletionOn; - private boolean mCapsLock; - private long mLastShiftTime; - private long mMetaState; - - private TranslatorKeyboard mSymbolsPage1Keyboard; - private TranslatorKeyboard mSymbolsPage2Keyboard; - private TranslatorKeyboard mLanguagePage1Keyboard; - private TranslatorKeyboard mLanguagePage2Keyboard; - - private TranslatorKeyboard mCurKeyboard; - - private int mActionId; - - private Translator mTranslator; - - @Override - public void onCreate() { - super.onCreate(); - - mTranslator = ((GFTranslator) getApplicationContext()).getTranslator(); - - mSymbolsPage1Keyboard = null; - mSymbolsPage2Keyboard = null; - mLanguagePage1Keyboard = null; - mLanguagePage2Keyboard = null; - } - - @Override - public View onCreateInputView() { - mInputView = (TranslatorKeyboardView) - getLayoutInflater().inflate(R.layout.input, null); - mInputView.setOnKeyboardActionListener(this); - mInputView.setKeyboard(mCurKeyboard); - return mInputView; - } - - @Override - public View onCreateCandidatesView() { - mCandidateView = new CompletionsView(this); - mCandidateView.setService(this); - return mCandidateView; - } - - private int mModeId; - private EditorInfo mAttribute; - private static TranslatorInputMethodService mInstance; - - static TranslatorInputMethodService getInstance() { - return mInstance; - } - - @Override - public void onStartInput(EditorInfo attribute, boolean restarting) { - super.onStartInput(attribute, restarting); - - // Reset our state. We want to do this even if restarting, because - // the underlying state of the text editor could have changed in any way. - mComposingText.setLength(0); - mComposingWord.setLength(0); - updateCandidates(); - - if (!restarting) { - // Clear shift states. - mMetaState = 0; - } - - mPredictionOn = false; - mCompletionOn = false; - mCompletions = null; - - int res1 = - mTranslator.getSourceLanguage().getKeyboardPage1Resource(); - int res2 = - mTranslator.getSourceLanguage().getKeyboardPage2Resource(); - mModeId = R.string.normalKeyboardMode; - if (attribute.extras != null && - !attribute.extras.getBoolean("show_language_toggle", true)) { - mModeId = R.string.internalKeyboardMode; - } - mAttribute = attribute; - mLanguagePage1Keyboard = new TranslatorKeyboard(this, res1, mModeId); - mLanguagePage2Keyboard = new TranslatorKeyboard(this, res2, mModeId); - mSymbolsPage1Keyboard = new TranslatorKeyboard(this, R.xml.symbols_page1, mModeId); - mSymbolsPage2Keyboard = new TranslatorKeyboard(this, R.xml.symbols_page2, mModeId); - - // We are now going to initialize our state based on the type of - // text being edited. - switch (attribute.inputType & InputType.TYPE_MASK_CLASS) { - case InputType.TYPE_CLASS_NUMBER: - case InputType.TYPE_CLASS_DATETIME: - // Numbers and dates default to the symbols keyboard, with - // no extra features. - mCurKeyboard = mSymbolsPage1Keyboard; - break; - - case InputType.TYPE_CLASS_PHONE: - // Phones will also default to the symbols keyboard, though - // often you will want to have a dedicated phone keyboard. - mCurKeyboard = mSymbolsPage1Keyboard; - break; - - case InputType.TYPE_CLASS_TEXT: - // This is general text editing. We will default to the - // normal alphabetic keyboard, and assume that we should - // be doing predictive text (showing candidates as the - // user types). - mCurKeyboard = mLanguagePage1Keyboard; - mPredictionOn = true; - - // We now look for a few special variations of text that will - // modify our behavior. - int variation = attribute.inputType & InputType.TYPE_MASK_VARIATION; - if (variation == InputType.TYPE_TEXT_VARIATION_PASSWORD || - variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD || - variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) { - // Do not display predictions / what the user is typing - // when they are entering a password. - mPredictionOn = false; - } - - if (variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || - variation == InputType.TYPE_TEXT_VARIATION_URI || - variation == InputType.TYPE_TEXT_VARIATION_FILTER) { - // Our predictions are not useful for e-mail addresses - // or URIs. - mPredictionOn = false; - } - - if ((attribute.inputType & InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { - // If this is an auto-complete text view, then our predictions - // will not be shown and instead we will allow the editor - // to supply their own. We only show the editor's - // candidates when in full-screen mode, otherwise relying - // own it displaying its own UI. - mPredictionOn = false; - mCompletionOn = isFullscreenMode(); - } - - // We also want to look at the current state of the editor - // to decide whether our alphabetic keyboard should start out - // shifted. - updateShiftKeyState(attribute); - break; - - default: - // For all unknown input types, default to the alphabetic - // keyboard with no special features. - mCurKeyboard = mLanguagePage1Keyboard; - updateShiftKeyState(attribute); - } - - mActionId = attribute.imeOptions & (EditorInfo.IME_MASK_ACTION | EditorInfo.IME_FLAG_NO_ENTER_ACTION); - mLanguagePage1Keyboard.setImeOptions(getResources(), attribute.imeOptions); - mLanguagePage2Keyboard.setImeOptions(getResources(), attribute.imeOptions); - - mInstance = this; - } - - @Override - public void onFinishInput() { - super.onFinishInput(); - - // Clear current composing text and candidates. - mComposingText.setLength(0); - mComposingWord.setLength(0); - updateCandidates(); - - // We only hide the candidates window when finishing input on - // a particular editor, to avoid popping the underlying application - // up and down if the user is entering text into the bottom of - // its window. - setCandidatesViewShown(false); - - mCurKeyboard = mLanguagePage1Keyboard; - if (mInputView != null) { - mInputView.closing(); - } - - mInstance = null; - mAttribute = null; - } - - @Override - public void onStartInputView(EditorInfo attribute, boolean restarting) { - super.onStartInputView(attribute, restarting); - // Apply the selected keyboard to the input view. - mInputView.setKeyboard(mCurKeyboard); - mInputView.closing(); - } - - @Override - public void onUpdateSelection(int oldSelStart, int oldSelEnd, - int newSelStart, int newSelEnd, - int candidatesStart, int candidatesEnd) { - super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, - candidatesStart, candidatesEnd); - - // If the current selection in the text view changes, we should - // clear whatever candidate text we have. - if (mComposingText.length() + mComposingWord.length() > 0 && - (newSelStart != candidatesEnd || newSelEnd != candidatesEnd)) { - mComposingText.setLength(0); - mComposingWord.setLength(0); - updateCandidates(); - InputConnection ic = getCurrentInputConnection(); - if (ic != null) { - ic.finishComposingText(); - } - } - } - - @Override - public void onDisplayCompletions(CompletionInfo[] completions) { - if (mCompletionOn) { - mCompletions = completions; - if (completions == null) { - setSuggestions(null, false, false); - return; - } - - setSuggestions(completions, true, true); - } - } - - /** - * This translates incoming hard key events in to edit operations on an - * InputConnection. It is only needed when using the - * PROCESS_HARD_KEYS option. - */ - private boolean translateKeyDown(int keyCode, KeyEvent event) { - mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState, - keyCode, event); - int c = event.getUnicodeChar(MetaKeyKeyListener.getMetaState(mMetaState)); - mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState); - InputConnection ic = getCurrentInputConnection(); - if (c == 0 || ic == null) { - return false; - } - - if ((c & KeyCharacterMap.COMBINING_ACCENT) != 0) { - c = c & KeyCharacterMap.COMBINING_ACCENT_MASK; - } - - if (mComposingWord.length() > 0) { - char accent = mComposingWord.charAt(mComposingWord.length()-1); - int composed = KeyEvent.getDeadChar(accent, c); - - if (composed != 0) { - c = composed; - mComposingWord.setLength(mComposingWord.length()-1); - } - } - - onKey(c, null); - - return true; - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - switch (keyCode) { - case KeyEvent.KEYCODE_BACK: - // The InputMethodService already takes care of the back - // key for us, to dismiss the input method if it is shown. - // However, our keyboard could be showing a pop-up window - // that back should dismiss, so we first allow it to do that. - if (event.getRepeatCount() == 0 && mInputView != null) { - if (mInputView.handleBack()) { - return true; - } - } - break; - - case KeyEvent.KEYCODE_DEL: - // Special handling of the delete key: if we currently are - // composing text for the user, we want to modify that instead - // of let the application to the delete itself. - if (mComposingText.length() + mComposingWord.length() > 0) { - onKey(TranslatorKeyboard.KEYCODE_DELETE, null); - return true; - } - break; - - case KeyEvent.KEYCODE_ENTER: - // Let the underlying text editor always handle these. - return false; - - default: - if (mPredictionOn && translateKeyDown(keyCode, event)) { - return true; - } - } - - return super.onKeyDown(keyCode, event); - } - - /** - * Helper function to commit any text being composed in to the editor. - */ - private void commitTyped(InputConnection inputConnection) { - if (mComposingText.length() + mComposingWord.length() > 0) { - String s = getComposingString(); - inputConnection.commitText(s, s.length()); - mComposingText.setLength(0); - mComposingWord.setLength(0); - updateCandidates(); - } - } - - /** - * Helper to update the shift state of our keyboard based on the initial - * editor state. - */ - private void updateShiftKeyState(EditorInfo attr) { - if (attr != null && mInputView != null && - (mLanguagePage1Keyboard == mInputView.getKeyboard() || - mLanguagePage2Keyboard == mInputView.getKeyboard())) { - int caps = 0; - EditorInfo ei = getCurrentInputEditorInfo(); - if (ei != null && ei.inputType != InputType.TYPE_NULL) { - caps = getCurrentInputConnection().getCursorCapsMode(attr.inputType); - } - mInputView.setShifted(mCapsLock || caps != 0); - } - } - - /** - * Helper to send a key down / key up pair to the current editor. - */ - private void keyDownUp(int keyEventCode) { - getCurrentInputConnection().sendKeyEvent( - new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode)); - getCurrentInputConnection().sendKeyEvent( - new KeyEvent(KeyEvent.ACTION_UP, keyEventCode)); - } - - // Implementation of KeyboardViewListener - public void onKey(int primaryCode, int[] keyCodes) { - if (primaryCode == TranslatorKeyboard.KEYCODE_DELETE) { - handleBackspace(); - } else if (primaryCode == TranslatorKeyboard.KEYCODE_SHIFT) { - handleShift(); - } else if (primaryCode == TranslatorKeyboard.KEYCODE_SOURCE_LANGUAGE - && mInputView != null) { - mTranslator.switchLanguages(); - handleSwitchLanguages(); - } else if (primaryCode < TranslatorKeyboard.KEYCODE_SOURCE_LANGUAGE && - primaryCode > TranslatorKeyboard.KEYCODE_SOURCE_LANGUAGE-TranslatorKeyboard.MAX_LANGUAGE_KEYCODES) { - Language newSource = - mTranslator.getAvailableLanguages().get(TranslatorKeyboard.KEYCODE_SOURCE_LANGUAGE-primaryCode-1); - mTranslator.setSourceLanguage(newSource); - handleChangeSourceLanguage(newSource); - } else if (primaryCode == TranslatorKeyboard.KEYCODE_TARGET_LANGUAGE) { - String translation = mTranslator.translate(getComposingString()).first; - if (translation.startsWith("% ") || translation.startsWith("* ") || translation.startsWith("+ ")) - translation = translation.substring(2); - getCurrentInputConnection().commitText(translation, 1); - return; - } else if (primaryCode < TranslatorKeyboard.KEYCODE_TARGET_LANGUAGE && - primaryCode > TranslatorKeyboard.KEYCODE_TARGET_LANGUAGE-TranslatorKeyboard.MAX_LANGUAGE_KEYCODES) { - Language newTarget = - mTranslator.getAvailableLanguages().get(TranslatorKeyboard.KEYCODE_TARGET_LANGUAGE-primaryCode-1); - mTranslator.setTargetLanguage(newTarget); - handleChangeTargetLanguage(newTarget); - } else if (primaryCode == TranslatorKeyboard.KEYCODE_MODE_CHANGE && - mInputView != null) { - TranslatorKeyboard current = (TranslatorKeyboard) mInputView.getKeyboard(); - if (current == mSymbolsPage1Keyboard || current == mSymbolsPage2Keyboard) { - current = mLanguagePage1Keyboard; - } else { - current = mSymbolsPage1Keyboard; - } - mInputView.setKeyboard(current); - if (current == mSymbolsPage1Keyboard) { - current.setShifted(false); - } - } else if (primaryCode == TranslatorKeyboard.KEYCODE_PAGE_CHANGE && - mInputView != null) { - TranslatorKeyboard current = (TranslatorKeyboard) mInputView.getKeyboard(); - if (current == mLanguagePage1Keyboard) { - current = mLanguagePage2Keyboard; - } else { - current = mLanguagePage1Keyboard; - } - mInputView.setKeyboard(current); - } else if (primaryCode == 10) { - if ((mActionId & EditorInfo.IME_FLAG_NO_ENTER_ACTION) == 0) - getCurrentInputConnection().performEditorAction(mActionId & EditorInfo.IME_MASK_ACTION); - else - handleCharacter(primaryCode, keyCodes); - } else if (primaryCode == ' ') { - if (mComposingText.length() + mComposingWord.length() == 0) - getCurrentInputConnection().commitText(" ", 1); - else if (mComposingWord.length() > 0) { - mComposingText.append(mComposingWord); - mComposingText.append(' '); - mComposingWord.setLength(0); - getCurrentInputConnection().setComposingText(getComposingString(), 1); - } else { - mComposingText.append(' '); - getCurrentInputConnection().setComposingText(getComposingString(), 1); - } - } else { - handleCharacter(primaryCode, keyCodes); - } - } - - public void onText(CharSequence text) { - InputConnection ic = getCurrentInputConnection(); - if (ic == null) return; - ic.beginBatchEdit(); - if (mComposingText.length() > 0) { - commitTyped(ic); - } - ic.commitText(text, 0); - ic.endBatchEdit(); - updateShiftKeyState(getCurrentInputEditorInfo()); - } - - /** - * Update the list of available candidates from the current composing - * text. This will need to be filled in by however you are determining - * candidates. - */ - private void updateCandidates() { - if (!mCompletionOn) { - if (mComposingWord.length() > 1) { - mCompletions = - mTranslator.lookupWordPrefix(mComposingWord.toString()); - setSuggestions(mCompletions, true, true); - } else { - setSuggestions(null, false, false); - } - } - } - - public void setSuggestions(CompletionInfo[] completions, boolean isCompletions, - boolean typedWordValid) { - if (completions != null && completions.length > 0) { - setCandidatesViewShown(true); - } else if (isExtractViewShown()) { - setCandidatesViewShown(true); - } - if (mCandidateView != null) { - mCandidateView.setSuggestions(completions, isCompletions, typedWordValid); - } - } - - private void handleBackspace() { - int wordLength = mComposingWord.length(); - int textLength = mComposingText.length(); - if (wordLength > 1) { - mComposingWord.delete(wordLength - 1, wordLength); - getCurrentInputConnection().setComposingText(getComposingString(), 1); - if (mPredictionOn) - updateCandidates(); - } else if (wordLength > 0) { - mComposingWord.setLength(0); - getCurrentInputConnection().setComposingText(getComposingString(), 1); - updateCandidates(); - } else if (textLength > 0) { - if (mComposingText.charAt(textLength - 1) == ' ') { - mComposingText.delete(textLength - 1, textLength); - getCurrentInputConnection().setComposingText(getComposingString(), 1); - } else { - mComposingText.delete(textLength - 1, textLength); - textLength--; - int index = mComposingText.lastIndexOf(" "); - if (index == -1) { - mComposingWord.append(mComposingText.toString()); - mComposingText.setLength(0); - } else { - mComposingWord.append(mComposingText.substring(index+1, textLength)); - mComposingText.delete(index+1, textLength); - } - getCurrentInputConnection().setComposingText(getComposingString(), 1); - } - updateCandidates(); - } else { - keyDownUp(KeyEvent.KEYCODE_DEL); - } - updateShiftKeyState(getCurrentInputEditorInfo()); - } - - private void handleShift() { - if (mInputView == null) { - return; - } - - TranslatorKeyboard currentKeyboard = (TranslatorKeyboard) mInputView.getKeyboard(); - if (mLanguagePage1Keyboard == currentKeyboard || - mLanguagePage2Keyboard == currentKeyboard) { - // Alphabet keyboard - checkToggleCapsLock(); - mInputView.setShifted(mCapsLock || !mInputView.isShifted()); - } else if (currentKeyboard == mSymbolsPage1Keyboard) { - mSymbolsPage1Keyboard.setShifted(true); - mInputView.setKeyboard(mSymbolsPage2Keyboard); - mSymbolsPage2Keyboard.setShifted(true); - } else if (currentKeyboard == mSymbolsPage2Keyboard) { - mSymbolsPage2Keyboard.setShifted(false); - mInputView.setKeyboard(mSymbolsPage1Keyboard); - mSymbolsPage1Keyboard.setShifted(false); - } - } - - private String getComposingString() { - return mComposingText.toString() + mComposingWord.toString(); - } - - private void handleCharacter(int primaryCode, int[] keyCodes) { - if (keyCodes.length > 0 && keyCodes[0] > 0) { - for (int i = 0; i < keyCodes.length && keyCodes[i] > 0; i++) { - int code = keyCodes[i]; - if (mInputView.isShifted()) - code = Character.toUpperCase(code); - mComposingWord.append((char) code); - } - } else { - if (mInputView.isShifted()) - primaryCode = Character.toUpperCase(primaryCode); - mComposingWord.append((char) primaryCode); - } - - if (primaryCode == 10) - commitTyped(getCurrentInputConnection()); - else - getCurrentInputConnection().setComposingText(getComposingString(), 1); - updateShiftKeyState(getCurrentInputEditorInfo()); - - if (mPredictionOn) { - updateCandidates(); - } - } - - private void handleClose() { - commitTyped(getCurrentInputConnection()); - requestHideSelf(0); - mInputView.closing(); - } - - void handleChangeSourceLanguage(Language newSource) { - updateLanguageKeyboard(newSource); - mSymbolsPage1Keyboard.updateLanguageKeyLabels(); - mSymbolsPage2Keyboard.updateLanguageKeyLabels(); - if (mInputView != null) { - mInputView.setKeyboard(mCurKeyboard); - } - } - - void handleChangeTargetLanguage(Language newTarget) { - mLanguagePage1Keyboard.updateLanguageKeyLabels(); - mLanguagePage2Keyboard.updateLanguageKeyLabels(); - mSymbolsPage1Keyboard.updateLanguageKeyLabels(); - mSymbolsPage2Keyboard.updateLanguageKeyLabels(); - if (mInputView != null) { - mInputView.invalidateAllKeys(); - } - } - - void handleSwitchLanguages() { - Language newSource = mTranslator.getSourceLanguage(); - updateLanguageKeyboard(newSource); - mSymbolsPage1Keyboard.updateLanguageKeyLabels(); - mSymbolsPage2Keyboard.updateLanguageKeyLabels(); - if (mInputView != null) - mInputView.setKeyboard(mCurKeyboard); - } - - private void updateLanguageKeyboard(Language language) { - TranslatorKeyboard keyboard1 = - new TranslatorKeyboard(this, language.getKeyboardPage1Resource(), mModeId); - TranslatorKeyboard keyboard2 = - new TranslatorKeyboard(this, language.getKeyboardPage2Resource(), mModeId); - keyboard1.setImeOptions(getResources(), mAttribute.imeOptions); - keyboard2.setImeOptions(getResources(), mAttribute.imeOptions); - if (mCurKeyboard == mLanguagePage1Keyboard) { - mCurKeyboard = keyboard1; - } else if (mCurKeyboard == mLanguagePage2Keyboard) { - mCurKeyboard = keyboard2; - } - mLanguagePage1Keyboard = keyboard1; - mLanguagePage2Keyboard = keyboard2; - } - - private void checkToggleCapsLock() { - long now = System.currentTimeMillis(); - if (mLastShiftTime + 800 > now) { - mCapsLock = !mCapsLock; - mLastShiftTime = 0; - } else { - mLastShiftTime = now; - } - } - - public void pickDefaultCandidate() { - pickSuggestionManually(0); - } - - public void pickSuggestionManually(int index) { - if (mCompletions != null && - index >= 0 && index < mCompletions.length) { - CompletionInfo ci = mCompletions[index]; - - if (mCompletionOn) - getCurrentInputConnection().commitCompletion(ci); - else { - mComposingWord.setLength(0); - mComposingWord.append(ci.getText()); - getCurrentInputConnection().setComposingText(getComposingString(), 1); - } - - if (mCandidateView != null) { - mCandidateView.clear(); - } - updateShiftKeyState(getCurrentInputEditorInfo()); - } - } - - public void swipeRight() { - if (mCompletionOn) { - pickDefaultCandidate(); - } - } - - public void swipeLeft() { - handleBackspace(); - } - - public void swipeDown() { - handleClose(); - } - - public void swipeUp() { - } - - public void onPress(int primaryCode) { - } - - public void onRelease(int primaryCode) { - } -} diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorKeyboard.java b/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorKeyboard.java deleted file mode 100644 index 876f660da..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorKeyboard.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.grammaticalframework.ui.android; - -import java.util.Locale; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.XmlResourceParser; -import android.view.inputmethod.EditorInfo; -import android.inputmethodservice.Keyboard; - -public class TranslatorKeyboard extends Keyboard { - - private Key mEnterKey; - private Key mSourceLanguageKey; - private Key mTargetLanguageKey; - - static final int KEYCODE_PAGE_CHANGE = -10; - static final int KEYCODE_SOURCE_LANGUAGE = -100; - static final int KEYCODE_TARGET_LANGUAGE = -200; - static final int MAX_LANGUAGE_KEYCODES = 99; - - private Translator mTranslator; - - public TranslatorKeyboard(Context context, int xmlLayoutResId, int modeId) { - super(context, xmlLayoutResId, modeId); - - mTranslator = ((GFTranslator) context.getApplicationContext()).getTranslator(); - updateLanguageKeyLabels(); - } - - public void updateLanguageKeyLabels() { - if (mSourceLanguageKey != null) - mSourceLanguageKey.label = getLanguageKeyLabel(mTranslator.getSourceLanguage()); - - if (mTargetLanguageKey != null) - mTargetLanguageKey.label = getLanguageKeyLabel(mTranslator.getTargetLanguage()); - } - - public static String getLanguageKeyLabel(Language lang) { - if ("cmn-hans-cn".equalsIgnoreCase(lang.getLangCode())) // this one has no ISO code - return "chi"; - else - return - LocaleUtils.parseJavaLocale(lang.getLangCode(), Locale.getDefault()) - .getISO3Language(); - } - - @Override - protected Key createKeyFromXml(Resources res, Row parent, int x, int y, - XmlResourceParser parser) { - Key key = new Key(res, parent, x, y, parser); - if (key.codes[0] == 10) { - mEnterKey = key; - } else if (key.codes[0] == KEYCODE_SOURCE_LANGUAGE) { - mSourceLanguageKey = key; - } else if (key.codes[0] == KEYCODE_TARGET_LANGUAGE) { - mTargetLanguageKey = key; - } - return key; - } - - /** - * This looks at the ime options given by the current editor, to set the - * appropriate label on the keyboard's enter key (if it has one). - */ - void setImeOptions(Resources res, int options) { - if (mEnterKey == null) { - return; - } - - switch (options&(EditorInfo.IME_MASK_ACTION|EditorInfo.IME_FLAG_NO_ENTER_ACTION)) { - case EditorInfo.IME_ACTION_DONE: - mEnterKey.iconPreview = null; - mEnterKey.icon = null; - mEnterKey.label = res.getText(R.string.label_done_key); - break; - case EditorInfo.IME_ACTION_GO: - mEnterKey.iconPreview = null; - mEnterKey.icon = null; - mEnterKey.label = res.getText(R.string.label_go_key); - break; - case EditorInfo.IME_ACTION_NEXT: - mEnterKey.iconPreview = null; - mEnterKey.icon = null; - mEnterKey.label = res.getText(R.string.label_next_key); - break; - case EditorInfo.IME_ACTION_PREVIOUS: - mEnterKey.iconPreview = null; - mEnterKey.icon = null; - mEnterKey.label = res.getText(R.string.label_previous_key); - break; - case EditorInfo.IME_ACTION_SEARCH: - mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_search); - mEnterKey.label = null; - break; - case EditorInfo.IME_ACTION_SEND: - mEnterKey.iconPreview = null; - mEnterKey.icon = null; - mEnterKey.label = res.getText(R.string.label_send_key); - break; - default: - mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_return); - mEnterKey.label = null; - break; - } - } -} \ No newline at end of file diff --git a/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorKeyboardView.java b/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorKeyboardView.java deleted file mode 100644 index 0a42eca2d..000000000 --- a/src/ui/android/src/org/grammaticalframework/ui/android/TranslatorKeyboardView.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.grammaticalframework.ui.android; - -import org.grammaticalframework.ui.android.TranslatorKeyboard; - -import android.content.Context; -import android.graphics.Point; -import android.inputmethodservice.Keyboard.Key; -import android.inputmethodservice.KeyboardView; -import android.util.AttributeSet; -import android.view.Display; -import android.view.Gravity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.WindowManager; -import android.widget.Button; -import android.widget.PopupWindow; -import android.widget.TableLayout; -import android.widget.TableRow; - -public class TranslatorKeyboardView extends KeyboardView { - - private Translator mTranslator; - - public TranslatorKeyboardView(Context context, AttributeSet attrs) { - super(context, attrs); - mTranslator = ((GFTranslator) context.getApplicationContext()).getTranslator(); - } - - public TranslatorKeyboardView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - mTranslator = ((GFTranslator) context.getApplicationContext()).getTranslator(); - } - - private PopupWindow mLanguagesPopup = null; - private Key mLanguagesKey = null; - - private void showLanguageOptions(Key popupKey) { - if (mLanguagesPopup == null) { - LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( - Context.LAYOUT_INFLATER_SERVICE); - TableLayout popupContainer = (TableLayout) - inflater.inflate(R.layout.keyboard_languages_options, null); - - int index = 0; - TableRow row = null; - for (Language lang : mTranslator.getAvailableLanguages()) { - int col_index = index % 4; - if (col_index == 0) { - row = new TableRow(getContext()); - popupContainer.addView(row); - } - - Button item = new Button(getContext()); - item.setText(TranslatorKeyboard.getLanguageKeyLabel(lang)); - item.setTag(index); - item.setOnClickListener(this); - row.addView(item, col_index); - index++; - } - - WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); - Display display = wm.getDefaultDisplay(); - Point size = new Point(); - display.getSize(size); - - popupContainer.measure( - MeasureSpec.makeMeasureSpec(size.x, MeasureSpec.AT_MOST), - MeasureSpec.makeMeasureSpec(size.y, MeasureSpec.AT_MOST)); - - mLanguagesPopup = new PopupWindow(getContext()); - mLanguagesPopup.setWidth(popupContainer.getMeasuredWidth()); - mLanguagesPopup.setHeight(popupContainer.getMeasuredHeight()); - mLanguagesPopup.setContentView(popupContainer); - - int[] windowOffset = new int[2]; - getLocationInWindow(windowOffset); - int popupX = popupKey.x + popupKey.width - popupContainer.getMeasuredWidth(); - int popupY = popupKey.y - popupContainer.getMeasuredHeight(); - final int x = popupX + popupContainer.getPaddingRight() + windowOffset[0]; - final int y = popupY + popupContainer.getPaddingBottom() + windowOffset[1]; - mLanguagesPopup.showAtLocation(this, Gravity.NO_GRAVITY, x, y); - - View closeButton = popupContainer.findViewById(R.id.closeButton); - if (closeButton != null) closeButton.setOnClickListener(this); - } - - mLanguagesKey = popupKey; - } - - private void dismissLanguages() { - if (mLanguagesPopup != null) { - mLanguagesPopup.dismiss(); - mLanguagesPopup = null; - mLanguagesKey = null; - } - } - - @Override - public void onClick(View v) { - super.onClick(v); - - if (v.getTag() != null) { - if (mLanguagesKey.codes[0] == TranslatorKeyboard.KEYCODE_SOURCE_LANGUAGE || - mLanguagesKey.codes[0] == TranslatorKeyboard.KEYCODE_TARGET_LANGUAGE) { - int keyCode = mLanguagesKey.codes[0] - ((Integer) v.getTag()) - 1; - getOnKeyboardActionListener().onKey(keyCode, new int[] {keyCode}); - } - } - - dismissLanguages(); - } - - public void closing() { - super.closing(); - dismissLanguages(); - } - - @Override - protected boolean onLongPress(Key key) { - if (key.codes[0] == TranslatorKeyboard.KEYCODE_SOURCE_LANGUAGE || - key.codes[0] == TranslatorKeyboard.KEYCODE_TARGET_LANGUAGE) { - showLanguageOptions(key); - return true; - } else { - return super.onLongPress(key); - } - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/Model.java b/src/ui/android/src/se/chalmers/phrasebook/backend/Model.java deleted file mode 100644 index 8e4b07b21..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/Model.java +++ /dev/null @@ -1,206 +0,0 @@ -package se.chalmers.phrasebook.backend; - -import org.w3c.dom.*; -import org.xml.sax.*; -import org.w3c.dom.ls.*; - -import java.io.*; -import java.util.*; -import javax.xml.parsers.*; - -import org.grammaticalframework.pgf.Expr; -import org.grammaticalframework.ui.android.R; -import org.grammaticalframework.ui.android.GFTranslator; -import se.chalmers.phrasebook.backend.syntax.*; - -public class Model { - private static Model model; - - private List phrases; - private Map> groups; - - private Model() { - try { - DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - InputStream is = GFTranslator.get().getAssets().open("phrases.xml"); - Document document = documentBuilder.parse(is); - parseSentencesData(document); - is.close(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (SAXException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static Model getInstance() { - if (model == null) model = getSync(); - return model; - } - - private synchronized static Model getSync() { - if (model == null) model = new Model(); - return model; - } - - public List getSentences() { - return phrases; - } - - public List getGroup(String id) { - return groups.get(id); - } - - private void parseSentencesData(Document document) { - phrases = new ArrayList(); - groups = new HashMap>(); - Map ids = new HashMap(); - List calls = new ArrayList(); - - NodeList nodesList = document.getDocumentElement().getChildNodes(); - for (int i = 0; i < nodesList.getLength(); i++) { - Node node = nodesList.item(i); - - if (node != null && - node.getNodeType() == Node.ELEMENT_NODE && - node.getNodeName().equals("sentence")) { - NamedNodeMap attributes = node.getAttributes(); - - if (attributes == null) - continue; - - String desc = ""; - if (attributes.getNamedItem("desc") != null) { - desc = attributes.getNamedItem("desc").getNodeValue(); - } - - SyntaxNode[] nodes = constructSyntaxNodeList(node, ids, calls); - if (nodes.length > 0) - phrases.add(new SyntaxTree(desc, nodes[0])); - } else if (node != null && - node.getNodeType() == Node.ELEMENT_NODE && - node.getNodeName().equals("group")) { - - NamedNodeMap attributes = node.getAttributes(); - if (attributes == null) - continue; - - String id = null; - if (attributes.getNamedItem("id") != null) { - id = attributes.getNamedItem("id").getNodeValue(); - } - if (id == null) - continue; - - List group_phrases = new ArrayList(); - - NodeList nodesList2 = node.getChildNodes(); - for (int j = 0; j < nodesList2.getLength(); j++) { - node = nodesList2.item(j); - - if (node != null && - node.getNodeType() == Node.ELEMENT_NODE && - node.getNodeName().equals("sentence")) { - attributes = node.getAttributes(); - - if (attributes == null) - continue; - - String desc = ""; - if (attributes.getNamedItem("desc") != null) { - desc = attributes.getNamedItem("desc").getNodeValue(); - } - - SyntaxNode[] nodes = constructSyntaxNodeList(node, ids, calls); - if (nodes.length > 0) { - SyntaxTree tree = new SyntaxTree(desc, nodes[0]); - phrases.add(tree); - group_phrases.add(tree); - } - } - } - - groups.put(id, group_phrases); - } else if (node.getAttributes() != null && node.getAttributes().getNamedItem("id") != null) { - String id = node.getAttributes().getNamedItem("id").getNodeValue(); - SyntaxNode snode = constructSyntaxNode(node, ids, calls); - if (snode == null) { - throw new IllegalArgumentException(outerXml(node)); - } - ids.put(id,snode); - } - } - - for (SyntaxNodeCall call : calls) { - call.bind(ids); - } - } - - private SyntaxNode constructSyntaxNode(Node node, Map ids, List calls) { - NamedNodeMap attributes = node.getAttributes(); - if (attributes == null) - return null; - - String desc = ""; - if (attributes.getNamedItem("desc") != null) { - desc = attributes.getNamedItem("desc").getNodeValue(); - } - - if (node.getNodeName().equals("function")) { - String function = attributes.getNamedItem("name").getNodeValue(); - SyntaxNode[] arguments = constructSyntaxNodeList(node, ids, calls); - return new SyntaxNodeFunction(desc, function, arguments); - } else if (node.getNodeName().equals("numeral")) { - return new SyntaxNodeNumeral(desc, 1, 100); - } else if (node.getNodeName().equals("option")) { - SyntaxNode[] options = constructSyntaxNodeList(node, ids, calls); - return new SyntaxNodeOption(desc, options); - } else if (node.getNodeName().equals("boolean")) { - SyntaxNode[] options = constructSyntaxNodeList(node, ids, calls); - return new SyntaxNodeBoolean(desc, options); - } else if (node.getNodeName().equals("call")) { - if (attributes.getNamedItem("ref") == null) - return null; - - String ref = attributes.getNamedItem("ref").getNodeValue(); - SyntaxNode[] arguments = constructSyntaxNodeList(node, ids, calls); - SyntaxNodeCall call = new SyntaxNodeCall(desc, ref, arguments); - calls.add(call); - return call; - } else if (node.getNodeName().equals("argument")) { - int d = 0; - if (attributes.getNamedItem("index") != null) - d = Integer.parseInt(attributes.getNamedItem("index").getNodeValue()); - return new SyntaxNodeArgument(desc, d); - } - - return null; - } - - private SyntaxNode[] constructSyntaxNodeList(Node root, Map ids, List calls) { - NodeList nl = root.getChildNodes(); - - int index = 0; - SyntaxNode[] list = new SyntaxNode[nl.getLength()]; - for (int i = 0; i < nl.getLength(); i++) { - Node node = nl.item(i); - if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { - list[index] = constructSyntaxNode(node, ids, calls); - if (list[index] == null) - throw new IllegalArgumentException(outerXml(node)); - index++; - } - } - return Arrays.copyOf(list, index); - } - - private String outerXml(Node node) { - DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument().getImplementation().getFeature("LS", "3.0"); - LSSerializer lsSerializer = lsImpl.createLSSerializer(); - lsSerializer.getDomConfig().setParameter("xml-declaration", false); - return lsSerializer.writeToString(node); - } -} - diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/ChoiceContext.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/ChoiceContext.java deleted file mode 100644 index 3995ad063..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/ChoiceContext.java +++ /dev/null @@ -1,61 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -import java.util.*; - -public class ChoiceContext { - private int pos; - private List choices; - private List stack; - - public ChoiceContext() { - this.pos = pos; - this.choices = new ArrayList(); - this.stack = new ArrayList(); - } - - public void reset() { - pos = 0; - stack.clear(); - } - - public void trim() { - while (pos < choices.size()) - choices.remove(choices.size()-1); - } - - public int choose(SyntaxNode node) { - SyntacticChoice choice = null; - - if (pos < choices.size()) { - if (choices.get(pos).getNode().unlink() == node.unlink()) { - choice = choices.get(pos); - } else { - trim(); - } - } - - if (choice == null) { - choice = new SyntacticChoice(node); - choices.add(choice); - } - - pos++; - return choice.getChoice(); - } - - public void push(SyntaxNode[] args) { - stack.add(args); - } - - public SyntaxNode[] pop() { - return stack.remove(stack.size()-1); - } - - public SyntaxNode getArgument(int i) { - return stack.get(stack.size()-1)[i]; - } - - public List getChoices() { - return choices; - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntacticChoice.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntacticChoice.java deleted file mode 100644 index 709893504..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntacticChoice.java +++ /dev/null @@ -1,25 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -import java.io.*; - -public class SyntacticChoice implements Serializable { - private int choice; - private SyntaxNode node; - - public SyntacticChoice(SyntaxNode node) { - this.node = node; - this.choice = node.getDefaultChoice(); - } - - public SyntaxNode getNode() { - return node; - } - - public int getChoice() { - return choice; - } - - public void setChoice(int choice) { - this.choice = choice; - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNode.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNode.java deleted file mode 100644 index 5268e41d4..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNode.java +++ /dev/null @@ -1,33 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -import java.io.Serializable; -import org.grammaticalframework.pgf.Expr; - -public class SyntaxNode implements Serializable { - private String desc; - - public SyntaxNode(String desc) { - this.desc = desc; - } - - public String getDesc() { - return desc; - } - - public String getAbstractSyntax(ChoiceContext context) { - return null; - } - - public int getDefaultChoice() { - return 0; - } - - public SyntaxNode unlink() { - return this; - } - - @Override - public String toString() { - return desc; - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeArgument.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeArgument.java deleted file mode 100644 index 12b13aa4b..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeArgument.java +++ /dev/null @@ -1,15 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -public class SyntaxNodeArgument extends SyntaxNode { - private int index; - - public SyntaxNodeArgument(String desc, int index) { - super(desc); - this.index = index; - } - - @Override - public String getAbstractSyntax(ChoiceContext context) { - return context.getArgument(index).getAbstractSyntax(context); - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeBoolean.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeBoolean.java deleted file mode 100644 index da1e95e04..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeBoolean.java +++ /dev/null @@ -1,7 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -public class SyntaxNodeBoolean extends SyntaxNodeOption { - public SyntaxNodeBoolean(String desc, SyntaxNode[] options) { - super(desc,options); - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeCall.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeCall.java deleted file mode 100644 index 199c818ae..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeCall.java +++ /dev/null @@ -1,52 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -import java.util.*; - -public class SyntaxNodeCall extends SyntaxNode { - private String id; - private SyntaxNode ref; - private SyntaxNode[] arguments; - - public SyntaxNodeCall(String desc, String id, SyntaxNode[] arguments) { - super(desc); - this.id = id; - this.ref = null; - this.arguments = arguments; - } - - public String getDesc() { - String desc = super.getDesc(); - if (desc == null || desc.isEmpty()) - return ref.getDesc(); - return desc; - } - - @Override - public String getAbstractSyntax(ChoiceContext context) { - context.push(arguments); - String res = ref.getAbstractSyntax(context); - context.pop(); - return res; - } - - @Override - public SyntaxNode unlink() { - return ref.unlink(); - } - - public String getId() { - return id; - } - - public SyntaxNode getRef() { - return ref; - } - - public void bind(Map ids) { - if (ref == null) { - ref = ids.get(id); - if (ref == null) - throw new IllegalArgumentException("Missing reference to "+id); - } - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeFunction.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeFunction.java deleted file mode 100644 index 2bc6e187d..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeFunction.java +++ /dev/null @@ -1,39 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -import java.util.*; - -public class SyntaxNodeFunction extends SyntaxNode { - private String function; - private SyntaxNode[] arguments; - - public SyntaxNodeFunction(String desc, String function, SyntaxNode[] arguments) { - super(desc); - this.function = function; - this.arguments = arguments; - } - - public String getFunction() { - return function; - } - - public SyntaxNode[] getArguments() { - return arguments; - } - - @Override - public String getAbstractSyntax(ChoiceContext context) { - if (arguments == null || arguments.length == 0) - return function; - - StringBuilder builder = new StringBuilder(); - builder.append(function); - for (SyntaxNode argument : arguments) { - builder.append(' '); - builder.append('('); - builder.append(argument.getAbstractSyntax(context)); - builder.append(')'); - } - - return builder.toString(); - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeNumeral.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeNumeral.java deleted file mode 100644 index 11a6b4103..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeNumeral.java +++ /dev/null @@ -1,84 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -public class SyntaxNodeNumeral extends SyntaxNode { - private int min; - private int max; - - public SyntaxNodeNumeral(String desc, int min, int max) { - super(desc); - this.min = min; - this.max = max; - } - - public String getAbstractSyntax(ChoiceContext context) { - return nbrToSyntax(context.choose(this)); - } - - @Override - public int getDefaultChoice() { - return 1; - } - - public int getMin() { - return min; - } - - public int getMax() { - return max; - } - - private String nbrToSyntax(int nbr) throws IllegalArgumentException { - String syntax = ""; - if(nbr < 1000000 && nbr > 0) { - if (nbr <=999) { - syntax = "(num (pot2as3 " + subs1000(nbr) + "))"; - } else if(nbr % 1000 == 0) { - syntax = "(num (pot3 " + subs1000(nbr/1000) + "))"; - } else if(nbr > 1000 && nbr%1000 != 0) { - syntax = "(num (pot3plus " + subs1000(nbr/1000) + " " + - subs1000(nbr%1000) + "))"; - } - } else { - throw new IllegalArgumentException("Input must be between 1 and 999999"); - } - return syntax; - } - - private String subs1000(int nbr) { - String syntax = ""; - if(nbr < 100) { - syntax = "(pot1as2 " + subs100(nbr) + ")"; - } else if(nbr % 100 == 0) { - syntax = "(pot2 " + subs10(nbr/100) + ")"; - } else if(nbr > 100 && nbr%100 != 0) { - syntax = "(pot2plus " + subs10(nbr/100) + " " + subs100(nbr%100) + ")"; - } - return syntax; - } - - private String subs100(int nbr) { - String syntax = ""; - if(nbr < 10) { - syntax = "(pot0as1 " + subs10(nbr) + ")"; - } else if(nbr == 10 || nbr == 11) { - syntax = "pot1" + nbr; - } else if(nbr >= 12 && nbr <= 19) { - syntax = "(pot1to19 n" + nbr%10 + ")"; - } else if(nbr >= 20 && nbr%10 == 0) { - syntax = "(pot1 n" + Integer.toString(nbr/10) + ")"; - } else if(nbr%10 != 0) { - syntax = "(pot1plus n" + nbr/10 + " " + subs10(nbr%10) + ")"; - } - return syntax; - } - - private String subs10(int nbr) { - String syntax = ""; - if (nbr == 1) { - syntax = "pot01"; - } else if (nbr >= 2 && nbr <= 9) { - syntax = "(pot0 n" + nbr + ")"; - } - return syntax; - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeOption.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeOption.java deleted file mode 100644 index d7dc4ca83..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxNodeOption.java +++ /dev/null @@ -1,22 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -import java.util.*; -import se.chalmers.phrasebook.backend.*; - -public class SyntaxNodeOption extends SyntaxNode { - private SyntaxNode[] options; - - public SyntaxNodeOption(String desc, SyntaxNode[] options) { - super(desc); - this.options = options; - } - - public SyntaxNode[] getOptions() { - return options; - } - - @Override - public String getAbstractSyntax(ChoiceContext context) { - return options[context.choose(this)].getAbstractSyntax(context); - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxTree.java b/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxTree.java deleted file mode 100644 index 964f07d0b..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/backend/syntax/SyntaxTree.java +++ /dev/null @@ -1,33 +0,0 @@ -package se.chalmers.phrasebook.backend.syntax; - -import java.io.Serializable; -import org.grammaticalframework.pgf.Expr; - -public class SyntaxTree implements Serializable { - private String desc; - private SyntaxNode root; - - public SyntaxTree(String desc, SyntaxNode root) { - this.desc = desc; - this.root = root; - } - - public String getDesc() { - return desc; - } - - public SyntaxNode getRoot() { - return root; - } - - public Expr getAbstractSyntax(ChoiceContext choices) { - Expr expr = Expr.readExpr(root.getAbstractSyntax(choices)); - choices.trim(); - return expr; - } - - @Override - public String toString() { - return desc; - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/gui/activities/NavigationActivity.java b/src/ui/android/src/se/chalmers/phrasebook/gui/activities/NavigationActivity.java deleted file mode 100644 index 1dc754380..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/gui/activities/NavigationActivity.java +++ /dev/null @@ -1,79 +0,0 @@ -package se.chalmers.phrasebook.gui.activities; - -import android.app.ActionBar; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.Color; -import android.graphics.drawable.ColorDrawable; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentActivity; -import android.support.v4.app.FragmentTransaction; -import android.support.v4.content.LocalBroadcastManager; -import android.support.v4.widget.DrawerLayout; - -import org.grammaticalframework.ui.android.R; -import se.chalmers.phrasebook.backend.Model; -import se.chalmers.phrasebook.backend.syntax.*; -import se.chalmers.phrasebook.gui.fragments.PhraseListFragment; -import se.chalmers.phrasebook.gui.fragments.TranslatorFragment; - -public class NavigationActivity extends FragmentActivity { - - /** - * Used to store the last screen title. For use in {@link #restoreActionBar()}. - */ - private CharSequence mTitle; - private Fragment mContent; - - private Model mModel; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_navigation); - - mModel = Model.getInstance(); - mTitle = getTitle(); - - FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); - transaction.replace(R.id.container, PhraseListFragment.newInstance("Phrasebook")); - transaction.commit(); - } - - public void switchContent(Fragment fragment, String message) { - mContent = fragment; - - FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); - transaction.replace(R.id.container, fragment); - transaction.addToBackStack(message); - transaction.commit(); - } - - public void restoreActionBar() { - ActionBar actionBar = getActionBar(); - actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); - actionBar.setDisplayShowTitleEnabled(true); - actionBar.setTitle(mTitle); - } - - @Override - public void onBackPressed() { - if (getSupportFragmentManager().getBackStackEntryCount() > 1) { - getSupportFragmentManager().popBackStack(); - getSupportFragmentManager().beginTransaction().commit(); - //Switches to the previous entry on the stack to ensure - //that mContent is preserved - mContent = getSupportFragmentManager().getFragments() - .get(getSupportFragmentManager().getFragments().size() - 2); - } else { - super.onBackPressed(); - } - } - - public void setToTranslationFragment(SyntaxTree phrase) { - switchContent(TranslatorFragment.newInstance(phrase), ""); - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/gui/fragments/PhraseListFragment.java b/src/ui/android/src/se/chalmers/phrasebook/gui/fragments/PhraseListFragment.java deleted file mode 100644 index 7e3c09ada..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/gui/fragments/PhraseListFragment.java +++ /dev/null @@ -1,86 +0,0 @@ -package se.chalmers.phrasebook.gui.fragments; - -import android.os.Bundle; - -import java.util.*; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v4.content.LocalBroadcastManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.ListView; - -import java.util.ArrayList; - -import org.grammaticalframework.ui.android.R; -import se.chalmers.phrasebook.backend.Model; -import se.chalmers.phrasebook.backend.syntax.SyntaxTree; -import se.chalmers.phrasebook.gui.activities.NavigationActivity; - - -/** - * Created by Björn on 2016-04-25. - */ -public class PhraseListFragment extends Fragment { - - protected Model model; - private String title; - private String id; - - public static PhraseListFragment newInstance(String title) { - PhraseListFragment fragment = new PhraseListFragment(); - Bundle args = new Bundle(); - args.putString("title", title); - fragment.setArguments(args); - return fragment; - } - - public static PhraseListFragment newInstance(String title, String id) { - PhraseListFragment fragment = new PhraseListFragment(); - Bundle args = new Bundle(); - args.putString("title", title); - args.putString("id", id); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - model = Model.getInstance(); - title = getArguments().getString("title"); - id = getArguments().getString("id"); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - - View view = inflater.inflate(R.layout.fragment_phrase_list, container, false); - getActivity().getActionBar().setTitle(title); - - final List sentences = (id == null) ? model.getSentences() : model.getGroup(id); - ArrayAdapter adapter = new ArrayAdapter(getActivity(), R.layout.phrase_list_item, sentences); - - final ListView phraseListView = (ListView) view.findViewById(R.id.phrase_listView); - phraseListView.setAdapter(adapter); - - phraseListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long item_id) { - SyntaxTree phrase = sentences.get(position); - getActivity().getActionBar().setTitle(phrase.getDesc()); - ((NavigationActivity) getActivity()).setToTranslationFragment(phrase); - } - }); - - return view; - } -} diff --git a/src/ui/android/src/se/chalmers/phrasebook/gui/fragments/TranslatorFragment.java b/src/ui/android/src/se/chalmers/phrasebook/gui/fragments/TranslatorFragment.java deleted file mode 100644 index cb5d50841..000000000 --- a/src/ui/android/src/se/chalmers/phrasebook/gui/fragments/TranslatorFragment.java +++ /dev/null @@ -1,253 +0,0 @@ -package se.chalmers.phrasebook.gui.fragments; - -import java.util.*; - -import android.os.Bundle; -import android.content.Context; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentTransaction; -import android.view.*; -import android.widget.*; -import android.text.Editable; -import android.text.TextWatcher; -import android.text.method.PasswordTransformationMethod; - -import org.grammaticalframework.pgf.Expr; -import org.grammaticalframework.ui.android.Translator; -import org.grammaticalframework.ui.android.GFTranslator; -import org.grammaticalframework.ui.android.TTS; -import org.grammaticalframework.ui.android.R; -import se.chalmers.phrasebook.backend.*; -import se.chalmers.phrasebook.backend.syntax.*; - -/** - * Created by matilda on 04/04/16. - */ -public class TranslatorFragment extends Fragment { - protected Model model; - Translator mTranslator; - private TTS mTts; - - private TextView origin,target; - private ListView list; - SyntaxTree phrase; - - ChoiceContext mContext; - ArrayAdapter mAdapter; - - public static TranslatorFragment newInstance(SyntaxTree phrase) { - TranslatorFragment translatorFragment = new TranslatorFragment(); - Bundle args = new Bundle(); - args.putSerializable("phrase", phrase); - translatorFragment.setArguments(args); - return translatorFragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - phrase = (SyntaxTree) getArguments().getSerializable("phrase"); - model = Model.getInstance(); - mTranslator = ((GFTranslator) getContext().getApplicationContext()).getTranslator(); - mTts = new TTS(getActivity()); - mContext = new ChoiceContext(); - - - mAdapter = - new ArrayAdapter(getActivity(), R.layout.spinner_input_list_item, mContext.getChoices()) { - LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - @Override - public View getView (int position, View convertView, ViewGroup parent) { - SyntacticChoice choice = mContext.getChoices().get(position); - View view = null; - if (choice.getNode() instanceof SyntaxNodeBoolean) { - view = createCheckBoxInputView(inflater, choice, (SyntaxNodeBoolean) choice.getNode(), parent); - } else if (choice.getNode() instanceof SyntaxNodeOption) { - view = createSpinnerInputView(inflater, choice, (SyntaxNodeOption) choice.getNode(), parent); - } else if (choice.getNode() instanceof SyntaxNodeNumeral) { - view = createNumeralInputView(inflater, choice, (SyntaxNodeNumeral) choice.getNode(), parent); - } - return view; - } - }; - } - - @Override - public View onCreateView(final LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_translator, container, false); - origin = (TextView) view.findViewById(R.id.origin_phrase); - target = (TextView) view.findViewById(R.id.target_phrase); - list = (ListView) view.findViewById(R.id.input_holder); - list.setAdapter(mAdapter); - - ImageView button = (ImageView) view.findViewById(R.id.button3); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mTts.speak(mTranslator.getTargetLanguage().getLangCode(), (String) target.getText()); - } - }); - - updateSyntax(); - return view; - } - - private View createSpinnerInputView(LayoutInflater inflater, final SyntacticChoice choice, final SyntaxNodeOption options, ViewGroup parent) { - View view = inflater.inflate(R.layout.spinner_input_list_item, parent, false); - TextView viewLabel = (TextView) view.findViewById(R.id.text_view_spinner); - Spinner spinner = (Spinner) view.findViewById(R.id.choice_spinner); - - String label = options.getDesc(); - if (label == null || label.isEmpty()) { - viewLabel.setVisibility(View.GONE); - } else { - viewLabel.setText(label); - } - - final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1,options.getOptions()); - adapter.setDropDownViewResource(android.R.layout.simple_list_item_1); - spinner.setAdapter(adapter); - - spinner.setSelection(choice.getChoice()); - spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (position != choice.getChoice()) { - choice.setChoice(position); - updateSyntax(); - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - - return view; - } - - private class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod { - @Override - public CharSequence getTransformation(CharSequence source, View view) { - return source; - } - } - - private View createNumeralInputView(LayoutInflater inflater, final SyntacticChoice choice, final SyntaxNodeNumeral numeral, ViewGroup parent) { - View view = inflater.inflate(R.layout.number_input_list_item, parent, false); - TextView viewLabel = (TextView) view.findViewById(R.id.textView_number); - final SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekBar); - final EditText editNumber = (EditText) view.findViewById(R.id.editNumber); - - String label = choice.getNode().getDesc(); - if (label == null || label.isEmpty()) { - viewLabel.setVisibility(View.GONE); - } else { - viewLabel.setText(label); - } - - seekBar.setProgress(choice.getChoice()); - editNumber.setText(Integer.toString(choice.getChoice())); - - editNumber.setTransformationMethod(new NumericKeyBoardTransformationMethod()); - editNumber.requestFocus(); - seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - editNumber.setText(Integer.toString(progress+1)); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } - }); - - - editNumber.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - int number; - boolean update = false; - try { - if(editNumber.getText().toString().equals("")) { - number = numeral.getMin(); - } else { - number = Integer.parseInt(editNumber.getText().toString()); - if (number < numeral.getMin()) { - number = numeral.getMin(); - update = true; - } - if (number > numeral.getMax()) { - number = numeral.getMax(); - update = true; - } - editNumber.setInputType(0); - } - } catch (NumberFormatException e) { - number = choice.getChoice(); - update = true; - } - choice.setChoice(number); - if (update) - editNumber.setText(Integer.toString(number)); - seekBar.setProgress(number-numeral.getMin()); - updateSyntax(); - } - }); - - return view; - } - - private View createCheckBoxInputView(LayoutInflater inflater, final SyntacticChoice choice, final SyntaxNodeBoolean options, ViewGroup parent) { - View view = inflater.inflate(R.layout.checkbox_input_list_item, parent, false); - final CheckBox checkBox = (CheckBox) view.findViewById(R.id.choice_checkbox); - - String label = options.getDesc(); - if (label != null && !label.isEmpty()) { - checkBox.setText(label); - } - - checkBox.setChecked(choice.getChoice() == 1); - checkBox.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View view) { - int position = checkBox.isChecked() ? 1 : 0; - if (position != choice.getChoice()) { - choice.setChoice(position); - updateSyntax(); - } - } - }); - - return view; - } - - public void updateSyntax() { - mContext.reset(); - - Expr expr = phrase.getAbstractSyntax(mContext); - origin.setText(mTranslator.linearizeSource(expr)); - target.setText(mTranslator.linearize(expr)); - mAdapter.notifyDataSetChanged(); - } -} diff --git a/src/ui/android/topics.txt b/src/ui/android/topics.txt deleted file mode 100644 index 785d07ba4..000000000 --- a/src/ui/android/topics.txt +++ /dev/null @@ -1,951 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/gwt/.classpath b/src/ui/gwt/.classpath deleted file mode 100644 index 781d7a2f8..000000000 --- a/src/ui/gwt/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/src/ui/gwt/.project b/src/ui/gwt/.project deleted file mode 100644 index dfd6dab3f..000000000 --- a/src/ui/gwt/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - GF-GWT - GF-GWT project - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.google.gdt.eclipse.core.webAppProjectValidator - - - - - com.google.gwt.eclipse.core.gwtProjectValidator - - - - - - org.eclipse.jdt.core.javanature - com.google.gwt.eclipse.core.gwtNature - - diff --git a/src/ui/gwt/Editor-compile b/src/ui/gwt/Editor-compile deleted file mode 100644 index 4106298ea..000000000 --- a/src/ui/gwt/Editor-compile +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh - -APPDIR=`dirname $0`; - -if [ -z "$GWT_CLASSPATH" ]; then - echo 'ERROR: $GWT_CLASSPATH is not set' - echo 'Set $GWT_CLASSPATH to point to the GWT JAR files. For example:' - echo 'export GWT_DIR="/Users/bringert/src/gwt-2.0.4"' - echo 'export GWT_CLASSPATH="$GWT_DIR/gwt-user.jar:$GWT_DIR/gwt-dev.jar"' - exit 1 -fi - -if [ `uname` = "Darwin" ]; then - GWT_JAVA_OPTS=-XstartOnFirstThread -fi - -java $GWT_JAVA_OPTS -Xmx256M -cp "$APPDIR/src:$APPDIR/bin:$GWT_CLASSPATH" com.google.gwt.dev.Compiler -war "$APPDIR/www/editor" "$@" org.grammaticalframework.ui.gwt.EditorApp; diff --git a/src/ui/gwt/Editor-compile.bat b/src/ui/gwt/Editor-compile.bat deleted file mode 100644 index 2c9b77f4e..000000000 --- a/src/ui/gwt/Editor-compile.bat +++ /dev/null @@ -1,7 +0,0 @@ -@echo off - -set APPDIR=. -set GWT_DIR=C:\Program Files\eclipse\plugins\com.google.gwt.eclipse.sdkbundle.2.0.4_2.0.4.v201006301254\gwt-2.0.4 -set GWT_CLASSPATH=%GWT_DIR%\gwt-user.jar;%GWT_DIR%\gwt-dev.jar - -java %GWT_JAVA_OPTS% -Xmx256M -cp "%APPDIR%\src;%GWT_CLASSPATH%" com.google.gwt.dev.Compiler -war "%APPDIR%\www\editor" org.grammaticalframework.ui.gwt.EditorApp -style PRETTY diff --git a/src/ui/gwt/Fridge-compile b/src/ui/gwt/Fridge-compile deleted file mode 100644 index 887e253bc..000000000 --- a/src/ui/gwt/Fridge-compile +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh - -APPDIR=`dirname $0`; - -if [ -z "$GWT_CLASSPATH" ]; then - echo 'ERROR: $GWT_CLASSPATH is not set' - echo 'Set $GWT_CLASSPATH to point to the GWT JAR files. For example:' - echo 'export GWT_DIR="/Users/bringert/src/gwt-2.0.4"' - echo 'export GWT_CLASSPATH="$GWT_DIR/gwt-user.jar:$GWT_DIR/gwt-dev.jar"' - exit 1 -fi - -if [ `uname` = "Darwin" ]; then - GWT_JAVA_OPTS=-XstartOnFirstThread -fi - -java $GWT_JAVA_OPTS -Xmx256M -cp "$APPDIR/src:$APPDIR/bin:$GWT_CLASSPATH" com.google.gwt.dev.Compiler -war "$APPDIR/www/fridge" "$@" org.grammaticalframework.ui.gwt.FridgeApp; diff --git a/src/ui/gwt/Fridge-compile-fast b/src/ui/gwt/Fridge-compile-fast deleted file mode 100644 index 1a7a4df03..000000000 --- a/src/ui/gwt/Fridge-compile-fast +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -APPDIR=`dirname $0`; - -if [ -z "$GWT_CLASSPATH" ]; then - echo 'ERROR: $GWT_CLASSPATH is not set' - echo 'Set $GWT_CLASSPATH to point to the GWT JAR files. For example:' - echo 'export GWT_DIR="/Users/bringert/src/gwt-mac-1.5.2"' - echo 'export GWT_CLASSPATH="$GWT_DIR/gwt-user.jar:$GWT_DIR/gwt-dev-mac.jar"' - exit 1 -fi - -if [ `uname` = "Darwin" ]; then - GWT_JAVA_OPTS=-XstartOnFirstThread -fi - -LIBS=$APPDIR/lib/gwt-dnd-2.5.6.jar - -java $GWT_JAVA_OPTS -Xmx256M -cp "$APPDIR/src:$APPDIR/bin:$LIBS:$GWT_CLASSPATH" com.google.gwt.dev.GWTCompiler -out "$APPDIR/www" -style DETAILED "$@" se.chalmers.cs.gf.gwt.FridgeApp_IE6; diff --git a/src/ui/gwt/Fridge-compile.bat b/src/ui/gwt/Fridge-compile.bat deleted file mode 100644 index 8617d8528..000000000 --- a/src/ui/gwt/Fridge-compile.bat +++ /dev/null @@ -1,9 +0,0 @@ -@echo off - -set APPDIR=. -set GWT_DIR=c:\gwt-windows-1.5.2 -set GWT_CLASSPATH="%GWT_DIR%\gwt-user.jar;%GWT_DIR%\gwt-dev-windows.jar" - -set LIBS=%APPDIR%\lib\gwt-dnd-2.5.6.jar - -java %GWT_JAVA_OPTS% -Xmx256M -cp "%APPDIR%\src;%APPDIR%\bin;%LIBS%;%GWT_CLASSPATH%" com.google.gwt.dev.GWTCompiler -out "%APPDIR%\www\fridge" se.chalmers.cs.gf.gwt.FridgeApp diff --git a/src/ui/gwt/Fridge-shell-external b/src/ui/gwt/Fridge-shell-external deleted file mode 100644 index 1209047ed..000000000 --- a/src/ui/gwt/Fridge-shell-external +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -APPDIR=`dirname $0`; - -if [ -z "$GWT_CLASSPATH" ]; then - echo 'ERROR: $GWT_CLASSPATH is not set' - echo 'Set $GWT_CLASSPATH to point to the GWT JAR files. For example:' - echo 'export GWT_DIR="/Users/bringert/src/gwt-mac-1.5.2"' - echo 'export GWT_CLASSPATH="$GWT_DIR/gwt-user.jar:$GWT_DIR/gwt-dev-mac.jar"' - exit 1 -fi - -if [ `uname` = "Darwin" ]; then - GWT_JAVA_OPTS=-XstartOnFirstThread -fi - -LIBS=$APPDIR/lib/gwt-dnd-2.5.6.jar - -java $GWT_JAVA_OPTS -Xmx256M -cp "$APPDIR/src:$APPDIR/bin:$LIBS:$GWT_CLASSPATH" com.google.gwt.dev.GWTShell -out "$APPDIR/www" -noserver "$@" http://localhost:41296/fridge/; diff --git a/src/ui/gwt/Morpho-compile b/src/ui/gwt/Morpho-compile deleted file mode 100644 index 234e18322..000000000 --- a/src/ui/gwt/Morpho-compile +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh - -APPDIR=`dirname $0`; - -if [ -z "$GWT_CLASSPATH" ]; then - echo 'ERROR: $GWT_CLASSPATH is not set' - echo 'Set $GWT_CLASSPATH to point to the GWT JAR files. For example:' - echo 'export GWT_DIR="/Users/bringert/src/gwt-2.0.4"' - echo 'export GWT_CLASSPATH="$GWT_DIR/gwt-user.jar:$GWT_DIR/gwt-dev.jar"' - exit 1 -fi - -if [ `uname` = "Darwin" ]; then - GWT_JAVA_OPTS=-XstartOnFirstThread -fi - -java $GWT_JAVA_OPTS -Xmx256M -cp "$APPDIR/src:$APPDIR/bin:$LIBS:$GWT_CLASSPATH" com.google.gwt.dev.Compiler -war "$APPDIR/www/morpho" "$@" org.grammaticalframework.ui.gwt.MorphoApp; diff --git a/src/ui/gwt/Translate-compile b/src/ui/gwt/Translate-compile deleted file mode 100644 index 220cf4a46..000000000 --- a/src/ui/gwt/Translate-compile +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh - -APPDIR=`dirname $0`; - -if [ -z "$GWT_CLASSPATH" ]; then - echo 'ERROR: $GWT_CLASSPATH is not set' - echo 'Set $GWT_CLASSPATH to point to the GWT JAR files. For example:' - echo 'export GWT_DIR="/Users/bringert/src/gwt-2.0.4"' - echo 'export GWT_CLASSPATH="$GWT_DIR/gwt-user.jar:$GWT_DIR/gwt-dev.jar"' - exit 1 -fi - -if [ `uname` = "Darwin" ]; then - GWT_JAVA_OPTS=-XstartOnFirstThread -fi - -java $GWT_JAVA_OPTS -Xmx256M -cp "$APPDIR/src:$APPDIR/bin:$GWT_CLASSPATH" com.google.gwt.dev.Compiler -war "$APPDIR/www/translate" "$@" org.grammaticalframework.ui.gwt.TranslateApp; diff --git a/src/ui/gwt/Translate-compile.bat b/src/ui/gwt/Translate-compile.bat deleted file mode 100644 index df3ee9389..000000000 --- a/src/ui/gwt/Translate-compile.bat +++ /dev/null @@ -1,9 +0,0 @@ -@echo off - -set APPDIR=. -set GWT_DIR=c:\gwt-windows-1.5.2 -set GWT_CLASSPATH="%GWT_DIR%\gwt-user.jar;%GWT_DIR%\gwt-dev-windows.jar" - -set LIBS=%APPDIR%\lib\gwt-dnd-2.5.6.jar - -java %GWT_JAVA_OPTS% -Xmx256M -cp "%APPDIR%\src;%APPDIR%\bin;%LIBS%;%GWT_CLASSPATH%" com.google.gwt.dev.GWTCompiler -out "%APPDIR%\www\translate" se.chalmers.cs.gf.gwt.TranslateApp diff --git a/src/ui/gwt/Translate-shell-external b/src/ui/gwt/Translate-shell-external deleted file mode 100644 index b1e58f019..000000000 --- a/src/ui/gwt/Translate-shell-external +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -APPDIR=`dirname $0`; - -if [ -z "$GWT_CLASSPATH" ]; then - echo 'ERROR: $GWT_CLASSPATH is not set' - echo 'Set $GWT_CLASSPATH to point to the GWT JAR files. For example:' - echo 'export GWT_DIR="/Users/bringert/src/gwt-mac-1.5.2"' - echo 'export GWT_CLASSPATH="$GWT_DIR/gwt-user.jar:$GWT_DIR/gwt-dev-mac.jar"' - exit 1 -fi - -if [ `uname` = "Darwin" ]; then - GWT_JAVA_OPTS=-XstartOnFirstThread -fi - -LIBS=$APPDIR/lib/gwt-dnd-2.5.6.jar - -java $GWT_JAVA_OPTS -Xmx256M -cp "$APPDIR/src:$APPDIR/bin:$LIBS:$GWT_CLASSPATH" com.google.gwt.dev.GWTShell -out "$APPDIR/www" -noserver "$@" http://localhost:41296/translate/; diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/EditorApp.gwt.xml b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/EditorApp.gwt.xml deleted file mode 100644 index a7b24c1af..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/EditorApp.gwt.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/FridgeApp.gwt.xml b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/FridgeApp.gwt.xml deleted file mode 100644 index b041f9830..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/FridgeApp.gwt.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/FridgeApp_IE6.gwt.xml b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/FridgeApp_IE6.gwt.xml deleted file mode 100644 index 70d2b1714..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/FridgeApp_IE6.gwt.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/MorphoApp.gwt.xml b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/MorphoApp.gwt.xml deleted file mode 100644 index 9bdd8d5ac..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/MorphoApp.gwt.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/PGF.gwt.xml b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/PGF.gwt.xml deleted file mode 100644 index 549a16f0d..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/PGF.gwt.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/TranslateApp.gwt.xml b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/TranslateApp.gwt.xml deleted file mode 100644 index ef51227ec..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/TranslateApp.gwt.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/BrowsePanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/BrowsePanel.java deleted file mode 100644 index 3f4c8a9a4..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/BrowsePanel.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; -import com.google.gwt.user.client.History; -import com.google.gwt.user.client.HistoryListener; -import com.google.gwt.user.client.Command; -import com.google.gwt.user.client.DeferredCommand; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.http.client.*; -import com.google.gwt.xml.client.*; -import com.google.gwt.event.logical.shared.*; - -public class BrowsePanel extends Composite { - - private PGFWrapper pgf; - private StatusPopup statusPopup; - private HTML sourceView; - private SuggestBox searchBox; - private CompletionOracle oracle; - private List identifiers = null; - - public BrowsePanel(PGFWrapper pgf, StatusPopup statusPopup) { - this.pgf = pgf; - this.statusPopup = statusPopup; - - oracle = new CompletionOracle(); - - HorizontalPanel browsePanel = new HorizontalPanel(); - VerticalPanel vPanel = new VerticalPanel(); - vPanel.add(createSearchPanel(oracle)); - vPanel.add(createTreeView()); - browsePanel.add(vPanel); - browsePanel.add(createSourcePanel()); - browsePanel.setCellWidth(sourceView,"100%"); - - initWidget(browsePanel); - setStylePrimaryName("my-BrowsePanel"); - - pgf.addSettingsListener(new MySettingsListener(pgf)); - } - - public native void onActivate() /*-{ - $doc.browsePanel = this; - $doc.callBrowse = @org.grammaticalframework.ui.gwt.client.BrowsePanel::callBrowse(Lorg/grammaticalframework/ui/gwt/client/BrowsePanel;Ljava/lang/String;); - }-*/; - - protected Widget createSearchPanel(CompletionOracle oracle) { - searchBox = new SuggestBox(oracle); - searchBox.setLimit(10); - searchBox.addKeyboardListener(new KeyboardListenerAdapter() { - public void onKeyUp (Widget sender, char keyCode, int modifiers) { - if (keyCode == KEY_ENTER) { - callBrowse(BrowsePanel.this,searchBox.getText()); - } - } - }); - - DecoratorPanel decorator = new DecoratorPanel(); - VerticalPanel vPanel = new VerticalPanel(); - vPanel.add(new Label("Search")); - vPanel.add(searchBox); - decorator.add(vPanel); - return decorator; - } - - private static void callBrowse(BrowsePanel panel, String id) { - panel.browse(id); - History.newItem("browse:"+id, false); - } - - public void browse(final String id) { - if (id == null || id.equals("")) { - sourceView.setHTML(""); - return; - } - - pgf.browse(id, "javascript:document.callBrowse(document.browsePanel,'$ID')", - "my-identifierLink", - new RequestCallback() { - public void onResponseReceived(Request request, Response response) { - sourceView.setHTML(response.getText()); - } - - public void onError(Request request, java.lang.Throwable e) { - statusPopup.showError("Cannot load the page", e); - } - }); - } - - protected Widget createTreeView() { - hierarchyTree = new Tree(); - hierarchyTree.addSelectionHandler(new SelectionHandler() { - public void onSelection(SelectionEvent event) { - TreeItem item = event.getSelectedItem(); - callBrowse(BrowsePanel.this,item.getText()); - } - }); - return hierarchyTree; - } - - protected Widget createSourcePanel() { - sourceView = new HTML(); - sourceView.setStylePrimaryName("source"); - return sourceView; - } - - protected class CompletionOracle extends SuggestOracle { - - public CompletionOracle() { - } - - public void requestSuggestions(SuggestOracle.Request request, SuggestOracle.Callback callback) { - List list = new ArrayList(); - - int index = Collections.binarySearch(identifiers, request.getQuery()); - index = (index >= 0) ? index : -(index+1); - - for (; index < identifiers.size(); index++) { - String id = identifiers.get(index); - - if (id.startsWith(request.getQuery())) { - list.add(new CompletionSuggestion(id)); - } - else - break; - - if (list.size() > request.getLimit()) - break; - } - - callback.onSuggestionsReady(request, new SuggestOracle.Response(list)); - } - } - - protected static class CompletionSuggestion implements SuggestOracle.Suggestion { - private String string; - - public CompletionSuggestion(String string) { - this.string = string; - } - - public String getDisplayString() { - return string; - } - - public String getReplacementString() { - return string; - } - } - - Tree hierarchyTree = null; - - protected void reloadHierarchyTree() { - hierarchyTree.clear(); - - final String url = pgf.getGrammarURL()+".xml"; - RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); - try - { - builder.sendRequest(null, new RequestCallback() { - public void onResponseReceived(Request request, Response response) - { - if (200 == response.getStatusCode()) - { - try - { - Document browseDoc = XMLParser.parse(response.getText()); - - TreeLoader loader = new TreeLoader(); - - Element element = browseDoc.getDocumentElement(); - NodeList children = element.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node node = children.item(i); - if (node instanceof Element) { - Element childElement = (Element) node; - TreeItem childItem = hierarchyTree.addItem(childElement.getAttribute("name")); - loader.push(childElement, childItem); - } - } - - loader.execute(); - } - catch (DOMException e) - { - } - } - else - { - } - } - - public void onError(Request request, Throwable e) - { - } - }); - } - catch (RequestException e) - { - } - } - - private class TreeLoader implements Command { - private int count = 0; - private ArrayList elements = new ArrayList(); - private ArrayList items = new ArrayList(); - - public void execute() { - for (int n = 0; n < 100; n++) { - if (count <= 0) - return; - - int index = --count; - Element element = (Element) elements.remove(index); - TreeItem item = (TreeItem) items.remove(index); - - NodeList children = element.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node node = children.item(i); - if (node instanceof Element) { - Element childElement = (Element) node; - TreeItem childItem = item.addItem(childElement.getAttribute("name")); - push(childElement, childItem); - } - } - } - DeferredCommand.addCommand(this); - } - - public final void push(Element element, TreeItem item) { - elements.add(element); - items.add(item); - count++; - } - } - - protected class MySettingsListener implements SettingsListener { - - private PGFWrapper pgf; - - public MySettingsListener(PGFWrapper pgf) { - this.pgf = pgf; - } - - public void onAvailableGrammarsChanged() { } - public void onSelectedGrammarChanged() - { - List ids = new ArrayList(); - - for (int i = 0; i < pgf.getCategories().length(); i++) { - ids.add(pgf.getCategories().get(i)); - } - for (int i = 0; i < pgf.getFunctions().length(); i++) { - ids.add(pgf.getFunctions().get(i)); - } - - Collections.sort(ids); - - identifiers = ids; - sourceView.setText(""); - searchBox.setText(""); - reloadHierarchyTree(); - } - public void onInputLanguageChanged() { } - public void onOutputLanguageChanged() { } - public void onStartCategoryChanged() { } - public void onSettingsError(String msg, Throwable e) { } - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/CompletionOracle.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/CompletionOracle.java deleted file mode 100644 index 7ea5d2be6..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/CompletionOracle.java +++ /dev/null @@ -1,152 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.google.gwt.user.client.ui.SuggestOracle; - -public class CompletionOracle extends SuggestOracle { - - private static final int LIMIT_SCALE_FACTOR = 4; - - private PGFWrapper pgf; - - private ErrorHandler errorHandler; - - private JSONRequest jsonRequest = null; - - private String oldQuery = null; - - private List oldSuggestions = Collections.emptyList(); - - - public CompletionOracle (PGFWrapper pgf) { - this(pgf, null); - } - - public CompletionOracle (PGFWrapper pgf, ErrorHandler errorHandler) { - this.pgf = pgf; - this.errorHandler = errorHandler; - pgf.addSettingsListener(new SettingsListener() { - public void onAvailableGrammarsChanged() { clearState(); } - public void onSelectedGrammarChanged() { clearState(); } - public void onInputLanguageChanged() { clearState(); } - public void onOutputLanguageChanged() { clearState(); } - public void onStartCategoryChanged() { clearState(); } - public void onSettingsError(String msg, Throwable e) { clearState(); } - }); - } - - private void clearState () { - this.oldQuery = null; - this.oldSuggestions = Collections.emptyList(); - if (jsonRequest != null) { - jsonRequest.cancel(); - jsonRequest = null; - } - } - - public void setErrorHandler(ErrorHandler errorHandler) { - this.errorHandler = errorHandler; - } - - public static interface ErrorHandler { - public void onError(Throwable e); - } - - public static class CompletionSuggestion implements SuggestOracle.Suggestion { - private String string; - public CompletionSuggestion(String string) { - this.string = string; - } - - public String getDisplayString() { - return string; - } - - public String getReplacementString() { - return string; - } - } - - public void requestSuggestions(SuggestOracle.Request request, SuggestOracle.Callback callback) { - // Only allow a single completion request at a time - if (jsonRequest != null) { - jsonRequest.cancel(); - jsonRequest = null; - } - - List suggestions = filterOldSuggestions(request); - if (suggestions != null) { - suggestionsReady(request, callback, suggestions); - } else { - retrieveSuggestions(request, callback); - } - } - - /** Filters old suggestions and checks if we still have enough suggestions. */ - private List filterOldSuggestions(SuggestOracle.Request request) { - String query = request.getQuery(); - if (query.length() > 0 && oldQuery != null && query.startsWith(oldQuery)) { - // If the prefix had no completions, there is no way that the current input will. - if (oldSuggestions.isEmpty()) { - return Collections.emptyList(); - } - // If the new input since the previous query ends in whitespace, - // always get completions from the server, - // since the old suggestions won't include the next word. - if (query.indexOf(' ', oldQuery.length()) != -1) { - return null; - } - List suggestions = new ArrayList(); - for (CompletionSuggestion c : oldSuggestions) { - if (c.getReplacementString().startsWith(query)) { - suggestions.add(c); - } - } - if (suggestions.size() >= request.getLimit() || oldSuggestions.size() < request.getLimit()) { - return suggestions; - } - } - return null; - } - - private void retrieveSuggestions(final SuggestOracle.Request request, final SuggestOracle.Callback callback) { - // hack: first report no completions, to hide suggestions until we get the new completions - callback.onSuggestionsReady(request, new SuggestOracle.Response(Collections.emptyList())); - - jsonRequest = pgf.complete(request.getQuery(), LIMIT_SCALE_FACTOR * request.getLimit(), - new PGF.CompleteCallback() { - public void onResult(IterableJsArray completions) { - jsonRequest = null; - List suggestions = new ArrayList(); - for (PGF.Completion completion : completions.iterable()) { - String text = completion.getBracketedString().render(); - for (String tokn : completion.getCompletions()) { - StringBuilder sbuilder = new StringBuilder(); - sbuilder.append(text); - if (sbuilder.length() > 0) - sbuilder.append(' '); - sbuilder.append(tokn); - suggestions.add(new CompletionSuggestion(sbuilder.toString())); - } - } - suggestionsReady(request, callback, suggestions); - } - - public void onError(Throwable e) { - errorHandler.onError(e); - } - - }); - } - - private void suggestionsReady(SuggestOracle.Request request, SuggestOracle.Callback callback, List suggestions) { - this.oldQuery = request.getQuery(); - this.oldSuggestions = suggestions; - suggestions = suggestions.size() <= request.getLimit() ? suggestions : SubList.makeSubList(suggestions, 0, request.getLimit()); - callback.onSuggestionsReady(request, new SuggestOracle.Response(suggestions)); - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/ContentService.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/ContentService.java deleted file mode 100644 index fd336bf34..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/ContentService.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import org.grammaticalframework.ui.gwt.client.JSONRequestBuilder.Arg; - -import java.util.*; -import com.google.gwt.core.client.*; - -public class ContentService { - - // Event listeners - private List listeners = new LinkedList(); - private List grammars = null; - - - public ContentService() { - } - - public static class Init extends JavaScriptObject { - protected Init() { } - - public final native String getUserId() /*-{ return this.userId; }-*/; - public final native String getUserURL() /*-{ return this.userURL; }-*/; - public final native String getUserEMail() /*-{ return this.userEMail; }-*/; - public final native String getContentURL() /*-{ return this.contentURL; }-*/; - } - - public static final native Init getInit() /*-{ - return $wnd.__gfInit; - }-*/; - - public void addSettingsListener(SettingsListener listener) { - listeners.add(listener); - } - - public void updateAvailableGrammars() { - List args = new ArrayList(); - args.add(new Arg("userId", getInit().getUserId())); - args.add(new Arg("command", "grammars")); - JSONRequestBuilder.sendRequest(getInit().getContentURL(), args, new GrammarsCallback() { - public void onResult(IterableJsArray grammars_) { - grammars = new ArrayList(); - for (ContentService.GrammarInfo grammar : grammars_.iterable()) { - grammars.add(grammar); - } - - for (SettingsListener listener : listeners) { - listener.onAvailableGrammarsChanged(); - } - } - - public void onError(Throwable e) { - } - }); - } - - public List getGrammars() { - return grammars; - } - - public interface GrammarsCallback extends JSONCallback> {} - - public static class GrammarInfo extends JavaScriptObject { - protected GrammarInfo() { } - - public final native String getURL() /*-{ return this.url; }-*/; - public final native String getName() /*-{ return this.name; }-*/; - public final native String getDescription() /*-{ return this.description; }-*/; - } - - public JSONRequest deleteGrammar(String grammarURL, DeleteCallback callback) { - List args = new ArrayList(); - args.add(new Arg("url", grammarURL)); - args.add(new Arg("userId", getInit().getUserId())); - args.add(new Arg("command", "delete_grammar")); - return JSONRequestBuilder.sendRequest(getInit().getContentURL(), args, callback); - } - - public JSONRequest save(Object id, String content, SaveCallback callback) { - List args = new ArrayList(); - if (id != null) - args.add(new Arg("id", id.toString())); - args.add(new Arg("command", "save")); - return JSONRequestBuilder.sendDataRequest(getInit().getContentURL(), args, content, callback); - } - - public interface SaveCallback extends JSONCallback {} - - public JSONRequest load(Object id, LoadCallback callback) { - List args = new ArrayList(); - args.add(new Arg("command", "load")); - args.add(new Arg("id", id.toString())); - return JSONRequestBuilder.sendRequest(getInit().getContentURL(), args, callback); - } - - public interface LoadCallback extends JSONCallback {} - - public JSONRequest search(String fullTextQuery, SearchCallback callback) { - List args = new ArrayList(); - args.add(new Arg("command", "search")); - args.add(new Arg("query", fullTextQuery)); - return JSONRequestBuilder.sendRequest(getInit().getContentURL(), args, callback); - } - - public interface SearchCallback extends JSONCallback> {} - - public static class DocumentSignature extends JavaScriptObject { - protected DocumentSignature() { } - - public final native int getId() /*-{ return this.id; }-*/; - public final native String getTitle() /*-{ return this.title; }-*/; - public final native String getCreated() /*-{ return this.created; }-*/; - public final native String getModified() /*-{ return this.modified; }-*/; - } - - public static class Document extends DocumentSignature { - protected Document() { } - - public final native String getContent() /*-{ return this.content; }-*/; - } - - public JSONRequest delete(List ids, DeleteCallback callback) { - List args = new ArrayList(); - args.add(new Arg("command", "delete")); - for (Object id : ids) { - args.add(new Arg("id", id.toString())); - } - return JSONRequestBuilder.sendRequest(getInit().getContentURL(), args, callback); - } - - public interface DeleteCallback extends JSONCallback {} - - public static class DeleteResult extends JavaScriptObject { - protected DeleteResult() { } - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/DocumentsPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/DocumentsPanel.java deleted file mode 100644 index 09acce5f5..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/DocumentsPanel.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; -import com.google.gwt.user.client.*; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.http.client.*; -import com.google.gwt.xml.client.*; -import com.google.gwt.event.logical.shared.*; -import com.google.gwt.event.dom.client.*; -import com.google.gwt.event.shared.*; - -public class DocumentsPanel extends Composite implements HasSelectionHandlers { - - private PGFWrapper pgf; - private ContentService contentService; - private StatusPopup statusPopup; - private FlexTable table; - private ArrayList documentIds = new ArrayList(); - - public DocumentsPanel(PGFWrapper pgf, ContentService contentService, StatusPopup statusPopup) { - this.pgf = pgf; - this.contentService = contentService; - this.statusPopup = statusPopup; - - VerticalPanel documentsPanel = new VerticalPanel(); - documentsPanel.setStylePrimaryName("my-DocumentsFrame"); - - HorizontalPanel searchPanel = new HorizontalPanel(); - searchPanel.setStylePrimaryName("my-DocumentsSearchFrame"); - final TextBox searchBox = new TextBox(); - searchBox.setWidth("20em"); - final Button searchBtn = new Button("Search"); - searchPanel.add(searchBox); - searchPanel.add(searchBtn); - documentsPanel.add(searchPanel); - - Image deleteButton = new Image("org.grammaticalframework.ui.gwt.EditorApp/trash-button.png"); - deleteButton.setTitle("Deletes the selected documents."); - deleteButton.setStylePrimaryName("toolbar-button"); - deleteButton.addClickListener(new ClickListener () { - public void onClick(Widget sender) { - deleteSelected(); - } - }); - - FlexTable header = new FlexTable(); - header.setStylePrimaryName("my-TableHeader"); - header.setText(0,0,"Documents"); - header.setWidget(0,1,deleteButton); - header.getColumnFormatter().setWidth(1,"20px"); - documentsPanel.add(header); - - table = new FlexTable(); - table.setCellPadding(2); - table.setStylePrimaryName("my-DocumentsTable"); - table.getColumnFormatter().setWidth(1,"80em"); - table.getColumnFormatter().setWidth(2,"80em"); - documentsPanel.add(table); - - searchBtn.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent event) { - searchDocuments(searchBox.getText()); - } - }); - table.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent event) { - HTMLTable.Cell cell = table.getCellForEvent(event); - if (cell != null) { - int row = cell.getRowIndex(); - selectDocument(row); - } - } - }); - - initWidget(documentsPanel); - setStylePrimaryName("my-DocumentsPanel"); - } - - public HandlerRegistration addSelectionHandler(SelectionHandler handler) { - return addHandler(handler, SelectionEvent.getType()); - } - - protected void selectDocument(int row) { - SelectionEvent.fire(this, documentIds.get(row)); - } - - protected void searchDocuments(String fullTextQuery) { - statusPopup.setStatus("Searching..."); - - documentIds.clear(); - while (table.getRowCount() > 0) - table.removeRow(0); - - contentService.search(fullTextQuery, new ContentService.SearchCallback() { - public void onResult(IterableJsArray documents) { - for (ContentService.DocumentSignature sign : documents.iterable()) { - int row = table.getRowCount(); - table.setWidget(row, 0, new CheckBox(sign.getTitle())); - table.setText(row, 1, sign.getCreated()); - table.setText(row, 2, sign.getModified()); - table.getRowFormatter().addStyleName(row, "row"); - documentIds.add(sign.getId()); - } - - statusPopup.clearStatus(); - } - - public void onError(Throwable e) { - statusPopup.showError("Search failed", e); - } - }); - } - - protected void deleteSelected() { - statusPopup.setStatus("Deleting..."); - - final ArrayList ids = new ArrayList(); - final ArrayList rows = new ArrayList(); - for (int row = 0; row < table.getRowCount(); row++) { - CheckBox checkBox = (CheckBox) table.getWidget(row,0); - if (checkBox.isChecked()) { - ids.add(documentIds.get(row)); - rows.add(new Integer(row)); - } - } - - contentService.delete(ids, new ContentService.DeleteCallback() { - public void onResult(ContentService.DeleteResult result) { - for (Integer row : rows) { - table.removeRow(row.intValue()); - } - - statusPopup.clearStatus(); - } - - public void onError(Throwable e) { - statusPopup.showError("Delete failed", e); - } - }); - - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/EditorApp.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/EditorApp.java deleted file mode 100644 index ece9ecac8..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/EditorApp.java +++ /dev/null @@ -1,461 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.core.client.*; -import com.google.gwt.user.client.*; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.event.dom.client.*; -import com.google.gwt.event.logical.shared.*; -import com.google.gwt.event.shared.*; - -public class EditorApp implements EntryPoint { - - protected ContentService contentService; - protected PGFWrapper pgf; - - protected SettingsPanel settingsPanel; - protected VerticalPanel outputPanel; - protected Widget editorPanel; - protected BrowsePanel browsePanel; - protected QueryPanel queryPanel; - protected DocumentsPanel documentsPanel; - protected GrammarsPanel grammarsPanel; - protected StatusPopup statusPopup; - protected TextInputPanel textPanel; - protected FridgeBagPanel bagPanel; - protected MagnetFactory magnetFactory; - protected TabBar tabBar; - - private JSONRequest completeRequest = null; - private JSONRequest translateRequest = null; - - private int maxMagnets = 100; - private static final int LIMIT_SCALE_FACTOR = 4; - - private String cachedPrefix = null; - private List cachedMagnets = Collections.emptyList(); - - // - // Update - // - protected void update() { - clearMagnetCache(); - updateBag(""); - updateTranslation(); - } - - protected void clearMagnetCache() { - cachedPrefix = null; - cachedMagnets = Collections.emptyList(); - } - - protected void updateTranslation() { - if (translateRequest != null) { - translateRequest.cancel(); - } - - outputPanel.clear(); - outputPanel.addStyleDependentName("working"); - translateRequest = pgf.translate(textPanel.getText(), - new PGF.TranslateCallback() { - public void onResult (IterableJsArray translations) { - translateRequest = null; - - outputPanel.clear(); - outputPanel.removeStyleDependentName("working"); - for (PGF.TranslationResult tr : translations.iterable()) { - textPanel.renderBracketedString(tr.getBracketedString()); - - if (tr.getTranslations() != null) - for (PGF.Linearizations lins : tr.getTranslations().iterable()) { - LinearizationsPanel lin = new LinearizationsPanel(pgf, lins); - lin.setWidth("100%"); - outputPanel.add(lin); - } - - if (tr.getTypeErrors() != null && tr.getTypeErrors().length > 0) { - for (PGF.TcError error : tr.getTypeErrors()) { - VerticalPanel panel = new VerticalPanel(); - panel.addStyleName("my-typeError"); - Label errLabel = new Label("Type Error"); - errLabel.addStyleName("title"); - panel.add(errLabel); - panel.add(createErrorMsg(error)); - outputPanel.add(panel); - } - textPanel.showError(tr.getTypeErrors()[0].getFId()); - } - } - } - public void onError (Throwable e) { - translateRequest = null; - - statusPopup.showError("Translation failed", e); - } - }); - } - - private class Callback { - private String prefix; - - public Callback(String prefix) { - this.prefix = prefix; - } - - public void onResult(List magnets) { - bagPanel.fill(magnets); - - if (magnets.size() == 0) { - if (prefix.isEmpty()) { - textPanel.hideSearchBox(); - textPanel.setFocus(true); - } - else - textPanel.showSearchError(); - } else { - textPanel.clearSearchError(); - } - } - } - - public void updateBag(String prefix) { - Callback callback = new Callback(prefix); - List magnets = filterCachedMagnets(prefix); - if (magnets != null) - callback.onResult(magnets); - else - retrieveMagnets(prefix, callback); - } - - public List filterCachedMagnets(final String prefix) { - if (prefix.length() > 0 && cachedPrefix != null && prefix.startsWith(cachedPrefix)) { - // If the prefix had no completions, there is no way that the current input will. - if (cachedMagnets.isEmpty()) { - return Collections.emptyList(); - } - - List magnets = new ArrayList(); - for (Magnet magnet : cachedMagnets) { - if (magnet.getWord().startsWith(prefix)) { - magnets.add(magnet); - if (magnets.size() >= maxMagnets) - return magnets; - } - } - } - return null; - } - - public void retrieveMagnets(final String prefix, final Callback callback) { - final String query = textPanel.getText() + " " + prefix; - - if (completeRequest != null) { - completeRequest.cancel(); - } - - bagPanel.clear(); - completeRequest = pgf.complete(query, LIMIT_SCALE_FACTOR * maxMagnets, - new PGF.CompleteCallback() { - public void onResult(IterableJsArray completions) { - completeRequest = null; - - cachedPrefix = query; - cachedMagnets = new ArrayList(); - - for (PGF.Completion completion : completions.iterable()) { - textPanel.renderBracketedString(completion.getBracketedString()); - if (completion.getCompletions() != null) { - if (completion.getText() != prefix) - textPanel.setSearchTerm(completion.getText()); - - for (String word : completion.getCompletions()) { - Magnet magnet = magnetFactory.createMagnet(word, completion.getFrom()); - cachedMagnets.add(magnet); - } - } else { - textPanel.setSearchTerm(completion.getText()); - } - } - - List magnets = new ArrayList(); - for (Magnet magnet : cachedMagnets) { - magnets.add(magnet); - if (magnets.size() >= maxMagnets) - break; - } - callback.onResult(magnets); - } - - public void onError(Throwable e) { - completeRequest = null; - - statusPopup.showError("Getting completions failed", e); - } - }); - } - - // - // GUI - // - - protected Widget createUI() { - editorPanel = createEditorPanel(); - browsePanel = createBrowsePanel(); - queryPanel = createQueryPanel(); - documentsPanel = createDocumentsPanel(); - grammarsPanel = createGrammarsPanel(); - - VerticalPanel vPanel = new VerticalPanel(); - vPanel.setWidth("100%"); - vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER); - - HorizontalPanel hPanel = new HorizontalPanel(); - hPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); - hPanel.setStylePrimaryName("my-HeaderPanel"); - - TabBar linksPanel = createLinksPanel(vPanel); - hPanel.add(linksPanel); - hPanel.setCellHorizontalAlignment(linksPanel,HorizontalPanel.ALIGN_LEFT); - linksPanel.selectTab(1); - - settingsPanel = createSettingsPanel(); - hPanel.add(settingsPanel); - hPanel.setCellHorizontalAlignment(settingsPanel,HorizontalPanel.ALIGN_RIGHT); - - vPanel.add(hPanel); - vPanel.add(editorPanel); - - return vPanel; - } - - protected SettingsPanel createSettingsPanel () { - return new SettingsPanel(pgf, contentService, statusPopup); - } - - protected Widget createEditorPanel() { - textPanel = new TextInputPanel(contentService, statusPopup); - textPanel.addValueChangeHandler(new ValueChangeHandler() { - public void onValueChange(ValueChangeEvent event) { - update(); - } - }); - textPanel.addSelectionHandler(new SelectionHandler() { - public void onSelection(SelectionEvent event) { - String prefix = event.getSelectedItem(); - char lastChar = prefix.charAt(prefix.length()-1); - - Iterator iter = bagPanel.iterator(); - if ((Character.isSpace(lastChar) || lastChar == 160) && iter.hasNext()) { - Magnet magnet = iter.next(); - textPanel.setSearchTerm(""); - textPanel.addMagnet(magnet); - } - else - updateBag(prefix); - } - }); - - final ClickListener magnetClickListener = new ClickListener () { - public void onClick(Widget widget) { - Magnet magnet = (Magnet)widget; - textPanel.hideSearchBox(); - textPanel.addMagnet(magnet); - textPanel.setFocus(true); - } - }; - magnetFactory = new MagnetFactory(magnetClickListener); - - bagPanel = new FridgeBagPanel(); - - outputPanel = new VerticalPanel(); - outputPanel.addStyleName("my-translations"); - - final DockPanel editorPanel = new DockPanel(); - editorPanel.setStyleName("my-EditorPanel"); - editorPanel.add(textPanel, DockPanel.NORTH); - editorPanel.add(bagPanel, DockPanel.CENTER); - editorPanel.add(outputPanel, DockPanel.EAST); - - editorPanel.setCellHeight(bagPanel, "100%"); - editorPanel.setCellWidth(bagPanel, "70%"); - editorPanel.setCellHeight(outputPanel, "100%"); - editorPanel.setCellWidth(outputPanel, "30%"); - editorPanel.setCellVerticalAlignment(bagPanel, HasVerticalAlignment.ALIGN_TOP); - editorPanel.setCellHorizontalAlignment(outputPanel, HasHorizontalAlignment.ALIGN_RIGHT); - - Window.addWindowResizeListener(new WindowResizeListener() { - public void onWindowResized(int w, int h) { - editorPanel.setPixelSize(w-20, h-50); - } - }); - int w = Window.getClientWidth(); - int h = Window.getClientHeight(); - editorPanel.setPixelSize(w-20, h-50); - - return editorPanel; - } - - protected BrowsePanel createBrowsePanel() { - return new BrowsePanel(pgf, statusPopup); - } - - protected QueryPanel createQueryPanel() { - return new QueryPanel(pgf, statusPopup); - } - - protected DocumentsPanel createDocumentsPanel() { - DocumentsPanel panel = new DocumentsPanel(pgf, contentService, statusPopup); - panel.addSelectionHandler(new SelectionHandler() { - public void onSelection(SelectionEvent event) { - tabBar.selectTab(1); - textPanel.load(event.getSelectedItem()); - } - }); - return panel; - } - - protected GrammarsPanel createGrammarsPanel() { - return new GrammarsPanel(pgf, contentService, statusPopup); - } - - protected TabBar createLinksPanel(final Panel parent) { - tabBar = new TabBar(); - tabBar.setStylePrimaryName("my-LinksPanel"); - tabBar.addTab("Documents"); - tabBar.addTab("Editor"); - tabBar.addTab("Query"); - tabBar.addTab("Browse"); - tabBar.addTab("Grammars"); - - NavigationHandler handler = new NavigationHandler(tabBar, parent); - tabBar.addSelectionHandler(handler); - History.addHistoryListener(handler); - - return tabBar; - } - - // - // History stuff - // - - protected class NavigationHandler implements HistoryListener, SelectionHandler { - private final TabBar linksPanel; - private final Panel parent; - private int level = 0; - - public NavigationHandler(TabBar linksPanel, Panel parent) { - this.linksPanel = linksPanel; - this.parent = parent; - } - - public void onSelection(SelectionEvent event) { - parent.remove(documentsPanel); - parent.remove(editorPanel); - parent.remove(queryPanel); - parent.remove(browsePanel); - parent.remove(grammarsPanel); - - switch (event.getSelectedItem().intValue()) { - case 0: parent.add(documentsPanel); - if (level == 0) History.newItem("documents", false); - break; - case 1: parent.add(editorPanel); - if (level == 0) History.newItem("editor", false); - break; - case 2: parent.add(queryPanel); - if (level == 0) History.newItem("query", false); - break; - case 3: parent.add(browsePanel); - if (level == 0) History.newItem("browse", false); - browsePanel.onActivate(); - break; - case 4: parent.add(grammarsPanel); - if (level == 0) History.newItem("grammars", false); - break; - } - } - - public void onHistoryChanged(String token) { - level++; - - if (token.equals("documents")) { - linksPanel.selectTab(0); - } else if (token.equals("editor")) { - linksPanel.selectTab(1); - } else if (token.equals("query")) { - linksPanel.selectTab(2); - } else if (token.equals("browse")) { - linksPanel.selectTab(3); - browsePanel.onActivate(); - browsePanel.browse(null); - } else if (token.startsWith("browse:")) { - linksPanel.selectTab(3); - browsePanel.browse(token.substring(7)); - } else if (token.equals("grammars")) { - linksPanel.selectTab(4); - } - - level--; - } - }; - - protected Widget createErrorMsg(final PGF.TcError error) { - HTML msgHTML = new HTML("
    "+error.getMsg()+"
    "); - msgHTML.addStyleName("content"); - msgHTML.addClickListener(new ClickListener() { - public void onClick(Widget sender) { - textPanel.showError(error.getFId()); - } - }); - return msgHTML; - } - - // - // Initialization - // - - protected class MySettingsListener implements SettingsListener { - // Will only happen on load - public void onAvailableGrammarsChanged() { - if (pgf.getGrammarURL() == null) { - List grammars = pgf.getGrammars(); - if (!grammars.isEmpty()) { - pgf.setGrammarURL(grammars.get(0)); - } - } - } - public void onSelectedGrammarChanged() { - textPanel.clear(); - if (pgf.getInputLanguage() == null) { - GWT.log("Setting input language to user language: " + pgf.getUserLanguage(), null); - pgf.setInputLanguage(pgf.getUserLanguage()); - } - update(); - } - public void onInputLanguageChanged() { - update(); - } - public void onOutputLanguageChanged() { - update(); - } - public void onStartCategoryChanged() { - update(); - } - public void onSettingsError(String msg, Throwable e) { - statusPopup.showError(msg,e); - } - } - - public void onModuleLoad() { - statusPopup = new StatusPopup(); - - pgf = new PGFWrapper(); - contentService = new ContentService(); - RootPanel.get().add(createUI()); - pgf.addSettingsListener(new MySettingsListener()); - contentService.updateAvailableGrammars(); - - textPanel.setFocus(true); - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeApp.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeApp.java deleted file mode 100644 index 4e9963451..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeApp.java +++ /dev/null @@ -1,338 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.core.client.EntryPoint; -import com.google.gwt.user.client.*; -import com.google.gwt.user.client.ui.*; - - -public class FridgeApp implements EntryPoint { - - protected static final String pgfBaseURL = "/grammars"; - - protected PGFWrapper pgf; - - protected JSONRequest completeRequest = null; - protected JSONRequest translateRequest = null; - - private FridgeBagPanel bagPanel; - private FridgeTextPanel textPanel; - protected VerticalPanel outputPanel; - protected StatusPopup statusPopup; - - private FlowPanel prefixPanel; - private LinkedHashSet prefixes = new LinkedHashSet(); - - private int maxMagnets = 100; - - private MagnetFactory magnetFactory; - - // - // Text - // - - protected void update () { - updateBag(getText()); - translate(); - } - - public void updateBag (String text) { - updateBag(text, ""); - } - - public void updateBag (final String text, String prefix) { - if (completeRequest != null) { - completeRequest.cancel(); - } - final boolean updatePrefixes = prefix.equals(""); - bagPanel.clear(); - bagPanel.addStyleDependentName("empty"); - if (updatePrefixes) { clearPrefixes(); } - int limit = updatePrefixes ? 0 : maxMagnets; - completeRequest = pgf.complete(text + " " + prefix, - limit, new PGF.CompleteCallback() { - public void onResult(IterableJsArray completions) { - List magnets = new ArrayList(); - for (PGF.Completion completion : completions.iterable()) { - for (String word : completion.getCompletions()) { - if (updatePrefixes) { - addPrefix(text, word.substring(0,1)); - } - if (magnets.size() < maxMagnets) { - Magnet magnet = magnetFactory.createMagnet(word, completion.getFrom()); - magnets.add(magnet); - } else { - prefixPanel.setVisible(true); - } - } - } - bagPanel.fill(magnets); - } - public void onError(Throwable e) { - showError("Translation failed", e); - } - }); - } - - protected void clearPrefixes () { - prefixes.clear(); - prefixPanel.clear(); - prefixPanel.setVisible(false); - } - - protected void addPrefix(final String text, final String prefix) { - if (prefixes.add(prefix)) { - Button prefixButton = new Button(prefix, new ClickListener() { - public void onClick(Widget sender) { - updateBag(text, prefix); - } - }); - prefixButton.setTitle("Show only magnets stating with '" + prefix + "'"); - prefixPanel.add(prefixButton); - } - } - - // - // Translation - // - - protected void translate() { - outputPanel.clear(); - outputPanel.addStyleDependentName("working"); - if (translateRequest != null) { - translateRequest.cancel(); - } - translateRequest = pgf.translate(getText(), - new PGF.TranslateCallback() { - public void onResult (IterableJsArray translations) { - outputPanel.removeStyleDependentName("working"); - for (PGF.TranslationResult tr : translations.iterable()) { - if (tr.getTranslations() != null) - for (PGF.Linearizations t : tr.getTranslations().iterable()) { - for (PGF.Linearization l : t.getLinearizations().iterable()) { - outputPanel.add(createTranslation(l.getTo(), l.getText())); - } - } - - if (tr.getTypeErrors() != null) - for (PGF.TcError error : tr.getTypeErrors()) { - SimplePanel panel = new SimplePanel(); - panel.addStyleName("my-typeError"); - panel.add(new HTML("
    "+error.getMsg()+"
    ")); - outputPanel.add(panel); - } - } - } - public void onError (Throwable e) { - showError("Translation failed", e); - } - }); - } - - protected ClickListener translationClickListener = new ClickListener () { - public void onClick(Widget widget) { - Magnet magnet = (Magnet)widget; - setInputLanguage(magnet.getLanguage()); // FIXME: this causes an unnecessary update() - setText(magnet.getText(), magnet.getLanguage()); - } - }; - - protected Widget createTranslation(String language, String text) { - Magnet magnet = magnetFactory.createUsedMagnet(text, language); - magnet.addClickListener(translationClickListener); - String lang = pgf.getLanguageCode(language); - if (lang != null) { - magnet.getElement().setLang(lang); - } - return magnet; - } - - // - // Current text - // - - public String getText () { - return textPanel.getText(); - } - - public void setText(String text, String language) { - textPanel.setText(text, language); - } - - private void clear() { - textPanel.clear(); - } - - - // - // Status stuff - // - - protected void setStatus(String msg) { - statusPopup.setStatus(msg); - } - - protected void showError(String msg, Throwable e) { - statusPopup.showError(msg, e); - } - - protected void clearStatus() { - statusPopup.clearStatus(); - } - - // GUI - - protected Widget createUI() { - ClickListener magnetClickListener = new ClickListener () { - public void onClick(Widget widget) { - Magnet magnet = (Magnet)widget; - textPanel.addMagnet(magnet); - } - }; - magnetFactory = new MagnetFactory(magnetClickListener); - - textPanel = new FridgeTextPanel(magnetFactory); - textPanel.addChangeListener(new ChangeListener() { - public void onChange(Widget widget) { - update(); - } - }); - prefixPanel = new FlowPanel(); - prefixPanel.setStylePrimaryName("my-PrefixPanel"); - bagPanel = new FridgeBagPanel(); - outputPanel = new TranslationsPanel(); - SettingsPanel settingsPanel = new SettingsPanel(pgf, null, statusPopup); - - VerticalPanel vPanel = new VerticalPanel(); - vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER); - vPanel.setWidth("100%"); - vPanel.add(prefixPanel); - vPanel.add(bagPanel); - - final DockPanel mainPanel = new DockPanel(); - mainPanel.setStyleName("my-FridgeApp"); - mainPanel.add(textPanel, DockPanel.NORTH); - mainPanel.add(settingsPanel, DockPanel.SOUTH); - mainPanel.add(vPanel, DockPanel.CENTER); - mainPanel.add(outputPanel, DockPanel.EAST); - - mainPanel.setCellHeight(vPanel, "100%"); - mainPanel.setCellWidth(vPanel, "80%"); - mainPanel.setCellHeight(outputPanel, "100%"); - mainPanel.setCellWidth(outputPanel, "20%"); - mainPanel.setCellVerticalAlignment(vPanel, HasVerticalAlignment.ALIGN_TOP); - mainPanel.setCellHorizontalAlignment(outputPanel, HasHorizontalAlignment.ALIGN_RIGHT); - mainPanel.setCellWidth(settingsPanel, "100%"); - - Window.addWindowResizeListener(new WindowResizeListener() { - public void onWindowResized(int w, int h) { - mainPanel.setPixelSize(w, h); - } - }); - int w = Window.getClientWidth(); - int h = Window.getClientHeight(); - mainPanel.setPixelSize(w, h); - - return mainPanel; - } - - private static class TranslationsPanel extends VerticalPanel { - public TranslationsPanel () { - setStylePrimaryName("my-TranslationsPanel"); - addStyleDependentName("empty"); - } - - public void clear () { - super.clear(); - addStyleDependentName("empty"); - } - - public void add(Widget w) { - removeStyleDependentName("empty"); - super.add(w); - } - - } - - - // - // History stuff - // - - protected class MyHistoryListener implements HistoryListener { - public void onHistoryChanged(String historyToken) { - updateSettingsFromHistoryToken(); - } - }; - - protected void updateSettingsFromHistoryToken() { - updateSettingsFromHistoryToken(History.getToken().split("/")); - } - - protected void updateSettingsFromHistoryToken(String[] tokenParts) { - if (tokenParts.length >= 1 && tokenParts[0].length() > 0) { - setGrammarURL(tokenParts[0]); - } - if (tokenParts.length >= 2 && tokenParts[1].length() > 0) { - setInputLanguage(tokenParts[1]); - } - } - - protected void setGrammarURL(String url) { - if (url != null && !url.equals(pgf.getGrammarURL())) { - pgf.setGrammarURL(url); - } - } - - protected void setInputLanguage (String inputLanguage) { - if (inputLanguage != null && !inputLanguage.equals(pgf.getInputLanguage())) { - pgf.setInputLanguage(inputLanguage); - } - } - - // - // Initialization - // - - protected class MySettingsListener implements SettingsListener { - // Will only happen on load - public void onAvailableGrammarsChanged() { - if (pgf.getGrammarURL() == null) { - List grammars = pgf.getGrammars(); - if (!grammars.isEmpty()) { - pgf.setGrammarURL(grammars.get(0)); - } - } - } - public void onSelectedGrammarChanged() { - if (pgf.getInputLanguage() == null) { - pgf.setInputLanguage(pgf.getUserLanguage()); - } - } - public void onInputLanguageChanged() { - clear(); - } - public void onOutputLanguageChanged() { - update(); - } - public void onStartCategoryChanged() { - update(); - } - public void onSettingsError(String msg, Throwable e) { - showError(msg,e); - } - } - - public void onModuleLoad() { - statusPopup = new StatusPopup(); - - pgf = new PGFWrapper(); - RootPanel.get().add(createUI()); - pgf.addSettingsListener(new MySettingsListener()); - History.addHistoryListener(new MyHistoryListener()); - updateSettingsFromHistoryToken(); - pgf.updateAvailableGrammars(); - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeBagPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeBagPanel.java deleted file mode 100644 index bab14808e..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeBagPanel.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.core.client.GWT; -import com.google.gwt.user.client.ui.*; - -public class FridgeBagPanel extends Composite implements Iterable { - - private FlowPanel mainPanel; - - public FridgeBagPanel () { - mainPanel = new FlowPanel(); - - initWidget(new ScrollPanel(mainPanel)); - setStylePrimaryName("my-FridgeBagPanel"); - addStyleDependentName("empty"); - } - - public void clear() { - mainPanel.clear(); - } - - public void fill(List magnets) { - for (Magnet magnet : magnets) { - mainPanel.add(magnet); - } - - if (mainPanel.getWidgetCount() == 0) - addStyleDependentName("empty"); - else - removeStyleDependentName("empty"); - } - - public Iterator iterator() { - return (Iterator) (Iterator) mainPanel.iterator(); - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeTextPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeTextPanel.java deleted file mode 100644 index a44a72446..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/FridgeTextPanel.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.user.client.ui.*; - -public class FridgeTextPanel extends Composite { - - private MagnetFactory magnetFactory; - - private FlowPanel mainPanel; - - private ChangeListenerCollection listeners = null; - - public FridgeTextPanel (MagnetFactory magnetFactory) { - this.magnetFactory = magnetFactory; - mainPanel = new FlowPanel(); - mainPanel.setStylePrimaryName("magnets"); - DockPanel wrapper = new DockPanel(); - wrapper.add(mainPanel, DockPanel.CENTER); - Widget buttons = createButtonPanel(); - wrapper.add(buttons, DockPanel.EAST); - wrapper.setCellWidth(mainPanel, "100%"); - wrapper.setCellWidth(buttons, "6em"); - wrapper.setHorizontalAlignment(DockPanel.ALIGN_RIGHT); - initWidget(wrapper); - setStylePrimaryName("my-FridgeTextPanel"); - } - - - protected Widget createButtonPanel () { - Panel buttons = new VerticalPanel(); - buttons.setStylePrimaryName("buttons"); - PushButton deleteLastButton = new PushButton(new Image("org.grammaticalframework.ui.gwt.FridgeApp/delete-last.png")); - deleteLastButton.setTitle("Removes the last magnet."); - deleteLastButton.addClickListener(new ClickListener () { - public void onClick(Widget sender) { - deleteLast(); - } - }); - buttons.add(deleteLastButton); - PushButton clearButton = new PushButton("Clear"); - clearButton.addClickListener(new ClickListener () { - public void onClick(Widget sender) { - clear(); - } - }); - clearButton.setTitle("Removes all magnets."); - buttons.add(clearButton); - return buttons; - } - - public void setEngaged(boolean engaged) { - if (engaged) { - addStyleDependentName("engage"); - } else { - removeStyleDependentName("engage"); - } - } - - public String getText () { - StringBuilder sb = new StringBuilder(); - for (Widget w : mainPanel) { - if (w instanceof Magnet) { - String word = ((Magnet)w).getText(); - if (sb.length() > 0) { - sb.append(' '); - } - sb.append(word); - } - } - return sb.toString(); - } - - public void setText (String text, String language) { - if (!text.equals(getText())) { - mainPanel.clear(); - for (String word : text.split("\\s+")) { - if (word.length() > 0) { - mainPanel.add(magnetFactory.createUsedMagnet(word, language)); - } - } - fireChange(); - } - } - - public void clear () { - mainPanel.clear(); - fireChange(); - } - - public void addMagnet (Magnet magnet) { - mainPanel.add(magnetFactory.createUsedMagnet(magnet)); - fireChange(); - } - - public void deleteLast() { - int c = mainPanel.getWidgetCount(); - if (c > 0) { - mainPanel.remove(c-1); - fireChange(); - } - } - - protected void fireChange() { - listeners.fireChange(this); - } - - public void addChangeListener(ChangeListener listener) { - if (listeners == null) { - listeners = new ChangeListenerCollection(); - } - listeners.add(listener); - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/GrammarsPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/GrammarsPanel.java deleted file mode 100644 index 0857c3c4e..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/GrammarsPanel.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; -import com.google.gwt.user.client.*; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.http.client.*; -import com.google.gwt.xml.client.*; -import com.google.gwt.event.logical.shared.*; -import com.google.gwt.event.dom.client.*; -import com.google.gwt.event.shared.*; - -public class GrammarsPanel extends Composite { - - private PGFWrapper pgf; - private ContentService contentService; - private StatusPopup statusPopup; - - private VerticalPanel grammarsPanel; - private FormPanel form = null; - - public GrammarsPanel(PGFWrapper pgf, ContentService contentService, StatusPopup statusPopup) { - this.pgf = pgf; - this.contentService = contentService; - this.statusPopup = statusPopup; - - VerticalPanel vpanel = new VerticalPanel(); - - Button btnNew = new Button("New Grammar"); - btnNew.addClickListener(new ClickListener() { - public void onClick(Widget sender) { - if (form == null) { - grammarsPanel.insert(new GrammarInfoPanel(null),0); - } - } - }); - vpanel.add(btnNew); - - grammarsPanel = new VerticalPanel(); - grammarsPanel.setWidth("100%"); - vpanel.add(grammarsPanel); - - initWidget(vpanel); - setStylePrimaryName("my-GrammarsPanel"); - - contentService.addSettingsListener(new MySettingsListener()); - } - - private class GrammarInfoPanel extends Composite { - public GrammarInfoPanel(final ContentService.GrammarInfo grammar) { - final VerticalPanel vpanel = new VerticalPanel(); - - if (grammar != null) { - FlexTable header = new FlexTable(); - header.setStylePrimaryName("my-TableHeader"); - header.setText(0,0,grammar.getName()); - vpanel.add(header); - - final Image updateButton = new Image("org.grammaticalframework.ui.gwt.EditorApp/grammar-buttons.png",0,0,20,20); - updateButton.setTitle("Edit the grammar definition."); - updateButton.setStylePrimaryName("toolbar-button"); - header.setWidget(0,1,updateButton); - header.getColumnFormatter().setWidth(1,"20px"); - - final Image deleteButton = new Image("org.grammaticalframework.ui.gwt.EditorApp/grammar-buttons.png",20,0,20,20); - deleteButton.setTitle("Delete this grammar."); - deleteButton.setStylePrimaryName("toolbar-button"); - header.setWidget(0,2,deleteButton); - header.getColumnFormatter().setWidth(2,"20px"); - - final Label descr = new Label(grammar.getDescription()); - descr.setStylePrimaryName("descr-label"); - vpanel.add(descr); - - updateButton.addClickListener(new ClickListener () { - public void onClick(Widget sender) { - if (form == null) { - vpanel.remove(descr); - vpanel.add(form = createUploadForm(grammar)); - } - } - }); - - deleteButton.addClickListener(new ClickListener () { - public void onClick(Widget sender) { - contentService.deleteGrammar(grammar.getURL(), new ContentService.DeleteCallback() { - public void onResult(ContentService.DeleteResult result) { - contentService.updateAvailableGrammars(); - } - - public void onError(Throwable e) { - statusPopup.showError("Delete failed", e); - } - }); - } - }); - } else { - FlexTable header = new FlexTable(); - header.setStylePrimaryName("my-TableHeader"); - header.setText(0,0,"Add New Grammar"); - vpanel.add(header); - vpanel.add(form = createUploadForm(grammar)); - } - - initWidget(vpanel); - setStylePrimaryName("my-GrammarInfoPanel"); - } - - public FormPanel createUploadForm(final ContentService.GrammarInfo grammar) { - UploadFormHandler uploadFormHandler = new UploadFormHandler(); - - final FormPanel form = new FormPanel(); - form.setWidth("100%"); - form.setEncoding(FormPanel.ENCODING_MULTIPART); - form.setMethod(FormPanel.METHOD_POST); - form.setAction(ContentService.getInit().getContentURL()); - form.addSubmitHandler(uploadFormHandler); - form.addSubmitCompleteHandler(uploadFormHandler); - - VerticalPanel vPanel = new VerticalPanel(); - vPanel.setWidth("100%"); - form.add(vPanel); - - vPanel.add(new HTML("\n"+ - "")); - - HorizontalPanel hPanel = new HorizontalPanel(); - hPanel.setSpacing(8); - hPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); - vPanel.add(hPanel); - - final FileUpload fileUpload = new FileUpload(); - fileUpload.setName("file"); - hPanel.add(fileUpload); - - hPanel.add(new HTML(" ")); - - hPanel.add(new Label("Name:")); - final TextBox grammarName = new TextBox(); - grammarName.setName("name"); - grammarName.setWidth("300px"); - hPanel.add(grammarName); - - hPanel.add(new HTML(" ")); - - hPanel.add(new Button("Upload", new ClickListener() { - public void onClick(Widget sender) { - if (grammar == null && - fileUpload.getFilename().equals("")) - statusPopup.showError("You must select a file to upload", null); - else - form.submit(); - } - })); - hPanel.add(new Button("Cancel", new ClickListener() { - public void onClick(Widget sender) { - contentService.updateAvailableGrammars(); - } - })); - - vPanel.add(new Label("Description:")); - TextArea grammarDescr = new TextArea(); - grammarDescr.setName("description"); - grammarDescr.setWidth("100%"); - grammarDescr.setHeight("50px"); - vPanel.add(grammarDescr); - - if (grammar != null) { - grammarName.setText(grammar.getName()); - grammarDescr.setText(grammar.getDescription()); - - vPanel.add(new HTML("")); - } - - return form; - } - - private class UploadFormHandler implements FormPanel.SubmitHandler, FormPanel.SubmitCompleteHandler { - public void onSubmit(FormPanel.SubmitEvent event) { - } - - public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) { - contentService.updateAvailableGrammars(); - } - } - } - - private class MySettingsListener implements SettingsListener { - public void onAvailableGrammarsChanged() { - form = null; - grammarsPanel.clear(); - for (ContentService.GrammarInfo grammar : contentService.getGrammars()) { - grammarsPanel.add(new GrammarInfoPanel(grammar)); - } - } - public void onSelectedGrammarChanged() { } - public void onInputLanguageChanged() { } - public void onOutputLanguageChanged() { } - public void onStartCategoryChanged() { } - public void onSettingsError(String msg, Throwable e) { } - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/IterableJsArray.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/IterableJsArray.java deleted file mode 100644 index b1d501ddb..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/IterableJsArray.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import com.google.gwt.core.client.JavaScriptObject; -import com.google.gwt.core.client.JsArray; - -public class IterableJsArray extends JsArray { - - protected IterableJsArray() {} - - public final boolean isEmpty() { - return length() == 0; - } - - public final Iterable iterable() { - return new Iterable() { - public Iterator iterator() { - return new Iterator() { - private int i = 0; - public boolean hasNext() { - return i < length(); - } - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return get(i++); - } - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - }; - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONCallback.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONCallback.java deleted file mode 100644 index 485173b49..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONCallback.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.core.client.JavaScriptObject; - -public interface JSONCallback { - public void onResult (T result) ; - public void onError (Throwable e) ; -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONRequest.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONRequest.java deleted file mode 100644 index 15da7caf0..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONRequest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.http.client.*; - -public class JSONRequest { - - private Request httpRequest; - - JSONRequest (Request httpRequest) { - this.httpRequest = httpRequest; - } - - public void cancel() { - if (httpRequest != null) { - httpRequest.cancel(); - } - } - -} \ No newline at end of file diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONRequestBuilder.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONRequestBuilder.java deleted file mode 100644 index e2e83dc6f..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/JSONRequestBuilder.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.core.client.JavaScriptObject; -import com.google.gwt.http.client.Request; -import com.google.gwt.http.client.RequestBuilder; -import com.google.gwt.http.client.RequestCallback; -import com.google.gwt.http.client.RequestException; -import com.google.gwt.http.client.Response; -import com.google.gwt.http.client.URL; - -import java.util.List; - -public class JSONRequestBuilder { - - public static class Arg { - public final String name; - public final String value; - public Arg (String name, String value) { - this.name = name; - this.value = value; - } - public Arg (String name, int value) { - this(name, Integer.toString(value)); - } - } - - public static JSONRequest sendRequest (String base, List vars, final JSONCallback callback) { - String url = getQueryURL(base,vars); - RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); - builder.setTimeoutMillis(30000); - builder.setHeader("Accept","text/plain, text/html;q=0.5, */*;q=0.1"); - Request request = null; - - try { - request = builder.sendRequest(null, new RequestCallback() { - public void onError(Request request, Throwable e) { - callback.onError(e); - } - - public void onResponseReceived(Request request, Response response) { - if (200 == response.getStatusCode()) { - callback.onResult(JSONRequestBuilder.eval(response.getText())); - } else { - RequestException e = new RequestException("Response not OK: " + response.getStatusCode() + ". " + response.getText()); - callback.onError(e); - } - } - }); - } catch (RequestException e) { - callback.onError(e); - } - - return new JSONRequest(request); - } - - public static JSONRequest sendDataRequest (String base, List vars, String content, final JSONCallback callback) { - String url = getQueryURL(base,vars); - RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url); - builder.setTimeoutMillis(30000); - builder.setHeader("Content-Length", Integer.toString(content.length())); - builder.setHeader("Accept","text/plain, text/html;q=0.5, */*;q=0.1"); - Request request = null; - - try { - request = builder.sendRequest(content, new RequestCallback() { - public void onError(Request request, Throwable e) { - callback.onError(e); - } - - public void onResponseReceived(Request request, Response response) { - if (200 == response.getStatusCode()) { - callback.onResult(JSONRequestBuilder.eval(response.getText())); - } else { - RequestException e = new RequestException("Response not OK: " + response.getStatusCode() + ". " + response.getText()); - callback.onError(e); - } - } - }); - } catch (RequestException e) { - callback.onError(e); - } - - return new JSONRequest(request); - } - - private static native T eval(String json) /*-{ - return eval('(' + json + ')'); - }-*/; - - public static String getQueryURL(String base, List args) { - StringBuffer sb = new StringBuffer(); - sb.append(base); - sb.append("?"); - if (args != null) { - for (Arg arg : args) { - if (arg.value != null) { - if (sb.length() > 0) { - sb.append("&"); - } - sb.append(URL.encodeComponent(arg.name)); - sb.append("="); - sb.append(URL.encodeComponent(arg.value)); - } - } - } - return sb.toString(); - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/LinearizationsPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/LinearizationsPanel.java deleted file mode 100644 index 04aa5d5d7..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/LinearizationsPanel.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.core.client.*; -import com.google.gwt.user.client.*; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.event.dom.client.*; -import com.google.gwt.event.logical.shared.*; -import com.google.gwt.event.shared.*; - -public class LinearizationsPanel extends Composite { - - protected PGFWrapper pgf; - - public LinearizationsPanel(PGFWrapper pgf, PGF.Linearizations lins) { - this.pgf = pgf; - - HorizontalPanel hPanel = new HorizontalPanel(); - VerticalPanel linsPanel = new VerticalPanel(); - linsPanel.addStyleName("my-translation-bar"); - hPanel.add(linsPanel); - HorizontalPanel btnPanel = new HorizontalPanel(); - btnPanel.addStyleName("my-translation-btns"); - btnPanel.setSpacing(4); - btnPanel.add(createAbsTreeButton(lins.getTree())); - btnPanel.add(createAlignButton(lins.getTree())); - hPanel.add(btnPanel); - hPanel.setCellHorizontalAlignment(btnPanel,HasHorizontalAlignment.ALIGN_RIGHT); - - for (PGF.Linearization l : lins.getLinearizations().iterable()) { - linsPanel.add(createTranslation(l.getTo(), lins.getTree(), l.getText())); - } - - initWidget(hPanel); - setStylePrimaryName("my-translation-frame"); - } - - protected Widget createAbsTreeButton(final String abstractTree) { - Image treeBtn = new Image("org.grammaticalframework.ui.gwt.EditorApp/tree-btn.png"); - treeBtn.setTitle("Displays the abstract syntax tree."); - treeBtn.addClickListener( - new ClickListener() { - public void onClick(Widget sender) { - // Create a dialog box and set the caption text - final DialogBox dialogBox = new DialogBox(); - dialogBox.setText("Abstract Syntax Tree"); - - // Create a table to layout the content - HorizontalPanel dialogContents = new HorizontalPanel(); - dialogContents.setSpacing(4); - dialogBox.setWidget(dialogContents); - - // Add an image to the dialog - - Frame image = new Frame(pgf.graphvizAbstractTree(abstractTree)); - image.addStyleName("my-treeimage"); - dialogContents.add(image); - - // Add a close button at the bottom of the dialog - Button closeButton = new Button("Close", - new ClickListener() { - public void onClick(Widget sender) { - dialogBox.hide(); - } - }); - dialogContents.add(closeButton); - - dialogBox.center(); - dialogBox.show(); - } - }); - return treeBtn; - } - - protected Widget createAlignButton(final String abstractTree) { - Image alignBtn = new Image("org.grammaticalframework.ui.gwt.EditorApp/align-btn.png"); - alignBtn.setTitle("Displays word-alignment diagram."); - alignBtn.addClickListener( - new ClickListener() { - public void onClick(Widget sender) { - // Create a dialog box and set the caption text - final DialogBox dialogBox = new DialogBox(); - dialogBox.setText("Word Alignment"); - - // Create a table to layout the content - HorizontalPanel dialogContents = new HorizontalPanel(); - dialogContents.setSpacing(4); - dialogBox.setWidget(dialogContents); - - // Add an image to the dialog - Frame image = new Frame(pgf.graphvizAlignment(abstractTree)); - image.addStyleName("my-alignmentimage"); - dialogContents.add(image); - - // Add a close button at the bottom of the dialog - Button closeButton = new Button("Close", - new ClickListener() { - public void onClick(Widget sender) { - dialogBox.hide(); - } - }); - dialogContents.add(closeButton); - - dialogBox.center(); - dialogBox.show(); - } - }); - return alignBtn; - } - - protected Widget createTranslation(final String language, final String abstractTree, String text) { - Label l = new Label(text); - l.addStyleName("my-translation"); - String lang = pgf.getLanguageCode(language); - if (lang != null) { - l.getElement().setLang(lang); - } - l.addClickListener(new ClickListener() { - public void onClick(Widget sender) { - // Create a dialog box and set the caption text - final DialogBox dialogBox = new DialogBox(); - dialogBox.setText("Parse Tree"); - - // Create a table to layout the content - HorizontalPanel dialogContents = new HorizontalPanel(); - dialogContents.setSpacing(4); - dialogBox.setWidget(dialogContents); - - // Add an image to the dialog - Frame image = new Frame(pgf.graphvizParseTree(abstractTree, language)); - image.addStyleName("my-treeimage"); - dialogContents.add(image); - - // Add a close button at the bottom of the dialog - Button closeButton = new Button("Close", - new ClickListener() { - public void onClick(Widget sender) { - dialogBox.hide(); - } - }); - dialogContents.add(closeButton); - - dialogBox.center(); - dialogBox.show(); - } - }); - return l; - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/Magnet.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/Magnet.java deleted file mode 100644 index ded8a171a..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/Magnet.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.user.client.ui.HTML; - -public class Magnet extends HTML { - - private String language; - - public Magnet (String text, String language) { - this.language = language; - setHTML(text); - setStylePrimaryName("my-Magnet"); - } - - public String getLanguage() { - return language; - } - - public String getWord() { - return getHTML(); - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MagnetFactory.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MagnetFactory.java deleted file mode 100644 index 5bb780456..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MagnetFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.user.client.ui.*; - -public class MagnetFactory { - - private ClickListener clickListener; - - public MagnetFactory (ClickListener clickListener) { - this.clickListener = clickListener; - } - - public Magnet createUsedMagnet(Magnet magnet) { - return createUsedMagnet(magnet.getText(), magnet.getLanguage()); - } - - public Magnet createUsedMagnet(String text, String language) { - return new Magnet(text, language); - } - - public Magnet createMagnet(Magnet magnet) { - return createMagnet(magnet.getText(), magnet.getLanguage()); - } - - public Magnet createMagnet(String text, String language) { - Magnet magnet = new Magnet(text, language); - magnet.addClickListener(clickListener); - return magnet; - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MagnetSearchBox.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MagnetSearchBox.java deleted file mode 100644 index 5a2a70401..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MagnetSearchBox.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.core.client.*; -import com.google.gwt.user.client.*; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.event.dom.client.*; -import com.google.gwt.event.logical.shared.*; -import com.google.gwt.event.shared.*; -import com.google.gwt.dom.client.Node; -import com.google.gwt.dom.client.Text; -import com.google.gwt.dom.client.Element; -import com.google.gwt.dom.client.Document; -import org.grammaticalframework.ui.gwt.client.selection.*; - -public class MagnetSearchBox extends FocusWidget { - public MagnetSearchBox() { - this(Document.get().createDivElement()); - } - - public MagnetSearchBox(Element elem) { - super(elem); - elem.setAttribute("contentEditable", "true"); - setStyleName("searchbox"); - } - - public String getText() { - return getElement().getInnerText(); - } - - public void setText(String s) { - getElement().setInnerText(s); - } - - public int getCursorPos() { - return 0; - } - - public void setCursorPos(int pos) { - Node child = getElement().getFirstChild(); - if (child instanceof Text) { - SelectionEndPoint selPoint = new SelectionEndPoint((Text) child,pos); - Selection sel = Selection.getSelection(); - sel.select(selPoint,selPoint); - } - return; - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MorphoApp.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MorphoApp.java deleted file mode 100644 index 44e7bacb6..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MorphoApp.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.core.client.*; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.core.client.JavaScriptObject; - -public class MorphoApp implements EntryPoint { - private TextBox lemmaBox = new TextBox(); - private Button submitButton = new Button("Submit"); - private Grid outputGrid = new Grid(2,0); - - public void onModuleLoad() { - HorizontalPanel inputPanel = new HorizontalPanel(); - inputPanel.add(lemmaBox); - inputPanel.add(submitButton); - - submitButton.addClickListener(new ClickListener() { - public void onClick(Widget sender) { - - String url = "http://localhost:41296/morpho/morpho.fcgi/eval"; - List args = new ArrayList(); - args.add(new JSONRequestBuilder.Arg("term", lemmaBox.getText())); - - JSONRequestBuilder.sendRequest(url, args, new TableCallback() { - public void onResult (IterableJsArray table) - { - outputGrid.resize(table.length(),2); - int row = 0; - for (InflectionForm form : table.iterable()) { - outputGrid.setText(row,0,form.getName()); - outputGrid.setText(row,1,form.getValue()); - row++; - } - } - - public void onError (Throwable e) - { - outputGrid.resize(1,1); - outputGrid.setText(0,0,e.toString()); - } - }); - } - }); - - - VerticalPanel mainPanel = new VerticalPanel(); - mainPanel.add(inputPanel); - mainPanel.add(outputGrid); - RootPanel.get().add(mainPanel); - } - - public interface TableCallback extends JSONCallback> { } - - public static class InflectionForm extends JavaScriptObject { - protected InflectionForm() { } - - public final native String getName() /*-{ return this.name; }-*/; - - public final native String getValue() /*-{ return this.value; }-*/; - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MyListBox.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MyListBox.java deleted file mode 100644 index ce716b91d..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/MyListBox.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.Collection; - -import com.google.gwt.user.client.ui.ListBox; - -public class MyListBox extends ListBox { - - public MyListBox () { } - - public void clearSelection () { - setSelectedIndex(-1); - } - - public String getSelectedValue() { - int i = getSelectedIndex(); - return i == -1 ? null : getValue(i); - } - - public void setSelectedValue(String value) { - if (value == null) { - clearSelection(); - } else { - int c = getItemCount(); - for (int i = 0; i < c; i++) { - if (getValue(i).equals(value)) { - setSelectedIndex(i); - return; - } - } - } - } - - public void addItems(Collection items) { - for (String item : items) { - addItem(item); - } - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/PGF.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/PGF.java deleted file mode 100644 index 17eef12bb..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/PGF.java +++ /dev/null @@ -1,241 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import org.grammaticalframework.ui.gwt.client.JSONRequestBuilder.Arg; - -import java.util.*; -import com.google.gwt.core.client.*; -import com.google.gwt.http.client.*; - -public class PGF { - - public PGF () { - } - - /* Grammar */ - - public JSONRequest grammar (String pgfURL, final GrammarCallback callback) { - return sendGrammarRequest(pgfURL, "grammar", new ArrayList(), callback); - } - - public interface GrammarCallback extends JSONCallback { } - - public static class Grammar extends JavaScriptObject { - protected Grammar() { } - - public final native String getName() /*-{ return this.name; }-*/; - - public final native String getUserLanguage() /*-{ return this.userLanguage; }-*/; - - public final native IterableJsArray getLanguages() /*-{ return this.languages; }-*/; - - public final native JsArrayString getCategories() /*-{ return this.categories; }-*/; - - public final native JsArrayString getFunctions() /*-{ return this.functions; }-*/; - } - - public static class Language extends JavaScriptObject { - protected Language() { } - - public final native String getName() /*-{ return this.name; }-*/; - public final native String getLanguageCode() /*-{ return this.languageCode; }-*/; - } - - /* Translation */ - - public JSONRequest translate (String pgfURL, String input, String fromLang, String cat, String toLang, - final TranslateCallback callback) { - List args = new ArrayList(); - args.add(new Arg("input", input)); - args.add(new Arg("from", fromLang)); - args.add(new Arg("cat", cat)); - args.add(new Arg("to", toLang)); - return sendGrammarRequest(pgfURL, "translate", args, callback); - } - - public interface TranslateCallback extends JSONCallback> { } - - public static class TranslationResult extends JavaScriptObject { - protected TranslationResult() { } - - public final native String getFrom() /*-{ return this.from; }-*/; - public final native BracketedString getBracketedString() /*-{ return this.brackets; }-*/; - public final native IterableJsArray getTranslations() /*-{ return this.translations; }-*/; - public final native TcError[] getTypeErrors() /*-{ return this.typeErrors; }-*/; - } - - public static class Linearizations extends JavaScriptObject { - protected Linearizations() { } - - public final native String getTree() /*-{ return this.tree; }-*/; - public final native IterableJsArray getLinearizations() /*-{ return this.linearizations; }-*/; - } - - /* Completion */ - - /** - * Get suggestions for completing the input. - * @param limit The number of suggestions to get. - * If -1 is passed, all available suggestions are retrieved. - */ - public JSONRequest complete (String pgfURL, String input, String fromLang, String cat, int limit, final CompleteCallback callback) { - List args = new ArrayList(); - args.add(new Arg("input", input)); - args.add(new Arg("from", fromLang)); - args.add(new Arg("cat", cat)); - if (limit > 0) { - args.add(new Arg("limit", limit)); - } - return sendGrammarRequest(pgfURL, "complete", args, callback); - } - - public interface CompleteCallback extends JSONCallback> { } - - public static class Completion extends JavaScriptObject { - protected Completion() { } - - public final native String getFrom() /*-{ return this.from; }-*/; - public final native BracketedString getBracketedString() /*-{ return this.brackets; }-*/; - public final native String[] getCompletions() /*-{ return this.completions; }-*/; - public final native String getText() /*-{ return this.text; }-*/; - } - - /* Parsing */ - - public JSONRequest parse (String pgfURL, String input, String fromLang, String cat, final ParseCallback callback) { - List args = new ArrayList(); - args.add(new Arg("input", input)); - args.add(new Arg("from", fromLang)); - args.add(new Arg("cat", cat)); - return sendGrammarRequest(pgfURL, "parse", args, callback); - } - - public interface ParseCallback extends JSONCallback> { } - - public static class ParseResult extends JavaScriptObject { - protected ParseResult() { } - - public final native String getFrom() /*-{ return this.from; }-*/; - public final native BracketedString getBracketedString() /*-{ return this.brackets; }-*/; - public final native String[] getTrees() /*-{ return this.trees; }-*/; - public final native TcError[] getTypeErrors() /*-{ return this.typeErrors; }-*/; - } - - public static class BracketedString extends JavaScriptObject { - protected BracketedString() { } - - public final native String getToken() /*-{ return this.token; }-*/; - - public final native String getCat() /*-{ return this.cat; }-*/; - public final native int getFId() /*-{ return this.fid; }-*/; - public final native int getIndex() /*-{ return this.index; }-*/; - public final native BracketedString[] getChildren() /*-{ return this.children; }-*/; - - public final String render() { - if (getToken() != null) - return getToken(); - else { - StringBuilder sbuilder = new StringBuilder(); - for (BracketedString bs : getChildren()) { - if (sbuilder.length() > 0) - sbuilder.append(' '); - sbuilder.append(bs.render()); - } - return sbuilder.toString(); - } - } - } - - public static class TcError extends JavaScriptObject { - protected TcError() { } - - public final native int getFId() /*-{ return this.fid; }-*/; - public final native String getMsg() /*-{ return this.msg; }-*/; - } - - - /* Linearization */ - - public JSONRequest linearize (String pgfURL, String tree, String toLang, final LinearizeCallback callback) { - List args = new ArrayList(); - args.add(new Arg("tree", tree)); - args.add(new Arg("to", toLang)); - return sendGrammarRequest(pgfURL, "linearize", args, callback); - } - - public interface LinearizeCallback extends JSONCallback> { } - - public static class Linearization extends JavaScriptObject { - protected Linearization() { } - - public final native String getTo() /*-{ return this.to; }-*/; - public final native String getText() /*-{ return this.text; }-*/; - } - - public String graphvizAbstractTree(String pgfURL, String abstractTree) { - List args = new ArrayList(); - args.add(new Arg("command", "abstrtree")); - args.add(new Arg("tree", abstractTree)); - return JSONRequestBuilder.getQueryURL(pgfURL,args); - } - - public String graphvizParseTree(String pgfURL, String abstractTree, String lang) { - List args = new ArrayList(); - args.add(new Arg("command", "parsetree")); - args.add(new Arg("tree", abstractTree)); - args.add(new Arg("from", lang)); - return JSONRequestBuilder.getQueryURL(pgfURL,args); - } - - public String graphvizAlignment(String pgfURL, String abstractTree) { - List args = new ArrayList(); - args.add(new Arg("command", "alignment")); - args.add(new Arg("tree", abstractTree)); - return JSONRequestBuilder.getQueryURL(pgfURL,args); - } - - public Request browse(String pgfURL, String id, String href, String cssClass, RequestCallback callback) { - List args = new ArrayList(); - args.add(new Arg("command", "browse")); - args.add(new Arg("id", id)); - args.add(new Arg("href", href)); - args.add(new Arg("css-class", cssClass)); - - Request request = null; - try { - RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, - JSONRequestBuilder.getQueryURL(pgfURL,args)); - builder.setCallback(callback); - request = builder.send(); - } catch (RequestException ex) { - callback.onError(request, ex); - } - - return request; - } - - public JSONRequest generateAll(String pgfURL, String cat, int depth, int limit, String toLang, GenerationCallback callback) { - List args = new ArrayList(); - args.add(new Arg("cat", cat)); - args.add(new Arg("depth", depth)); - args.add(new Arg("limit", limit)); - args.add(new Arg("to", toLang)); - return sendGrammarRequest(pgfURL, "generate", args, callback); - } - - public JSONRequest generateRandom(String pgfURL, String cat, int depth, int limit, String toLang, GenerationCallback callback) { - List args = new ArrayList(); - args.add(new Arg("cat", cat)); - args.add(new Arg("depth", depth)); - args.add(new Arg("limit", limit)); - args.add(new Arg("to", toLang)); - return sendGrammarRequest(pgfURL, "random", args, callback); - } - - public interface GenerationCallback extends JSONCallback> {} - - public JSONRequest sendGrammarRequest(String pgfURL, String resource, List args, final JSONCallback callback) { - args.add(new Arg("command", resource)); - return JSONRequestBuilder.sendRequest(pgfURL, args, callback); - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/PGFWrapper.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/PGFWrapper.java deleted file mode 100644 index 1e248fa40..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/PGFWrapper.java +++ /dev/null @@ -1,294 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import com.google.gwt.http.client.*; -import com.google.gwt.xml.client.*; -import com.google.gwt.core.client.*; - -public class PGFWrapper { - - private String grammarURL = null; - - private PGF pgf; - - private String inputLanguage = null; - - private String outputLanguage = null; - - private String cat = null; - - // Cached info about the available grammars - - private List grammars; - - // Cached info about the currently selected grammar - - private String userLanguage; - - private LinkedHashMap languages; - - private JsArrayString categories; - private JsArrayString functions; - - // Event listeners - - private List listeners = new LinkedList(); - - - public PGFWrapper() { - this.pgf = new PGF(); - } - - public void updateAvailableGrammars() { - String url = "/grammars.xml"; - RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); - try - { - builder.sendRequest(null, new RequestCallback() { - public void onResponseReceived(Request request, Response response) - { - if (200 == response.getStatusCode()) - { - grammars = new ArrayList(); - try - { - Document grammarsDoc = XMLParser.parse(response.getText()); - - NodeList grammarsList = grammarsDoc.getElementsByTagName("grammar"); - for (int i = 0; i < grammarsList.getLength(); i++) - { - Node grammarNode = grammarsList.item(i); - grammars.add(((Element)grammarNode).getAttribute("name")); - } - } - catch (DOMException e) - { - fireSettingsError("Could not parse XML document.", e); - } - fireAvailableGrammarsChanged(); - } - else - { - fireSettingsError("Error getting grammar list", null); - } - } - - public void onError(Request request, Throwable e) - { - fireSettingsError("Error getting grammar list", e); - } - }); - } - catch (RequestException e) - { - fireSettingsError("Couldn't connect to server", e); - } - } - - protected void updateSelectedGrammar () { - if (grammarURL == null) - return; - - clearCachedInfo(); - pgf.grammar(grammarURL, new PGF.GrammarCallback() { - public void onResult(PGF.Grammar grammar) { - userLanguage = grammar.getUserLanguage(); - languages = new LinkedHashMap(); - for (PGF.Language l : grammar.getLanguages().iterable()) { - String name = l.getName(); - languages.put(name, l); - } - - categories = grammar.getCategories(); - functions = grammar.getFunctions(); - - fireSelectedGrammarChanged(); - } - - public void onError (Throwable e) { - fireSettingsError("Error getting language information", e); - } - }); - } - - // - // PGF functionality - // - - public JSONRequest translate (String input, final PGF.TranslateCallback callback) { - return pgf.translate(grammarURL, input, inputLanguage, cat, outputLanguage, callback); - } - - public JSONRequest complete (String input, int limit, final PGF.CompleteCallback callback) { - return pgf.complete(grammarURL, input, inputLanguage, cat, limit, callback); - } - - public JSONRequest parse (String input, final PGF.ParseCallback callback) { - return pgf.parse(grammarURL, input, inputLanguage, cat, callback); - } - - public JSONRequest linearize (String tree, final PGF.LinearizeCallback callback) { - return pgf.linearize(grammarURL, tree, outputLanguage, callback); - } - - public String graphvizAbstractTree(String abstractTree) { - return pgf.graphvizAbstractTree(grammarURL,abstractTree); - } - - public String graphvizParseTree(String abstractTree, String lang) { - return pgf.graphvizParseTree(grammarURL,abstractTree,lang); - } - - public String graphvizAlignment(String abstractTree) { - return pgf.graphvizAlignment(grammarURL,abstractTree); - } - - public Request browse(String id, String href, String cssClass, RequestCallback callback) { - return pgf.browse(grammarURL, id, href, cssClass, callback); - } - - public JSONRequest generateAll(String cat, int depth, int limit, PGF.GenerationCallback callback) { - return pgf.generateAll(grammarURL, cat, depth, limit, outputLanguage, callback); - } - - public JSONRequest generateRandom(String cat, int depth, int limit, PGF.GenerationCallback callback) { - return pgf.generateRandom(grammarURL, cat, depth, limit, outputLanguage, callback); - } - - // - // Settings - // - - public String getGrammarURL() { - return grammarURL; - } - - public void setGrammarURL(String grammarURL) { - this.grammarURL = grammarURL; - this.inputLanguage = null; - this.outputLanguage = null; - this.cat = null; - updateSelectedGrammar(); - } - - public String getInputLanguage() { - return inputLanguage; - } - - public void setInputLanguage(String inputLanguage) { - this.inputLanguage = inputLanguage; - fireInputLanguageChanged(); - } - - public String getOutputLanguage() { - return outputLanguage; - } - - public void setOutputLanguage(String outputLanguage) { - this.outputLanguage = outputLanguage; - fireOutputLanguageChanged(); - } - - public String getStartCategory() { - return cat; - } - - public void setStartCategory(String cat) { - this.cat = cat; - fireStartCategoryChanged(); - } - - public JsArrayString getCategories() { - return categories; - } - - public JsArrayString getFunctions() { - return functions; - } - - - // - // Information about the available grammars - // - public List getGrammars() { - return grammars; - } - - // - // Information about the selected grammar - // - private void clearCachedInfo () { - languages = null; - } - - public String getUserLanguage () { - return userLanguage; - } - - public String getLanguageCode (String language) { - PGF.Language l = languages.get(language); - return l == null ? null : l.getLanguageCode(); - } - - public Collection getAllLanguages() { - return languages.keySet(); - } - - // - // Listeners - // - - public static class SettingsAdapter implements SettingsListener { - public void onAvailableGrammarsChanged() {} - public void onSelectedGrammarChanged() {} - public void onInputLanguageChanged() {} - public void onOutputLanguageChanged() {} - public void onStartCategoryChanged() {} - public void onSettingsError(String msg, Throwable e) {} - } - - public void addSettingsListener(SettingsListener listener) { - listeners.add(listener); - } - - protected void fireAvailableGrammarsChanged() { - for (SettingsListener listener : listeners) { - listener.onAvailableGrammarsChanged(); - } - } - - protected void fireSelectedGrammarChanged() { - for (SettingsListener listener : listeners) { - listener.onSelectedGrammarChanged(); - } - } - - protected void fireInputLanguageChanged() { - for (SettingsListener listener : listeners) { - listener.onInputLanguageChanged(); - } - } - - protected void fireOutputLanguageChanged() { - for (SettingsListener listener : listeners) { - listener.onOutputLanguageChanged(); - } - } - - protected void fireStartCategoryChanged() { - for (SettingsListener listener : listeners) { - listener.onStartCategoryChanged(); - } - } - - protected void fireSettingsError(String msg, Throwable e) { - for (SettingsListener listener : listeners) { - listener.onSettingsError(msg, e); - } - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/QueryPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/QueryPanel.java deleted file mode 100644 index b364ed0b6..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/QueryPanel.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.http.client.*; -import com.google.gwt.user.client.ui.*; - -public class QueryPanel extends Composite { - - private PGFWrapper pgf; - private StatusPopup statusPopup; - private TextArea queryBox; - private VerticalPanel outputPanel; - private JSONRequest executeRequest = null; - - public QueryPanel(PGFWrapper pgf, StatusPopup statusPopup) { - this.pgf = pgf; - this.statusPopup = statusPopup; - - VerticalPanel vPanel = new VerticalPanel(); - vPanel.add(createQueryPanel()); - - initWidget(vPanel); - setStylePrimaryName("my-QueryPanel"); - - pgf.addSettingsListener(new MySettingsListener()); - } - - protected Widget createQueryPanel() { - queryBox = new TextArea(); - queryBox.setStylePrimaryName("my-QueryBox"); - queryBox.setTitle("Goal category"); - - HorizontalPanel boxPanel = new HorizontalPanel(); - boxPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); - boxPanel.setSpacing(5); - - final TextBox limitBox = new TextBox(); - limitBox.setTitle("Upper limit of the number of examples generated"); - limitBox.setWidth("5em"); - limitBox.setText("10"); - boxPanel.add(new Label("limit:")); - boxPanel.add(limitBox); - - boxPanel.add(new HTML("")); - - final TextBox depthBox = new TextBox(); - depthBox.setTitle("Maximal depth for every example"); - depthBox.setWidth("5em"); - depthBox.setText("4"); - boxPanel.add(new Label("depth:")); - boxPanel.add(depthBox); - - boxPanel.add(new HTML("")); - - final CheckBox randomBox = new CheckBox(); - randomBox.setTitle("random/exhaustive generation"); - randomBox.setText("random"); - boxPanel.add(randomBox); - - outputPanel = new VerticalPanel(); - outputPanel.addStyleName("my-translations"); - outputPanel.addStyleDependentName("working"); - - Button execButton = new Button("Execute"); - - DecoratorPanel queryDecorator = new DecoratorPanel(); - VerticalPanel vPanel = new VerticalPanel(); - vPanel.add(new Label("Query")); - HorizontalPanel hPanel = new HorizontalPanel(); - hPanel.add(queryBox); - hPanel.add(execButton); - vPanel.add(hPanel); - vPanel.add(boxPanel); - queryDecorator.add(vPanel); - - VerticalPanel queryPanel = new VerticalPanel(); - queryPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER); - queryPanel.add(queryDecorator); - queryPanel.add(outputPanel); - - execButton.addClickListener(new ClickListener() { - public void onClick(Widget sender) { - if (executeRequest != null) { - executeRequest.cancel(); - } - - PGF.GenerationCallback callback = new PGF.GenerationCallback() { - public void onResult(IterableJsArray result) { - executeRequest = null; - - outputPanel.clear(); - outputPanel.removeStyleDependentName("working"); - - for (PGF.Linearizations lins : result.iterable()) { - LinearizationsPanel lin = new LinearizationsPanel(pgf, lins); - lin.setWidth("100%"); - outputPanel.add(lin); - } - } - - public void onError(Throwable e) { - executeRequest = null; - statusPopup.showError("The execution failed", e); - } - }; - - int depth, limit; - try { - depth = Integer.parseInt(depthBox.getText()); - limit = Integer.parseInt(limitBox.getText()); - } catch (NumberFormatException e) { - statusPopup.showError("Invalid depth/limit parameter", e); - return; - } - - if (randomBox.getValue()) - executeRequest = pgf.generateRandom(queryBox.getText(), depth, limit, callback); - else - executeRequest = pgf.generateAll(queryBox.getText(), depth, limit, callback); - } - }); - - return queryPanel; - } - - protected class MySettingsListener implements SettingsListener { - - public MySettingsListener() { - } - - public void onAvailableGrammarsChanged() { } - - public void onSelectedGrammarChanged() { - queryBox.setText(""); - outputPanel.clear(); - } - - public void onInputLanguageChanged() { } - public void onOutputLanguageChanged() { } - public void onStartCategoryChanged() { } - public void onSettingsError(String msg, Throwable e) { } - } -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SettingsListener.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SettingsListener.java deleted file mode 100644 index 494c990f6..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SettingsListener.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -public interface SettingsListener { - public void onAvailableGrammarsChanged(); - public void onSelectedGrammarChanged(); - public void onInputLanguageChanged(); - public void onOutputLanguageChanged(); - public void onStartCategoryChanged(); - public void onSettingsError(String msg, Throwable e); -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SettingsPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SettingsPanel.java deleted file mode 100644 index b3c22572c..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SettingsPanel.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.user.client.ui.*; - -public class SettingsPanel extends Composite { - - private PGFWrapper pgf; - private ContentService contentService; - private StatusPopup statusPopup; - - private MyListBox grammarBox; - private MyListBox fromLangBox; - private MyListBox toLangBox; - - public SettingsPanel (PGFWrapper pgf, ContentService contentService, StatusPopup statusPopup) { - this.pgf = pgf; - this.contentService = contentService; - this.statusPopup = statusPopup; - - HorizontalPanel settingsPanel = new HorizontalPanel(); - settingsPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER); - settingsPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); - - grammarBox = new MyListBox(); - grammarBox.addChangeListener(new ChangeListener() { - public void onChange(Widget sender) { - SettingsPanel.this.pgf.setGrammarURL(grammarBox.getSelectedValue()); - } - }); - settingsPanel.add(new FormWidget("Grammar:", grammarBox)); - - fromLangBox = new MyListBox(); - fromLangBox.addChangeListener(new ChangeListener() { - public void onChange(Widget sender) { - SettingsPanel.this.pgf.setInputLanguage(fromLangBox.getSelectedValue()); - } - }); - settingsPanel.add(new FormWidget("From:", fromLangBox)); - - toLangBox = new MyListBox(); - toLangBox.addChangeListener(new ChangeListener() { - public void onChange(Widget sender) { - SettingsPanel.this.pgf.setOutputLanguage(toLangBox.getSelectedValue()); - } - }); - settingsPanel.add(new FormWidget("To:", toLangBox)); - - if (contentService.getInit().getUserEMail() != null) { - String url = contentService.getInit().getContentURL(); - settingsPanel.add(new FormWidget(contentService.getInit().getUserEMail(), - new HTML("Sign Out"))); - } else { - String url = contentService.getInit().getContentURL(); - url = "https://www.google.com/accounts/o8/ud" - + "?openid.ns=http://specs.openid.net/auth/2.0" - + "&openid.ns.max_auth_age=300" - + "&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select" - + "&openid.identity=http://specs.openid.net/auth/2.0/identifier_select" - + "&openid.return_to=http://localhost:8080"+url - + "&openid.realm=http://localhost:8080/" - + "&openid.mode=checkid_setup" - + "&openid.ns.ax=http://openid.net/srv/ax/1.0" - + "&openid.ax.mode=fetch_request" - + "&openid.ax.type.email=http://axschema.org/contact/email" - + "&openid.ax.required=email"; - settingsPanel.add(new FormWidget("", - new HTML("Sign In"))); - } - - initWidget(settingsPanel); - setStylePrimaryName("my-SettingsPanel"); - - pgf.addSettingsListener(new MySettingsListener()); - contentService.addSettingsListener(new MySettingsListener()); - } - - private static class FormWidget extends HorizontalPanel { - public FormWidget(String label, Widget w) { - setStylePrimaryName("form-widget"); - setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE); - add(new Label(label)); - add(w); - } - } - - private class MySettingsListener implements SettingsListener { - public void onAvailableGrammarsChanged() { - if (grammarBox != null) { - grammarBox.clear(); - fromLangBox.clear(); - toLangBox.clear(); - - for (ContentService.GrammarInfo grammar : contentService.getGrammars()) { - grammarBox.addItem(grammar.getName(), grammar.getURL()); - } - pgf.setGrammarURL(grammarBox.getSelectedValue()); - } - } - public void onSelectedGrammarChanged() { - if (grammarBox != null) { - grammarBox.setSelectedValue(pgf.getGrammarURL()); - } - if (fromLangBox != null) { - fromLangBox.clear(); - fromLangBox.addItem("Any language", ""); - fromLangBox.addItems(pgf.getAllLanguages()); - String inputLanguage = pgf.getInputLanguage(); - if (inputLanguage != null) { - fromLangBox.setSelectedValue(inputLanguage); - } - } - if (toLangBox != null) { - toLangBox.clear(); - toLangBox.addItem("All languages", ""); - toLangBox.addItems(pgf.getAllLanguages()); - String outputLanguage = pgf.getOutputLanguage(); - if (outputLanguage != null) { - fromLangBox.setSelectedValue(outputLanguage); - } - } - } - public void onInputLanguageChanged() { - if (fromLangBox != null) { - fromLangBox.setSelectedValue(pgf.getInputLanguage()); - } - } - public void onOutputLanguageChanged() { - if (toLangBox != null) { - toLangBox.setSelectedValue(pgf.getOutputLanguage()); - } - } - public void onStartCategoryChanged() { } - public void onSettingsError(String msg, Throwable e) { } - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/StatusPopup.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/StatusPopup.java deleted file mode 100644 index 73ff82e0d..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/StatusPopup.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import com.google.gwt.core.client.GWT; -import com.google.gwt.user.client.ui.Label; -import com.google.gwt.user.client.ui.PopupPanel; - -public class StatusPopup extends PopupPanel { - - private Label label = new Label(); - - public StatusPopup () { - super(true, true); - label = new Label(); - add(label); - } - - public void setStatus(String msg) { - removeStyleDependentName("error"); - label.setText(msg); - center(); - } - - public void showError(String msg, Throwable e) { - GWT.log(msg, e); - addStyleDependentName("error"); - label.setText(msg); - center(); - } - - public void clearStatus() { - removeStyleDependentName("error"); - label.setText(""); - hide(); - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SubList.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SubList.java deleted file mode 100644 index 9d3221f39..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SubList.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.AbstractList; -import java.util.List; - -/** Work-around for missing List.subList() method in GWT JRE API emulation. */ -public class SubList extends AbstractList { - - private List list; - - private int fromIndex; - - private int toIndex; - - public SubList(List list, int fromIndex, int toIndex) { - this.list = list; - this.fromIndex = fromIndex; - this.toIndex = toIndex; - if (fromIndex < 0 || toIndex > list.size()) - throw new IndexOutOfBoundsException("Endpoint index value out of range"); - if (fromIndex > toIndex) - throw new IllegalArgumentException("Endpoint indices out of order"); - } - - public T get(int index) { - return list.get(fromIndex + index); - } - - public int size() { - return toIndex - fromIndex; - } - - public static SubList makeSubList(List list, int fromIndex, int toIndex) { - return new SubList(list, fromIndex, toIndex); - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SuggestPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SuggestPanel.java deleted file mode 100644 index 8e2edf582..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/SuggestPanel.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.LinkedList; -import java.util.List; - -import com.google.gwt.core.client.GWT; -import com.google.gwt.user.client.ui.*; - -public class SuggestPanel extends Composite implements HasText { - - private SuggestBox suggest; - private Button submitButton; - - private List listeners = new LinkedList(); - - public SuggestPanel (PGFWrapper pgf) { - - CompletionOracle oracle = new CompletionOracle(pgf, new CompletionOracle.ErrorHandler() { - public void onError(Throwable e) { - GWT.log("Completion failed", e); - } - }); - - suggest = new SuggestBox(oracle); - suggest.setLimit(10); - suggest.addKeyboardListener(new KeyboardListenerAdapter() { - public void onKeyUp (Widget sender, char keyCode, int modifiers) { - if (keyCode == KEY_ENTER) { - submit(); - } - } - }); - - submitButton = new Button("Submit"); - submitButton.addClickListener(new ClickListener() { - public void onClick(Widget sender) { - submit(); - } - }); - - DockPanel mainPanel = new DockPanel(); - mainPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); - mainPanel.add(suggest, DockPanel.CENTER); - mainPanel.add(submitButton, DockPanel.EAST); - - initWidget(mainPanel); - setStylePrimaryName("my-SuggestPanel"); - - } - - public int getLimit() { - return suggest.getLimit(); - } - - public String getText() { - return suggest.getText(); - } - - public String getTitle() { - return suggest.getTitle(); - } - - public void onLoad() { - suggest.setFocus(true); - } - - public void setButtonText (String text) { - submitButton.setText(text); - } - - public void setEnabled(boolean enabled) { - submitButton.setEnabled(enabled); - } - - public void setLimit(int limit) { - suggest.setLimit(limit); - } - - public void setText (String text) { - suggest.setText(text); - } - - public void setTitle(String title) { - suggest.setTitle(title); - } - - public void addSubmitListener(SubmitListener listener) { - listeners.add(listener); - } - - public void submit() { - String text = getText(); - for (SubmitListener listener : listeners) { - listener.onSubmit(text); - } - } - - public interface SubmitListener { - public void onSubmit(String text); - } - -} diff --git a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/TextInputPanel.java b/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/TextInputPanel.java deleted file mode 100644 index bf2c04a03..000000000 --- a/src/ui/gwt/src/org/grammaticalframework/ui/gwt/client/TextInputPanel.java +++ /dev/null @@ -1,600 +0,0 @@ -package org.grammaticalframework.ui.gwt.client; - -import java.util.*; - -import com.google.gwt.core.client.*; -import com.google.gwt.user.client.*; -import com.google.gwt.user.client.ui.*; -import com.google.gwt.event.dom.client.*; -import com.google.gwt.event.logical.shared.*; -import com.google.gwt.event.shared.*; - -public class TextInputPanel extends Composite implements Focusable, HasValueChangeHandlers, HasSelectionHandlers { - - protected ContentService contentService; - protected StatusPopup statusPopup; - protected FlowPanel textPanel = null; - protected FlowPanel mainPanel = null; - protected FocusPanel focusPanel = null; - protected Panel focusedPanel = null; - protected List selectedPanels = null; - protected List errorPanels = null; - protected Panel tempPanel = null; - protected Label status = null; - protected NavigationController navigationController; - protected MagnetSearchBox searchBox = null; - - private List