[
  {
    "path": ".git/HEAD",
    "content": "ref: refs/heads/master\n"
  },
  {
    "path": ".git/config",
    "content": "[core]\n\trepositoryformatversion = 1\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n[remote \"origin\"]\n\turl = https://github.com/ponty/framebuffer-vncserver\n\ttagOpt = --no-tags\n\tfetch = +refs/heads/master:refs/remotes/origin/master\n\tpromisor = true\n\tpartialclonefilter = blob:limit=1048576\n[branch \"master\"]\n\tremote = origin\n\tmerge = refs/heads/master\n"
  },
  {
    "path": ".git/description",
    "content": "Unnamed repository; edit this file 'description' to name the repository.\n"
  },
  {
    "path": ".git/hooks/applypatch-msg.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to check the commit log message taken by\n# applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.  The hook is\n# allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"applypatch-msg\".\n\n. git-sh-setup\ncommitmsg=\"$(git rev-parse --git-path hooks/commit-msg)\"\ntest -x \"$commitmsg\" && exec \"$commitmsg\" ${1+\"$@\"}\n:\n"
  },
  {
    "path": ".git/hooks/commit-msg.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to check the commit log message.\n# Called by \"git commit\" with one argument, the name of the file\n# that has the commit message.  The hook should exit with non-zero\n# status after issuing an appropriate message if it wants to stop the\n# commit.  The hook is allowed to edit the commit message file.\n#\n# To enable this hook, rename this file to \"commit-msg\".\n\n# Uncomment the below to add a Signed-off-by line to the message.\n# Doing this in a hook is a bad idea in general, but the prepare-commit-msg\n# hook is more suited to it.\n#\n# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\\(.*>\\).*$/Signed-off-by: \\1/p')\n# grep -qs \"^$SOB\" \"$1\" || echo \"$SOB\" >> \"$1\"\n\n# This example catches duplicate Signed-off-by lines.\n\ntest \"\" = \"$(grep '^Signed-off-by: ' \"$1\" |\n\t sort | uniq -c | sed -e '/^[ \t]*1[ \t]/d')\" || {\n\techo >&2 Duplicate Signed-off-by lines.\n\texit 1\n}\n"
  },
  {
    "path": ".git/hooks/fsmonitor-watchman.sample",
    "content": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\nuse IPC::Open2;\n\n# An example hook script to integrate Watchman\n# (https://facebook.github.io/watchman/) with git to speed up detecting\n# new and modified files.\n#\n# The hook is passed a version (currently 2) and last update token\n# formatted as a string and outputs to stdout a new update token and\n# all files that have been modified since the update token. Paths must\n# be relative to the root of the working tree and separated by a single NUL.\n#\n# To enable this hook, rename this file to \"query-watchman\" and set\n# 'git config core.fsmonitor .git/hooks/query-watchman'\n#\nmy ($version, $last_update_token) = @ARGV;\n\n# Uncomment for debugging\n# print STDERR \"$0 $version $last_update_token\\n\";\n\n# Check the hook interface version\nif ($version ne 2) {\n\tdie \"Unsupported query-fsmonitor hook version '$version'.\\n\" .\n\t    \"Falling back to scanning...\\n\";\n}\n\nmy $git_work_tree = get_working_dir();\n\nmy $retry = 1;\n\nmy $json_pkg;\neval {\n\trequire JSON::XS;\n\t$json_pkg = \"JSON::XS\";\n\t1;\n} or do {\n\trequire JSON::PP;\n\t$json_pkg = \"JSON::PP\";\n};\n\nlaunch_watchman();\n\nsub launch_watchman {\n\tmy $o = watchman_query();\n\tif (is_work_tree_watched($o)) {\n\t\toutput_result($o->{clock}, @{$o->{files}});\n\t}\n}\n\nsub output_result {\n\tmy ($clockid, @files) = @_;\n\n\t# Uncomment for debugging watchman output\n\t# open (my $fh, \">\", \".git/watchman-output.out\");\n\t# binmode $fh, \":utf8\";\n\t# print $fh \"$clockid\\n@files\\n\";\n\t# close $fh;\n\n\tbinmode STDOUT, \":utf8\";\n\tprint $clockid;\n\tprint \"\\0\";\n\tlocal $, = \"\\0\";\n\tprint @files;\n}\n\nsub watchman_clock {\n\tmy $response = qx/watchman clock \"$git_work_tree\"/;\n\tdie \"Failed to get clock id on '$git_work_tree'.\\n\" .\n\t\t\"Falling back to scanning...\\n\" if $? != 0;\n\n\treturn $json_pkg->new->utf8->decode($response);\n}\n\nsub watchman_query {\n\tmy $pid = open2(\\*CHLD_OUT, \\*CHLD_IN, 'watchman -j --no-pretty')\n\tor die \"open2() failed: $!\\n\" .\n\t\"Falling back to scanning...\\n\";\n\n\t# In the query expression below we're asking for names of files that\n\t# changed since $last_update_token but not from the .git folder.\n\t#\n\t# To accomplish this, we're using the \"since\" generator to use the\n\t# recency index to select candidate nodes and \"fields\" to limit the\n\t# output to file names only. Then we're using the \"expression\" term to\n\t# further constrain the results.\n\tmy $last_update_line = \"\";\n\tif (substr($last_update_token, 0, 1) eq \"c\") {\n\t\t$last_update_token = \"\\\"$last_update_token\\\"\";\n\t\t$last_update_line = qq[\\n\"since\": $last_update_token,];\n\t}\n\tmy $query = <<\"\tEND\";\n\t\t[\"query\", \"$git_work_tree\", {$last_update_line\n\t\t\t\"fields\": [\"name\"],\n\t\t\t\"expression\": [\"not\", [\"dirname\", \".git\"]]\n\t\t}]\n\tEND\n\n\t# Uncomment for debugging the watchman query\n\t# open (my $fh, \">\", \".git/watchman-query.json\");\n\t# print $fh $query;\n\t# close $fh;\n\n\tprint CHLD_IN $query;\n\tclose CHLD_IN;\n\tmy $response = do {local $/; <CHLD_OUT>};\n\n\t# Uncomment for debugging the watch response\n\t# open ($fh, \">\", \".git/watchman-response.json\");\n\t# print $fh $response;\n\t# close $fh;\n\n\tdie \"Watchman: command returned no output.\\n\" .\n\t\"Falling back to scanning...\\n\" if $response eq \"\";\n\tdie \"Watchman: command returned invalid output: $response\\n\" .\n\t\"Falling back to scanning...\\n\" unless $response =~ /^\\{/;\n\n\treturn $json_pkg->new->utf8->decode($response);\n}\n\nsub is_work_tree_watched {\n\tmy ($output) = @_;\n\tmy $error = $output->{error};\n\tif ($retry > 0 and $error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) {\n\t\t$retry--;\n\t\tmy $response = qx/watchman watch \"$git_work_tree\"/;\n\t\tdie \"Failed to make watchman watch '$git_work_tree'.\\n\" .\n\t\t    \"Falling back to scanning...\\n\" if $? != 0;\n\t\t$output = $json_pkg->new->utf8->decode($response);\n\t\t$error = $output->{error};\n\t\tdie \"Watchman: $error.\\n\" .\n\t\t\"Falling back to scanning...\\n\" if $error;\n\n\t\t# Uncomment for debugging watchman output\n\t\t# open (my $fh, \">\", \".git/watchman-output.out\");\n\t\t# close $fh;\n\n\t\t# Watchman will always return all files on the first query so\n\t\t# return the fast \"everything is dirty\" flag to git and do the\n\t\t# Watchman query just to get it over with now so we won't pay\n\t\t# the cost in git to look up each individual file.\n\t\tmy $o = watchman_clock();\n\t\t$error = $output->{error};\n\n\t\tdie \"Watchman: $error.\\n\" .\n\t\t\"Falling back to scanning...\\n\" if $error;\n\n\t\toutput_result($o->{clock}, (\"/\"));\n\t\t$last_update_token = $o->{clock};\n\n\t\teval { launch_watchman() };\n\t\treturn 0;\n\t}\n\n\tdie \"Watchman: $error.\\n\" .\n\t\"Falling back to scanning...\\n\" if $error;\n\n\treturn 1;\n}\n\nsub get_working_dir {\n\tmy $working_dir;\n\tif ($^O =~ 'msys' || $^O =~ 'cygwin') {\n\t\t$working_dir = Win32::GetCwd();\n\t\t$working_dir =~ tr/\\\\/\\//;\n\t} else {\n\t\trequire Cwd;\n\t\t$working_dir = Cwd::cwd();\n\t}\n\n\treturn $working_dir;\n}\n"
  },
  {
    "path": ".git/hooks/post-update.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to prepare a packed repository for use over\n# dumb transports.\n#\n# To enable this hook, rename this file to \"post-update\".\n\nexec git update-server-info\n"
  },
  {
    "path": ".git/hooks/pre-applypatch.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed\n# by applypatch from an e-mail message.\n#\n# The hook should exit with non-zero status after issuing an\n# appropriate message if it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-applypatch\".\n\n. git-sh-setup\nprecommit=\"$(git rev-parse --git-path hooks/pre-commit)\"\ntest -x \"$precommit\" && exec \"$precommit\" ${1+\"$@\"}\n:\n"
  },
  {
    "path": ".git/hooks/pre-commit.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed.\n# Called by \"git commit\" with no arguments.  The hook should\n# exit with non-zero status after issuing an appropriate message if\n# it wants to stop the commit.\n#\n# To enable this hook, rename this file to \"pre-commit\".\n\nif git rev-parse --verify HEAD >/dev/null 2>&1\nthen\n\tagainst=HEAD\nelse\n\t# Initial commit: diff against an empty tree object\n\tagainst=$(git hash-object -t tree /dev/null)\nfi\n\n# If you want to allow non-ASCII filenames set this variable to true.\nallownonascii=$(git config --type=bool hooks.allownonascii)\n\n# Redirect output to stderr.\nexec 1>&2\n\n# Cross platform projects tend to avoid non-ASCII filenames; prevent\n# them from being added to the repository. We exploit the fact that the\n# printable range starts at the space character and ends with tilde.\nif [ \"$allownonascii\" != \"true\" ] &&\n\t# Note that the use of brackets around a tr range is ok here, (it's\n\t# even required, for portability to Solaris 10's /usr/bin/tr), since\n\t# the square bracket bytes happen to fall in the designated range.\n\ttest $(git diff-index --cached --name-only --diff-filter=A -z $against |\n\t  LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0\nthen\n\tcat <<\\EOF\nError: Attempt to add a non-ASCII file name.\n\nThis can cause problems if you want to work with people on other platforms.\n\nTo be portable it is advisable to rename the file.\n\nIf you know what you are doing you can disable this check using:\n\n  git config hooks.allownonascii true\nEOF\n\texit 1\nfi\n\n# If there are whitespace errors, print the offending file names and fail.\nexec git diff-index --check --cached $against --\n"
  },
  {
    "path": ".git/hooks/pre-merge-commit.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to verify what is about to be committed.\n# Called by \"git merge\" with no arguments.  The hook should\n# exit with non-zero status after issuing an appropriate message to\n# stderr if it wants to stop the merge commit.\n#\n# To enable this hook, rename this file to \"pre-merge-commit\".\n\n. git-sh-setup\ntest -x \"$GIT_DIR/hooks/pre-commit\" &&\n        exec \"$GIT_DIR/hooks/pre-commit\"\n:\n"
  },
  {
    "path": ".git/hooks/pre-push.sample",
    "content": "#!/bin/sh\n\n# An example hook script to verify what is about to be pushed.  Called by \"git\n# push\" after it has checked the remote status, but before anything has been\n# pushed.  If this script exits with a non-zero status nothing will be pushed.\n#\n# This hook is called with the following parameters:\n#\n# $1 -- Name of the remote to which the push is being done\n# $2 -- URL to which the push is being done\n#\n# If pushing without using a named remote those arguments will be equal.\n#\n# Information about the commits which are being pushed is supplied as lines to\n# the standard input in the form:\n#\n#   <local ref> <local oid> <remote ref> <remote oid>\n#\n# This sample shows how to prevent push of commits where the log message starts\n# with \"WIP\" (work in progress).\n\nremote=\"$1\"\nurl=\"$2\"\n\nzero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')\n\nwhile read local_ref local_oid remote_ref remote_oid\ndo\n\tif test \"$local_oid\" = \"$zero\"\n\tthen\n\t\t# Handle delete\n\t\t:\n\telse\n\t\tif test \"$remote_oid\" = \"$zero\"\n\t\tthen\n\t\t\t# New branch, examine all commits\n\t\t\trange=\"$local_oid\"\n\t\telse\n\t\t\t# Update to existing branch, examine new commits\n\t\t\trange=\"$remote_oid..$local_oid\"\n\t\tfi\n\n\t\t# Check for WIP commit\n\t\tcommit=$(git rev-list -n 1 --grep '^WIP' \"$range\")\n\t\tif test -n \"$commit\"\n\t\tthen\n\t\t\techo >&2 \"Found WIP commit in $local_ref, not pushing\"\n\t\t\texit 1\n\t\tfi\n\tfi\ndone\n\nexit 0\n"
  },
  {
    "path": ".git/hooks/pre-rebase.sample",
    "content": "#!/bin/sh\n#\n# Copyright (c) 2006, 2008 Junio C Hamano\n#\n# The \"pre-rebase\" hook is run just before \"git rebase\" starts doing\n# its job, and can prevent the command from running by exiting with\n# non-zero status.\n#\n# The hook is called with the following parameters:\n#\n# $1 -- the upstream the series was forked from.\n# $2 -- the branch being rebased (or empty when rebasing the current branch).\n#\n# This sample shows how to prevent topic branches that are already\n# merged to 'next' branch from getting rebased, because allowing it\n# would result in rebasing already published history.\n\npublish=next\nbasebranch=\"$1\"\nif test \"$#\" = 2\nthen\n\ttopic=\"refs/heads/$2\"\nelse\n\ttopic=`git symbolic-ref HEAD` ||\n\texit 0 ;# we do not interrupt rebasing detached HEAD\nfi\n\ncase \"$topic\" in\nrefs/heads/??/*)\n\t;;\n*)\n\texit 0 ;# we do not interrupt others.\n\t;;\nesac\n\n# Now we are dealing with a topic branch being rebased\n# on top of master.  Is it OK to rebase it?\n\n# Does the topic really exist?\ngit show-ref -q \"$topic\" || {\n\techo >&2 \"No such branch $topic\"\n\texit 1\n}\n\n# Is topic fully merged to master?\nnot_in_master=`git rev-list --pretty=oneline ^master \"$topic\"`\nif test -z \"$not_in_master\"\nthen\n\techo >&2 \"$topic is fully merged to master; better remove it.\"\n\texit 1 ;# we could allow it, but there is no point.\nfi\n\n# Is topic ever merged to next?  If so you should not be rebasing it.\nonly_next_1=`git rev-list ^master \"^$topic\" ${publish} | sort`\nonly_next_2=`git rev-list ^master           ${publish} | sort`\nif test \"$only_next_1\" = \"$only_next_2\"\nthen\n\tnot_in_topic=`git rev-list \"^$topic\" master`\n\tif test -z \"$not_in_topic\"\n\tthen\n\t\techo >&2 \"$topic is already up to date with master\"\n\t\texit 1 ;# we could allow it, but there is no point.\n\telse\n\t\texit 0\n\tfi\nelse\n\tnot_in_next=`git rev-list --pretty=oneline ^${publish} \"$topic\"`\n\t/usr/bin/perl -e '\n\t\tmy $topic = $ARGV[0];\n\t\tmy $msg = \"* $topic has commits already merged to public branch:\\n\";\n\t\tmy (%not_in_next) = map {\n\t\t\t/^([0-9a-f]+) /;\n\t\t\t($1 => 1);\n\t\t} split(/\\n/, $ARGV[1]);\n\t\tfor my $elem (map {\n\t\t\t\t/^([0-9a-f]+) (.*)$/;\n\t\t\t\t[$1 => $2];\n\t\t\t} split(/\\n/, $ARGV[2])) {\n\t\t\tif (!exists $not_in_next{$elem->[0]}) {\n\t\t\t\tif ($msg) {\n\t\t\t\t\tprint STDERR $msg;\n\t\t\t\t\tundef $msg;\n\t\t\t\t}\n\t\t\t\tprint STDERR \" $elem->[1]\\n\";\n\t\t\t}\n\t\t}\n\t' \"$topic\" \"$not_in_next\" \"$not_in_master\"\n\texit 1\nfi\n\n<<\\DOC_END\n\nThis sample hook safeguards topic branches that have been\npublished from being rewound.\n\nThe workflow assumed here is:\n\n * Once a topic branch forks from \"master\", \"master\" is never\n   merged into it again (either directly or indirectly).\n\n * Once a topic branch is fully cooked and merged into \"master\",\n   it is deleted.  If you need to build on top of it to correct\n   earlier mistakes, a new topic branch is created by forking at\n   the tip of the \"master\".  This is not strictly necessary, but\n   it makes it easier to keep your history simple.\n\n * Whenever you need to test or publish your changes to topic\n   branches, merge them into \"next\" branch.\n\nThe script, being an example, hardcodes the publish branch name\nto be \"next\", but it is trivial to make it configurable via\n$GIT_DIR/config mechanism.\n\nWith this workflow, you would want to know:\n\n(1) ... if a topic branch has ever been merged to \"next\".  Young\n    topic branches can have stupid mistakes you would rather\n    clean up before publishing, and things that have not been\n    merged into other branches can be easily rebased without\n    affecting other people.  But once it is published, you would\n    not want to rewind it.\n\n(2) ... if a topic branch has been fully merged to \"master\".\n    Then you can delete it.  More importantly, you should not\n    build on top of it -- other people may already want to\n    change things related to the topic as patches against your\n    \"master\", so if you need further changes, it is better to\n    fork the topic (perhaps with the same name) afresh from the\n    tip of \"master\".\n\nLet's look at this example:\n\n\t\t   o---o---o---o---o---o---o---o---o---o \"next\"\n\t\t  /       /           /           /\n\t\t /   a---a---b A     /           /\n\t\t/   /               /           /\n\t       /   /   c---c---c---c B         /\n\t      /   /   /             \\         /\n\t     /   /   /   b---b C     \\       /\n\t    /   /   /   /             \\     /\n    ---o---o---o---o---o---o---o---o---o---o---o \"master\"\n\n\nA, B and C are topic branches.\n\n * A has one fix since it was merged up to \"next\".\n\n * B has finished.  It has been fully merged up to \"master\" and \"next\",\n   and is ready to be deleted.\n\n * C has not merged to \"next\" at all.\n\nWe would want to allow C to be rebased, refuse A, and encourage\nB to be deleted.\n\nTo compute (1):\n\n\tgit rev-list ^master ^topic next\n\tgit rev-list ^master        next\n\n\tif these match, topic has not merged in next at all.\n\nTo compute (2):\n\n\tgit rev-list master..topic\n\n\tif this is empty, it is fully merged to \"master\".\n\nDOC_END\n"
  },
  {
    "path": ".git/hooks/pre-receive.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to make use of push options.\n# The example simply echoes all push options that start with 'echoback='\n# and rejects all pushes when the \"reject\" push option is used.\n#\n# To enable this hook, rename this file to \"pre-receive\".\n\nif test -n \"$GIT_PUSH_OPTION_COUNT\"\nthen\n\ti=0\n\twhile test \"$i\" -lt \"$GIT_PUSH_OPTION_COUNT\"\n\tdo\n\t\teval \"value=\\$GIT_PUSH_OPTION_$i\"\n\t\tcase \"$value\" in\n\t\techoback=*)\n\t\t\techo \"echo from the pre-receive-hook: ${value#*=}\" >&2\n\t\t\t;;\n\t\treject)\n\t\t\texit 1\n\t\tesac\n\t\ti=$((i + 1))\n\tdone\nfi\n"
  },
  {
    "path": ".git/hooks/prepare-commit-msg.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to prepare the commit log message.\n# Called by \"git commit\" with the name of the file that has the\n# commit message, followed by the description of the commit\n# message's source.  The hook's purpose is to edit the commit\n# message file.  If the hook fails with a non-zero status,\n# the commit is aborted.\n#\n# To enable this hook, rename this file to \"prepare-commit-msg\".\n\n# This hook includes three examples. The first one removes the\n# \"# Please enter the commit message...\" help message.\n#\n# The second includes the output of \"git diff --name-status -r\"\n# into the message, just before the \"git status\" output.  It is\n# commented because it doesn't cope with --amend or with squashed\n# commits.\n#\n# The third example adds a Signed-off-by line to the message, that can\n# still be edited.  This is rarely a good idea.\n\nCOMMIT_MSG_FILE=$1\nCOMMIT_SOURCE=$2\nSHA1=$3\n\n/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' \"$COMMIT_MSG_FILE\"\n\n# case \"$COMMIT_SOURCE,$SHA1\" in\n#  ,|template,)\n#    /usr/bin/perl -i.bak -pe '\n#       print \"\\n\" . `git diff --cached --name-status -r`\n# \t if /^#/ && $first++ == 0' \"$COMMIT_MSG_FILE\" ;;\n#  *) ;;\n# esac\n\n# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\\(.*>\\).*$/Signed-off-by: \\1/p')\n# git interpret-trailers --in-place --trailer \"$SOB\" \"$COMMIT_MSG_FILE\"\n# if test -z \"$COMMIT_SOURCE\"\n# then\n#   /usr/bin/perl -i.bak -pe 'print \"\\n\" if !$first_line++' \"$COMMIT_MSG_FILE\"\n# fi\n"
  },
  {
    "path": ".git/hooks/push-to-checkout.sample",
    "content": "#!/bin/sh\n\n# An example hook script to update a checked-out tree on a git push.\n#\n# This hook is invoked by git-receive-pack(1) when it reacts to git\n# push and updates reference(s) in its repository, and when the push\n# tries to update the branch that is currently checked out and the\n# receive.denyCurrentBranch configuration variable is set to\n# updateInstead.\n#\n# By default, such a push is refused if the working tree and the index\n# of the remote repository has any difference from the currently\n# checked out commit; when both the working tree and the index match\n# the current commit, they are updated to match the newly pushed tip\n# of the branch. This hook is to be used to override the default\n# behaviour; however the code below reimplements the default behaviour\n# as a starting point for convenient modification.\n#\n# The hook receives the commit with which the tip of the current\n# branch is going to be updated:\ncommit=$1\n\n# It can exit with a non-zero status to refuse the push (when it does\n# so, it must not modify the index or the working tree).\ndie () {\n\techo >&2 \"$*\"\n\texit 1\n}\n\n# Or it can make any necessary changes to the working tree and to the\n# index to bring them to the desired state when the tip of the current\n# branch is updated to the new commit, and exit with a zero status.\n#\n# For example, the hook can simply run git read-tree -u -m HEAD \"$1\"\n# in order to emulate git fetch that is run in the reverse direction\n# with git push, as the two-tree form of git read-tree -u -m is\n# essentially the same as git switch or git checkout that switches\n# branches while keeping the local changes in the working tree that do\n# not interfere with the difference between the branches.\n\n# The below is a more-or-less exact translation to shell of the C code\n# for the default behaviour for git's push-to-checkout hook defined in\n# the push_to_deploy() function in builtin/receive-pack.c.\n#\n# Note that the hook will be executed from the repository directory,\n# not from the working tree, so if you want to perform operations on\n# the working tree, you will have to adapt your code accordingly, e.g.\n# by adding \"cd ..\" or using relative paths.\n\nif ! git update-index -q --ignore-submodules --refresh\nthen\n\tdie \"Up-to-date check failed\"\nfi\n\nif ! git diff-files --quiet --ignore-submodules --\nthen\n\tdie \"Working directory has unstaged changes\"\nfi\n\n# This is a rough translation of:\n#\n#   head_has_history() ? \"HEAD\" : EMPTY_TREE_SHA1_HEX\nif git cat-file -e HEAD 2>/dev/null\nthen\n\thead=HEAD\nelse\n\thead=$(git hash-object -t tree --stdin </dev/null)\nfi\n\nif ! git diff-index --quiet --cached --ignore-submodules $head --\nthen\n\tdie \"Working directory has staged changes\"\nfi\n\nif ! git read-tree -u -m \"$commit\"\nthen\n\tdie \"Could not update working tree to new HEAD\"\nfi\n"
  },
  {
    "path": ".git/hooks/sendemail-validate.sample",
    "content": "#!/bin/sh\n\n# An example hook script to validate a patch (and/or patch series) before\n# sending it via email.\n#\n# The hook should exit with non-zero status after issuing an appropriate\n# message if it wants to prevent the email(s) from being sent.\n#\n# To enable this hook, rename this file to \"sendemail-validate\".\n#\n# By default, it will only check that the patch(es) can be applied on top of\n# the default upstream branch without conflicts in a secondary worktree. After\n# validation (successful or not) of the last patch of a series, the worktree\n# will be deleted.\n#\n# The following config variables can be set to change the default remote and\n# remote ref that are used to apply the patches against:\n#\n#   sendemail.validateRemote (default: origin)\n#   sendemail.validateRemoteRef (default: HEAD)\n#\n# Replace the TODO placeholders with appropriate checks according to your\n# needs.\n\nvalidate_cover_letter () {\n\tfile=\"$1\"\n\t# TODO: Replace with appropriate checks (e.g. spell checking).\n\ttrue\n}\n\nvalidate_patch () {\n\tfile=\"$1\"\n\t# Ensure that the patch applies without conflicts.\n\tgit am -3 \"$file\" || return\n\t# TODO: Replace with appropriate checks for this patch\n\t# (e.g. checkpatch.pl).\n\ttrue\n}\n\nvalidate_series () {\n\t# TODO: Replace with appropriate checks for the whole series\n\t# (e.g. quick build, coding style checks, etc.).\n\ttrue\n}\n\n# main -------------------------------------------------------------------------\n\nif test \"$GIT_SENDEMAIL_FILE_COUNTER\" = 1\nthen\n\tremote=$(git config --default origin --get sendemail.validateRemote) &&\n\tref=$(git config --default HEAD --get sendemail.validateRemoteRef) &&\n\tworktree=$(mktemp --tmpdir -d sendemail-validate.XXXXXXX) &&\n\tgit worktree add -fd --checkout \"$worktree\" \"refs/remotes/$remote/$ref\" &&\n\tgit config --replace-all sendemail.validateWorktree \"$worktree\"\nelse\n\tworktree=$(git config --get sendemail.validateWorktree)\nfi || {\n\techo \"sendemail-validate: error: failed to prepare worktree\" >&2\n\texit 1\n}\n\nunset GIT_DIR GIT_WORK_TREE\ncd \"$worktree\" &&\n\nif grep -q \"^diff --git \" \"$1\"\nthen\n\tvalidate_patch \"$1\"\nelse\n\tvalidate_cover_letter \"$1\"\nfi &&\n\nif test \"$GIT_SENDEMAIL_FILE_COUNTER\" = \"$GIT_SENDEMAIL_FILE_TOTAL\"\nthen\n\tgit config --unset-all sendemail.validateWorktree &&\n\ttrap 'git worktree remove -ff \"$worktree\"' EXIT &&\n\tvalidate_series\nfi\n"
  },
  {
    "path": ".git/hooks/update.sample",
    "content": "#!/bin/sh\n#\n# An example hook script to block unannotated tags from entering.\n# Called by \"git receive-pack\" with arguments: refname sha1-old sha1-new\n#\n# To enable this hook, rename this file to \"update\".\n#\n# Config\n# ------\n# hooks.allowunannotated\n#   This boolean sets whether unannotated tags will be allowed into the\n#   repository.  By default they won't be.\n# hooks.allowdeletetag\n#   This boolean sets whether deleting tags will be allowed in the\n#   repository.  By default they won't be.\n# hooks.allowmodifytag\n#   This boolean sets whether a tag may be modified after creation. By default\n#   it won't be.\n# hooks.allowdeletebranch\n#   This boolean sets whether deleting branches will be allowed in the\n#   repository.  By default they won't be.\n# hooks.denycreatebranch\n#   This boolean sets whether remotely creating branches will be denied\n#   in the repository.  By default this is allowed.\n#\n\n# --- Command line\nrefname=\"$1\"\noldrev=\"$2\"\nnewrev=\"$3\"\n\n# --- Safety check\nif [ -z \"$GIT_DIR\" ]; then\n\techo \"Don't run this script from the command line.\" >&2\n\techo \" (if you want, you could supply GIT_DIR then run\" >&2\n\techo \"  $0 <ref> <oldrev> <newrev>)\" >&2\n\texit 1\nfi\n\nif [ -z \"$refname\" -o -z \"$oldrev\" -o -z \"$newrev\" ]; then\n\techo \"usage: $0 <ref> <oldrev> <newrev>\" >&2\n\texit 1\nfi\n\n# --- Config\nallowunannotated=$(git config --type=bool hooks.allowunannotated)\nallowdeletebranch=$(git config --type=bool hooks.allowdeletebranch)\ndenycreatebranch=$(git config --type=bool hooks.denycreatebranch)\nallowdeletetag=$(git config --type=bool hooks.allowdeletetag)\nallowmodifytag=$(git config --type=bool hooks.allowmodifytag)\n\n# check for no description\nprojectdesc=$(sed -e '1q' \"$GIT_DIR/description\")\ncase \"$projectdesc\" in\n\"Unnamed repository\"* | \"\")\n\techo \"*** Project description file hasn't been set\" >&2\n\texit 1\n\t;;\nesac\n\n# --- Check types\n# if $newrev is 0000...0000, it's a commit to delete a ref.\nzero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')\nif [ \"$newrev\" = \"$zero\" ]; then\n\tnewrev_type=delete\nelse\n\tnewrev_type=$(git cat-file -t $newrev)\nfi\n\ncase \"$refname\",\"$newrev_type\" in\n\trefs/tags/*,commit)\n\t\t# un-annotated tag\n\t\tshort_refname=${refname##refs/tags/}\n\t\tif [ \"$allowunannotated\" != \"true\" ]; then\n\t\t\techo \"*** The un-annotated tag, $short_refname, is not allowed in this repository\" >&2\n\t\t\techo \"*** Use 'git tag [ -a | -s ]' for tags you want to propagate.\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/tags/*,delete)\n\t\t# delete tag\n\t\tif [ \"$allowdeletetag\" != \"true\" ]; then\n\t\t\techo \"*** Deleting a tag is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/tags/*,tag)\n\t\t# annotated tag\n\t\tif [ \"$allowmodifytag\" != \"true\" ] && git rev-parse $refname > /dev/null 2>&1\n\t\tthen\n\t\t\techo \"*** Tag '$refname' already exists.\" >&2\n\t\t\techo \"*** Modifying a tag is not allowed in this repository.\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/heads/*,commit)\n\t\t# branch\n\t\tif [ \"$oldrev\" = \"$zero\" -a \"$denycreatebranch\" = \"true\" ]; then\n\t\t\techo \"*** Creating a branch is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/heads/*,delete)\n\t\t# delete branch\n\t\tif [ \"$allowdeletebranch\" != \"true\" ]; then\n\t\t\techo \"*** Deleting a branch is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\trefs/remotes/*,commit)\n\t\t# tracking branch\n\t\t;;\n\trefs/remotes/*,delete)\n\t\t# delete tracking branch\n\t\tif [ \"$allowdeletebranch\" != \"true\" ]; then\n\t\t\techo \"*** Deleting a tracking branch is not allowed in this repository\" >&2\n\t\t\texit 1\n\t\tfi\n\t\t;;\n\t*)\n\t\t# Anything else (is there anything else?)\n\t\techo \"*** Update hook: unknown type of update to ref $refname of type $newrev_type\" >&2\n\t\texit 1\n\t\t;;\nesac\n\n# --- Finished\nexit 0\n"
  },
  {
    "path": ".git/info/exclude",
    "content": "# git ls-files --others --exclude-from=.git/info/exclude\n# Lines that start with '#' are comments.\n# For a project mostly in C, the following would be a good set of\n# exclude patterns (uncomment them if you want to use them):\n# *.[oa]\n# *~\n"
  },
  {
    "path": ".git/logs/HEAD",
    "content": "0000000000000000000000000000000000000000 1963e57bebfde420baeecbb2c6848a2382488413 appuser <appuser@7c99e0e64a07.(none)> 1778656786 +0000\tclone: from https://github.com/ponty/framebuffer-vncserver\n"
  },
  {
    "path": ".git/logs/refs/heads/master",
    "content": "0000000000000000000000000000000000000000 1963e57bebfde420baeecbb2c6848a2382488413 appuser <appuser@7c99e0e64a07.(none)> 1778656786 +0000\tclone: from https://github.com/ponty/framebuffer-vncserver\n"
  },
  {
    "path": ".git/logs/refs/remotes/origin/HEAD",
    "content": "0000000000000000000000000000000000000000 1963e57bebfde420baeecbb2c6848a2382488413 appuser <appuser@7c99e0e64a07.(none)> 1778656786 +0000\tclone: from https://github.com/ponty/framebuffer-vncserver\n"
  },
  {
    "path": ".git/objects/pack/pack-bef8852657c06b106e38622c43f30aebfe12ac48.promisor",
    "content": "1963e57bebfde420baeecbb2c6848a2382488413 refs/heads/master\n"
  },
  {
    "path": ".git/packed-refs",
    "content": "# pack-refs with: peeled fully-peeled sorted \n1963e57bebfde420baeecbb2c6848a2382488413 refs/remotes/origin/master\n"
  },
  {
    "path": ".git/refs/heads/master",
    "content": "1963e57bebfde420baeecbb2c6848a2382488413\n"
  },
  {
    "path": ".git/refs/remotes/origin/HEAD",
    "content": "ref: refs/remotes/origin/master\n"
  },
  {
    "path": ".git/shallow",
    "content": "1963e57bebfde420baeecbb2c6848a2382488413\n"
  },
  {
    "path": ".github/workflows/main.yml",
    "content": "# For more information see: \n#  https://docs.github.com/en/actions/automating-builds-and-tests/\n\nname: build\n\non:\n  schedule:\n    # * is a special character in YAML so you have to quote this string\n    - cron:  '30 5 1 */3 *'\n  push:\n  pull_request:\n\njobs:\n  build:\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        os: \n          - \"ubuntu-20.04\"\n          - \"ubuntu-22.04\"\n    steps:\n    - uses: actions/checkout@v3\n    - name: Install dependencies\n      run: |\n        sudo apt-get update\n        sudo apt-get install -y libvncserver-dev cmake qt5-qmake qtbase5-dev\n    - name: Test CMake build\n      run: |\n        mkdir -p build && cd build && cmake .. && make && cd ..\n    - name: Test QT build\n      run: |\n        mkdir -p buildqt && cd buildqt && qmake ../framebuffer-vncserver.pro && make && cd ..\n"
  },
  {
    "path": ".gitignore",
    "content": "# C++ objects and libs\n\n*.slo\n*.lo\n*.o\n*.a\n*.la\n*.lai\n*.so\n*.dll\n*.dylib\n\n# Qt-es\n\n/.qmake.cache\n/.qmake.stash\n*.pro.user\n*.pro.user.*\n*.moc\nmoc_*.cpp\nqrc_*.cpp\nui_*.h\n#Makefile*\n*-build-*\n\n# QtCreator\n\n*.autosave\n\n#QtCtreator Qml\n*.qmlproject.user\n*.qmlproject.user.*\n\n\n.*\n!.git*\n!.travis*\n\nbuild/\n*.log\n"
  },
  {
    "path": ".travis.yml.bak",
    "content": "language: c\ninstall:\n - sudo apt-get update -qq\n - sudo apt-get install -y libvncserver-dev cmake qt4-qmake \n\nscript:  \n - mkdir -p build1 && cd build1 && cmake .. && make && cd ..\n - mkdir -p build2 && cd build2 && qmake ../framebuffer-vncserver.pro && make && cd ..\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "PROJECT(framebuffer-vncserver)\nCMAKE_MINIMUM_REQUIRED(VERSION 2.6)\n\n\nFILE(GLOB SOURCES src/*.c)\nADD_EXECUTABLE(framebuffer-vncserver ${SOURCES})\nINSTALL(TARGETS framebuffer-vncserver RUNTIME DESTINATION bin)\n\n# LIBVNC\nfind_library(LIBVNC NAMES libvncserver vncserver)\ntarget_link_libraries(framebuffer-vncserver ${LIBVNC})\n\n\nMESSAGE( STATUS \"LIBVNC:         \" ${LIBVNC} )\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM alpine as builder\nLABEL maintainer=\"ek5.chimenti@gmail.com\"\n\nADD . /target/\nWORKDIR /target\n\nRUN apk fetch\nRUN apk add libvncserver-dev\nRUN apk add gcc g++ cmake make linux-headers\n\nRUN mkdir -p build\nWORKDIR /target/build\nRUN cmake ..\nRUN make\n\nFROM alpine\n\nCOPY --from=builder /target/build/framebuffer-vncserver /usr/bin\nRUN apk update && apk add libvncserver\n\nENTRYPOINT [ \"framebuffer-vncserver\" ]\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n\n"
  },
  {
    "path": "README.md",
    "content": "# framebuffer-vncserver\n\nVNC server for Linux framebuffer devices.\n\n![workflow](https://github.com/ponty/framebuffer-vncserver/actions/workflows/main.yml/badge.svg)\n\nThe goal is to access remote embedded Linux systems without X.\nImplemented features: remote display, touchscreen, keyboard, rotation\nNot implemented: file transfer, ..\n\nWorking configurations:\n\nwithout rotation:\n- [x]  1 bit/pixel\n- [x]  8 bit/pixel\n- [x]  16 bit/pixel\n- [x]  24 bit/pixel\n- [x]  32 bit/pixel\n\nwith rotation:\n- [ ]  1 bit/pixel\n- [ ]  8 bit/pixel\n- [x]  16 bit/pixel\n- [ ]  24 bit/pixel\n- [ ]  32 bit/pixel\n\nThe code is based on a LibVNC example for Android:\nhttps://github.com/LibVNC/libvncserver/blob/master/examples/androidvncserver.c\n\n### build\n\nDependency:\n\n\tsudo apt-get install libvncserver-dev\n\nThere are 2 options: CMake or qmake\n\nUsing cmake:\n\n\tmkdir -p build && cd build\n\tcmake ..\n\tmake\n\t\nUsing qmake:\n\n\tmkdir -p buildqt && cd buildqt\n\tqmake ../framebuffer-vncserver.pro\n\tmake\n\n \n\n### command-line help \n\n\t./framebuffer-vncserver [-f device] [-p port] [-t touchscreen] [-m mouse] [-k keyboard] [-r rotation] [-R touchscreen rotation] [-F FPS] [-v] [-h]\n\t-p port: VNC port, default is 5900\n\t-f device: framebuffer device node, default is /dev/fb0\n\t-k device: keyboard device node (example: /dev/input/event0)\n\t-t device: touchscreen device node (example:/dev/input/event2)\n\t-m device: mouse device node (example:/dev/input/event2)\n\t-r degrees: framebuffer rotation, default is 0\n\t-R degrees: touchscreen rotation, default is same as framebuffer rotation\n\t-F FPS: Maximum target FPS, default is 10\n\t-v: verbose\n\t-h: print this help\n\n## Run on startup as service\n\nTo run at startup as a service using systemd, edit the file `fbvnc.service` make sure the path and command line arguments are correct and then run:\n\n```shell\nsudo cp fbvnc.service /etc/systemd/system/\nsudo systemctl enable fbvnc.service\nsudo systemctl start fbvnc.service\n```\n\n## Vfb test\n\nLinux Virtual Frame Buffer kernel object (vfb.ko) is used for this test.\nhttps://cateee.net/lkddb/web-lkddb/FB_VIRTUAL.html\n\nLocal computer:\n\t\n\t# install\n\tsudo apt install vagrant virtualbox xtightvncviewer\n\t\n\t# after framebuffer-vncserver start\n\tvncviewer localhost\n\n\tvagrant up\n\tvagrant ssh\n\nInside vagrant box:\n\n\tsudo su\n\tcd /home/vagrant/build/\n\n\t# build framebuffer-vncserver\n\tmake\n\n\t# set resolution, color depth\n    fbset -g 640 480 640 480 16\n\n\t# restart framebuffer-vncserver\n\tkillall framebuffer-vncserver;./framebuffer-vncserver -t /dev/input/ms -k /dev/input/kbd &\n\n\t# set test pattern or ..\n\tfb-test\n\n\t# draw random rectangles or ..\n\trect\n\t\n\t# display a GUI or ...\n\tqmlscene -platform linuxfb -plugin evdevmouse:/dev/input/ms:abs -plugin evdevkeyboard:/dev/input/kbd:grab=1\n\n### Automatic test \n\nThis generates patterns with different resolutions and color depths (on local computer):\n\t\n\tpython3 -m pip install fabric vncdotool python-vagrant entrypoint2\n\tpython3 vfb.py\n\n| rotation | color | fbtest                                  | qmlscene                                  | gradient                                  |\n| -------: | ----: | --------------------------------------- | ----------------------------------------- | ----------------------------------------- |\n|        0 |     1 |                                         | ![](/img/qmlscene_160x120_c1_rot0.png)    |                                           |\n|        0 |     8 | ![](/img/fbtest_160x120_c8_rot0.png)    |                                           | ![](/img/gradient_160x120_c8_rot0.png)    |\n|        0 |    16 | ![](/img/fbtest_160x120_c16_rot0.png)   | ![](/img/qmlscene_160x120_c16_rot0.png)   | ![](/img/gradient_160x120_c16_rot0.png)   |\n|        0 |    24 | ![](/img/fbtest_160x120_c24_rot0.png)   | ![](/img/qmlscene_160x120_c24_rot0.png)   | ![](/img/gradient_160x120_c24_rot0.png)   |\n|        0 |    32 | ![](/img/fbtest_160x120_c32_rot0.png)   | ![](/img/qmlscene_160x120_c32_rot0.png)   | ![](/img/gradient_160x120_c32_rot0.png)   |\n|       90 |    16 | ![](/img/fbtest_160x120_c16_rot90.png)  | ![](/img/qmlscene_160x120_c16_rot90.png)  | ![](/img/gradient_160x120_c16_rot90.png)  |\n|      180 |    16 | ![](/img/fbtest_160x120_c16_rot180.png) | ![](/img/qmlscene_160x120_c16_rot180.png) | ![](/img/gradient_160x120_c16_rot180.png) |\n|      270 |    16 | ![](/img/fbtest_160x120_c16_rot270.png) | ![](/img/qmlscene_160x120_c16_rot270.png) | ![](/img/gradient_160x120_c16_rot270.png) |\n\n## Testing single-touch\n\n\t$ (evtest /dev/input/event0 &) ;./framebuffer-vncserver -t /dev/input/event0 -v\n\t...\n\tInitializing touch device /dev/input/event0 ...\n\tx:(0 4095)  y:(0 4095) \n\t...\n\tSupported events:\n\tEvent type 0 (EV_SYN)\n\tEvent type 1 (EV_KEY)\n\t\tEvent code 330 (BTN_TOUCH)\n\tEvent type 3 (EV_ABS)\n\t\tEvent code 0 (ABS_X)\n\t\tValue   1970\n\t\tMin        0\n\t\tMax     4095\n\t\tEvent code 1 (ABS_Y)\n\t\tValue   1745\n\t\tMin        0\n\t\tMax     4095\n\t\tEvent code 24 (ABS_PRESSURE)\n\t\tValue      0\n\t\tMin        0\n\t\tMax      255\n\t...\n\tGot ptrevent: 0001 (x=186, y=570)\n\tEvent: time 1580221917.655639, type 1 (EV_KEY), code 330 (BTN_TOUCH), value 1\n\tEvent: time 1580221917.655639, type 3 (EV_ABS), code 0 (ABS_X), value 1586\n\tEvent: time 1580221917.655639, type 3 (EV_ABS), code 1 (ABS_Y), value 2733\n\tEvent: time 1580221917.655639, -------------- SYN_REPORT ------------\n\tinjectTouchEvent (screen(186,570) -> touch(1586,2733), mouse=1)\n\t...\n\tGot ptrevent: 0000 (x=186, y=570)\n\tEvent: time 1580221918.516897, type 1 (EV_KEY), code 330 (BTN_TOUCH), value 0\n\tEvent: time 1580221918.516897, -------------- SYN_REPORT ------------\n\tinjectTouchEvent (screen(186,570) -> touch(1586,2733), mouse=0)\n\n## Testing multi-touch\n\n\t$ (evtest /dev/input/event2 &) ;./framebuffer-vncserver -t /dev/input/event2 -v\n\t...\n\tSupported events:\n\tEvent type 0 (EV_SYN)\n\tEvent type 1 (EV_KEY)\n\t\tEvent code 330 (BTN_TOUCH)\n\tEvent type 3 (EV_ABS)\n\t\tEvent code 0 (ABS_X)\n\t\tValue    245\n\t\tMin        0\n\t\tMax      480\n\t\tEvent code 1 (ABS_Y)\n\t\tValue    485\n\t\tMin        0\n\t\tMax      854\n\t\tEvent code 47 (ABS_MT_SLOT)\n\t\tValue      4\n\t\tMin        0\n\t\tMax        4\n\t\tEvent code 48 (ABS_MT_TOUCH_MAJOR)\n\t\tValue      0\n\t\tMin        0\n\t\tMax      255\n\t\tEvent code 50 (ABS_MT_WIDTH_MAJOR)\n\t\tValue      0\n\t\tMin        0\n\t\tMax      255\n\t\tEvent code 53 (ABS_MT_POSITION_X)\n\t\tValue      0\n\t\tMin        0\n\t\tMax      480\n\t\tEvent code 54 (ABS_MT_POSITION_Y)\n\t\tValue      0\n\t\tMin        0\n\t\tMax      854\n\t\tEvent code 57 (ABS_MT_TRACKING_ID)\n\t\tValue      0\n\t\tMin        0\n\t\tMax    65535\n\t...\n\tInitializing touch device /dev/input/event2 ...\n\tx:(0 480)  y:(0 854) \n\t...\n\tGot ptrevent: 0001 (x=237, y=528)\n\tEvent: time 1580221680.870277, type 3 (EV_ABS), code 57 (ABS_MT_TRACKING_ID), value 0\n\tEvent: time 1580221680.870277, type 1 (EV_KEY), code 330 (BTN_TOUCH), value 1\n\tEvent: time 1580221680.870277, type 3 (EV_ABS), code 53 (ABS_MT_POSITION_X), value 237\n\tEvent: time 1580221680.870277, type 3 (EV_ABS), code 54 (ABS_MT_POSITION_Y), value 528\n\tEvent: time 1580221680.870277, type 3 (EV_ABS), code 0 (ABS_X), value 237\n\tEvent: time 1580221680.870277, type 3 (EV_ABS), code 1 (ABS_Y), value 528\n\tEvent: time 1580221680.870277, -------------- SYN_REPORT ------------\n\tinjectTouchEvent (screen(237,528) -> touch(237,528), mouse=1)\n\t...\n\tGot ptrevent: 0000 (x=237, y=528)\n\tEvent: time 1580221681.190716, type 3 (EV_ABS), code 57 (ABS_MT_TRACKING_ID), value -1\n\tEvent: time 1580221681.190716, type 1 (EV_KEY), code 330 (BTN_TOUCH), value 0\n\tEvent: time 1580221681.190716, -------------- SYN_REPORT ------------\n\tinjectTouchEvent (screen(237,528) -> touch(237,528), mouse=0)\n"
  },
  {
    "path": "Vagrantfile",
    "content": "Vagrant.configure(2) do |config|\n  config.vm.box = \"ubuntu/jammy64\"\n\n  config.vm.network \"forwarded_port\", guest: 5900, host: 5900\n\n  config.vm.provider \"virtualbox\" do |vb|\n    vb.name = \"framebuffer-vncserver.22.04\"\n    #   vb.gui = true\n    #   vb.memory = \"1024\"\n\n    # https://bugs.launchpad.net/cloud-images/+bug/1829625\n    # vb.customize [\"modifyvm\", :id, \"--uart1\", \"0x3F8\", \"4\"]\n    # vb.customize [\"modifyvm\", :id, \"--uartmode1\", \"file\", \"./ttyS0.log\"]\n  end\n\n  # disable vbox fb\n  config.vm.provision \"shell\", inline: \"echo 'blacklist vboxvideo' >> /etc/modprobe.d/vbox.conf;sudo update-initramfs -u\"\n\t# vagrant plugin install vagrant-reload\n  config.vm.provision :reload\n  config.vm.provision \"shell\", path: \"vagrant.sh\"\n\n  config.ssh.extra_args = [\"-t\", \"cd /vagrant;sudo su\"]\nend\n"
  },
  {
    "path": "Vagrantfile.20.04.rb",
    "content": "Vagrant.configure(2) do |config|\n  config.vm.box = \"ubuntu/focal64\"\n\n  config.vm.network \"forwarded_port\", guest: 5900, host: 5900\n\n  config.vm.provider \"virtualbox\" do |vb|\n    vb.name = \"framebuffer-vncserver.20.04\"\n    #   vb.gui = true\n    #   vb.memory = \"1024\"\n\n    # https://bugs.launchpad.net/cloud-images/+bug/1829625\n    # vb.customize [\"modifyvm\", :id, \"--uart1\", \"0x3F8\", \"4\"]\n    # vb.customize [\"modifyvm\", :id, \"--uartmode1\", \"file\", \"./ttyS0.log\"]\n  end\n\n  config.vm.provision \"shell\", path: \"vagrant.sh\"\n\n  config.ssh.extra_args = [\"-t\", \"cd /vagrant;sudo su\"]\nend\n\n# export VAGRANT_VAGRANTFILE=Vagrantfile.20.04.rb;export VAGRANT_DOTFILE_PATH=.vagrant_${VAGRANT_VAGRANTFILE}\n"
  },
  {
    "path": "deployment.pri",
    "content": "# This file was generated by an application wizard of Qt Creator.\n# The code below handles deployment to Android and Maemo, aswell as copying\n# of the application data to shadow build directories on desktop.\n# It is recommended not to modify this file, since newer versions of Qt Creator\n# may offer an updated version of it.\n\ndefineTest(qtcAddDeployment) {\nfor(deploymentfolder, DEPLOYMENTFOLDERS) {\n    item = item$${deploymentfolder}\n    greaterThan(QT_MAJOR_VERSION, 4) {\n        itemsources = $${item}.files\n    } else {\n        itemsources = $${item}.sources\n    }\n    $$itemsources = $$eval($${deploymentfolder}.source)\n    itempath = $${item}.path\n    $$itempath= $$eval($${deploymentfolder}.target)\n    export($$itemsources)\n    export($$itempath)\n    DEPLOYMENT += $$item\n}\n\nMAINPROFILEPWD = $$PWD\n\nandroid-no-sdk {\n    for(deploymentfolder, DEPLOYMENTFOLDERS) {\n        item = item$${deploymentfolder}\n        itemfiles = $${item}.files\n        $$itemfiles = $$eval($${deploymentfolder}.source)\n        itempath = $${item}.path\n        $$itempath = /data/user/qt/$$eval($${deploymentfolder}.target)\n        export($$itemfiles)\n        export($$itempath)\n        INSTALLS += $$item\n    }\n\n    target.path = /data/user/qt\n\n    export(target.path)\n    INSTALLS += target\n} else:android {\n    for(deploymentfolder, DEPLOYMENTFOLDERS) {\n        item = item$${deploymentfolder}\n        itemfiles = $${item}.files\n        $$itemfiles = $$eval($${deploymentfolder}.source)\n        itempath = $${item}.path\n        $$itempath = /assets/$$eval($${deploymentfolder}.target)\n        export($$itemfiles)\n        export($$itempath)\n        INSTALLS += $$item\n    }\n\n    x86 {\n        target.path = /libs/x86\n    } else: armeabi-v7a {\n        target.path = /libs/armeabi-v7a\n    } else {\n        target.path = /libs/armeabi\n    }\n\n    export(target.path)\n    INSTALLS += target\n} else:win32 {\n    copyCommand =\n    for(deploymentfolder, DEPLOYMENTFOLDERS) {\n        source = $$MAINPROFILEPWD/$$eval($${deploymentfolder}.source)\n        source = $$replace(source, /, \\\\)\n        sourcePathSegments = $$split(source, \\\\)\n        target = $$OUT_PWD/$$eval($${deploymentfolder}.target)/$$last(sourcePathSegments)\n        target = $$replace(target, /, \\\\)\n        target ~= s,\\\\\\\\\\\\.?\\\\\\\\,\\\\,\n        !isEqual(source,$$target) {\n            !isEmpty(copyCommand):copyCommand += &&\n            isEqual(QMAKE_DIR_SEP, \\\\) {\n                copyCommand += $(COPY_DIR) \\\"$$source\\\" \\\"$$target\\\"\n            } else {\n                source = $$replace(source, \\\\\\\\, /)\n                target = $$OUT_PWD/$$eval($${deploymentfolder}.target)\n                target = $$replace(target, \\\\\\\\, /)\n                copyCommand += test -d \\\"$$target\\\" || mkdir -p \\\"$$target\\\" && cp -r \\\"$$source\\\" \\\"$$target\\\"\n            }\n        }\n    }\n    !isEmpty(copyCommand) {\n        copyCommand = @echo Copying application data... && $$copyCommand\n        copydeploymentfolders.commands = $$copyCommand\n        first.depends = $(first) copydeploymentfolders\n        export(first.depends)\n        export(copydeploymentfolders.commands)\n        QMAKE_EXTRA_TARGETS += first copydeploymentfolders\n    }\n} else:ios {\n    copyCommand =\n    for(deploymentfolder, DEPLOYMENTFOLDERS) {\n        source = $$MAINPROFILEPWD/$$eval($${deploymentfolder}.source)\n        source = $$replace(source, \\\\\\\\, /)\n        target = $CODESIGNING_FOLDER_PATH/$$eval($${deploymentfolder}.target)\n        target = $$replace(target, \\\\\\\\, /)\n        sourcePathSegments = $$split(source, /)\n        targetFullPath = $$target/$$last(sourcePathSegments)\n        targetFullPath ~= s,/\\\\.?/,/,\n        !isEqual(source,$$targetFullPath) {\n            !isEmpty(copyCommand):copyCommand += &&\n            copyCommand += mkdir -p \\\"$$target\\\"\n            copyCommand += && cp -r \\\"$$source\\\" \\\"$$target\\\"\n        }\n    }\n    !isEmpty(copyCommand) {\n        copyCommand = echo Copying application data... && $$copyCommand\n        !isEmpty(QMAKE_POST_LINK): QMAKE_POST_LINK += \";\"\n        QMAKE_POST_LINK += \"$$copyCommand\"\n        export(QMAKE_POST_LINK)\n    }\n} else:unix {\n    maemo5 {\n        desktopfile.files = $${TARGET}.desktop\n        desktopfile.path = /usr/share/applications/hildon\n        icon.files = $${TARGET}64.png\n        icon.path = /usr/share/icons/hicolor/64x64/apps\n    } else:!isEmpty(MEEGO_VERSION_MAJOR) {\n        desktopfile.files = $${TARGET}_harmattan.desktop\n        desktopfile.path = /usr/share/applications\n        icon.files = $${TARGET}80.png\n        icon.path = /usr/share/icons/hicolor/80x80/apps\n    } else { # Assumed to be a Desktop Unix\n        copyCommand =\n        for(deploymentfolder, DEPLOYMENTFOLDERS) {\n            source = $$MAINPROFILEPWD/$$eval($${deploymentfolder}.source)\n            source = $$replace(source, \\\\\\\\, /)\n            macx {\n                target = $$OUT_PWD/$${TARGET}.app/Contents/Resources/$$eval($${deploymentfolder}.target)\n            } else {\n                target = $$OUT_PWD/$$eval($${deploymentfolder}.target)\n            }\n            target = $$replace(target, \\\\\\\\, /)\n            sourcePathSegments = $$split(source, /)\n            targetFullPath = $$target/$$last(sourcePathSegments)\n            targetFullPath ~= s,/\\\\.?/,/,\n            !isEqual(source,$$targetFullPath) {\n                !isEmpty(copyCommand):copyCommand += &&\n                copyCommand += $(MKDIR) \\\"$$target\\\"\n                copyCommand += && $(COPY_DIR) \\\"$$source\\\" \\\"$$target\\\"\n            }\n        }\n        !isEmpty(copyCommand) {\n            copyCommand = @echo Copying application data... && $$copyCommand\n            copydeploymentfolders.commands = $$copyCommand\n            first.depends = $(first) copydeploymentfolders\n            export(first.depends)\n            export(copydeploymentfolders.commands)\n            QMAKE_EXTRA_TARGETS += first copydeploymentfolders\n        }\n    }\n    !isEmpty(target.path) {\n        installPrefix = $${target.path}\n    } else {\n        installPrefix = /opt/$${TARGET}\n    }\n    for(deploymentfolder, DEPLOYMENTFOLDERS) {\n        item = item$${deploymentfolder}\n        itemfiles = $${item}.files\n        $$itemfiles = $$eval($${deploymentfolder}.source)\n        itempath = $${item}.path\n        $$itempath = $${installPrefix}/$$eval($${deploymentfolder}.target)\n        export($$itemfiles)\n        export($$itempath)\n        INSTALLS += $$item\n    }\n\n    !isEmpty(desktopfile.path) {\n        export(icon.files)\n        export(icon.path)\n        export(desktopfile.files)\n        export(desktopfile.path)\n        INSTALLS += icon desktopfile\n    }\n\n    isEmpty(target.path) {\n        target.path = $${installPrefix}/bin\n        export(target.path)\n    }\n    INSTALLS += target\n}\n\nexport (ICON)\nexport (INSTALLS)\nexport (DEPLOYMENT)\nexport (LIBS)\nexport (QMAKE_EXTRA_TARGETS)\n}\n\n"
  },
  {
    "path": "fbvnc.service",
    "content": "[Unit]\nDescription=Framebuffer VNC Server for 3.5\" TFT Display\n\n[Service]\nType=simple\nPIDFile=/var/run/fbvnc.pid\nExecStart=/home/pi/framebuffer-vncserver/build/framebuffer-vncserver -f /dev/fb1 -p 5901 -t /dev/input/touchscreen\n\n[Install]\nWantedBy=multi-user.target\n"
  },
  {
    "path": "format-code.sh",
    "content": "#!/bin/bash\nset -e\nautoflake  -i -r --remove-all-unused-imports .\nautoflake  -i -r --remove-unused-variables .\nisort .\nblack .\n"
  },
  {
    "path": "framebuffer-vncserver.pro",
    "content": "TEMPLATE = app\nCONFIG += console\nCONFIG -= app_bundle\nCONFIG -= qt\n\nSOURCES += src/framebuffer-vncserver.c\nSOURCES += src/keyboard.c\nSOURCES += src/touch.c\nSOURCES += src/mouse.c\n\ninclude(deployment.pri)\nqtcAddDeployment()\n\n\nLIBS += -lvncserver\n\nDISTFILES += \\\n    README.md\n"
  },
  {
    "path": "gradient.py",
    "content": "from entrypoint2 import entrypoint\n\n# last color channel\nchan = {\n    8: 0x07,\n    16: 0x1F,\n    24: 0xFF,\n    32: 0xFF,\n}\n\n\n@entrypoint\ndef gradient(width=320, height=240, colorbit=32, fileout=\"/dev/fb0\"):\n    \"\"\"colorbit: 8/16/24/32\"\"\"\n    assert colorbit in chan\n    with open(fileout, \"wb\") as f:\n        for y in range(0, height):\n            for x in range(0, width):\n                c = int(chan[colorbit] * (x + y) / (width + height))\n                f.write((c).to_bytes(int(colorbit / 8), byteorder=\"little\"))\n"
  },
  {
    "path": "src/framebuffer-vncserver.c",
    "content": "/*\n * $Id$\n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 2, or (at your option) any\n * later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * This project is an adaptation of the original fbvncserver for the iPAQ\n * and Zaurus.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <unistd.h>\n#include <sys/mman.h>\n#include <sys/ioctl.h>\n\n#include <sys/stat.h>\n#include <sys/sysmacros.h> /* For makedev() */\n\n#include <fcntl.h>\n#include <linux/fb.h>\n#include <linux/input.h>\n\n#include <assert.h>\n#include <errno.h>\n\n/* libvncserver */\n#include \"rfb/rfb.h\"\n#include \"rfb/keysym.h\"\n\n#include \"touch.h\"\n#include \"mouse.h\"\n#include \"keyboard.h\"\n#include \"logging.h\"\n\n/*****************************************************************************/\n#define LOG_FPS\n\n#define BITS_PER_SAMPLE 5\n#define SAMPLES_PER_PIXEL 2\n\n// #define CHANNELS_PER_PIXEL 4\n\nstatic char fb_device[256] = \"/dev/fb0\";\nstatic char touch_device[256] = \"\";\nstatic char kbd_device[256] = \"\";\nstatic char mouse_device[256] = \"\";\n\nstatic struct fb_var_screeninfo var_scrinfo;\nstatic struct fb_fix_screeninfo fix_scrinfo;\nstatic int fbfd = -1;\nstatic unsigned short int *fbmmap = MAP_FAILED;\nstatic unsigned short int *vncbuf;\nstatic unsigned short int *fbbuf;\n\nstatic int vnc_port = 5900;\nstatic int vnc_rotate = 0;\nstatic int touch_rotate = -1;\nstatic int target_fps = 10;\nstatic rfbScreenInfoPtr server;\nstatic size_t bytespp;\nstatic unsigned int bits_per_pixel;\nstatic unsigned int frame_size;\nstatic unsigned int fb_xres;\nstatic unsigned int fb_yres;\nint verbose = 0;\n\n#define UNUSED(x) (void)(x)\n\n/* No idea, just copied from fbvncserver as part of the frame differerencing\n * algorithm.  I will probably be later rewriting all of this. */\nstatic struct varblock_t\n{\n    int min_i;\n    int min_j;\n    int max_i;\n    int max_j;\n    int r_offset;\n    int g_offset;\n    int b_offset;\n    int rfb_xres;\n    int rfb_maxy;\n} varblock;\n\n/*****************************************************************************/\n\nstatic void init_fb(void)\n{\n    size_t pixels;\n\n    if ((fbfd = open(fb_device, O_RDONLY)) == -1)\n    {\n        error_print(\"cannot open fb device %s\\n\", fb_device);\n        exit(EXIT_FAILURE);\n    }\n\n    if (ioctl(fbfd, FBIOGET_VSCREENINFO, &var_scrinfo) != 0)\n    {\n        error_print(\"ioctl error\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    if (ioctl(fbfd, FBIOGET_FSCREENINFO, &fix_scrinfo) != 0)\n    {\n        error_print(\"ioctl error\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    /*\n     * Get actual resolution of the framebufffer, which is not always the same as the screen resolution.\n     * This prevents the screen from 'smearing' on 1366 x 768 displays\n     */\n\n    fb_xres = fix_scrinfo.line_length / (var_scrinfo.bits_per_pixel / 8.0);\n    fb_yres = var_scrinfo.yres;\n\n    pixels = fb_xres * fb_yres;\n    bytespp = var_scrinfo.bits_per_pixel / 8;\n    bits_per_pixel = var_scrinfo.bits_per_pixel;\n    frame_size = pixels * bits_per_pixel / 8;\n\n    info_print(\"  xres=%d, yres=%d, xresv=%d, yresv=%d, xoffs=%d, yoffs=%d, bpp=%d\\n\",\n               (int)fb_xres, (int)fb_yres,\n               (int)var_scrinfo.xres_virtual, (int)var_scrinfo.yres_virtual,\n               (int)var_scrinfo.xoffset, (int)var_scrinfo.yoffset,\n               (int)var_scrinfo.bits_per_pixel);\n    info_print(\"  offset:length red=%d:%d green=%d:%d blue=%d:%d \\n\",\n               (int)var_scrinfo.red.offset, (int)var_scrinfo.red.length,\n               (int)var_scrinfo.green.offset, (int)var_scrinfo.green.length,\n               (int)var_scrinfo.blue.offset, (int)var_scrinfo.blue.length);\n\n    fbmmap = mmap(NULL, frame_size, PROT_READ, MAP_SHARED, fbfd, 0);\n\n    if (fbmmap == MAP_FAILED)\n    {\n        error_print(\"mmap failed\\n\");\n        exit(EXIT_FAILURE);\n    }\n}\n\nstatic void cleanup_fb(void)\n{\n    if (fbfd != -1)\n    {\n        close(fbfd);\n        fbfd = -1;\n    }\n}\n\nstatic void keyevent(rfbBool down, rfbKeySym key, rfbClientPtr cl)\n{\n    int scancode;\n\n    debug_print(\"Got keysym: %04x (down=%d)\\n\", (unsigned int)key, (int)down);\n\n    if ((scancode = keysym2scancode(key, cl)))\n    {\n        injectKeyEvent(scancode, down);\n    }\n}\n\nstatic void ptrevent_touch(int buttonMask, int x, int y, rfbClientPtr cl)\n{\n    UNUSED(cl);\n    /* Indicates either pointer movement or a pointer button press or release. The pointer is\nnow at (x-position, y-position), and the current state of buttons 1 to 8 are represented\nby bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).\nOn a conventional mouse, buttons 1, 2 and 3 correspond to the left, middle and right\nbuttons on the mouse. On a wheel mouse, each step of the wheel upwards is represented\nby a press and release of button 4, and each step downwards is represented by\na press and release of button 5.\n  From: http://www.vislab.usyd.edu.au/blogs/index.php/2009/05/22/an-headerless-indexed-protocol-for-input-1?blog=61 */\n\n    debug_print(\"Got ptrevent: %04x (x=%d, y=%d)\\n\", buttonMask, x, y);\n    // Simulate left mouse event as touch event\n    static int pressed = 0;\n    if (buttonMask & 1)\n    {\n        if (pressed == 1)\n        {\n            injectTouchEvent(MouseDrag, x, y, &var_scrinfo);\n        }\n        else\n        {\n            pressed = 1;\n            injectTouchEvent(MousePress, x, y, &var_scrinfo);\n        }\n    }\n    if (buttonMask == 0)\n    {\n        if (pressed == 1)\n        {\n            pressed = 0;\n            injectTouchEvent(MouseRelease, x, y, &var_scrinfo);\n        }\n    }\n}\n\nstatic void ptrevent_mouse(int buttonMask, int x, int y, rfbClientPtr cl)\n{\n    UNUSED(cl);\n    /* Indicates either pointer movement or a pointer button press or release. The pointer is\nnow at (x-position, y-position), and the current state of buttons 1 to 8 are represented\nby bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).\nOn a conventional mouse, buttons 1, 2 and 3 correspond to the left, middle and right\nbuttons on the mouse. On a wheel mouse, each step of the wheel upwards is represented\nby a press and release of button 4, and each step downwards is represented by\na press and release of button 5.\n  From: http://www.vislab.usyd.edu.au/blogs/index.php/2009/05/22/an-headerless-indexed-protocol-for-input-1?blog=61 */\n\n    debug_print(\"Got mouse: %04x (x=%d, y=%d)\\n\", buttonMask, x, y);\n    // Simulate left mouse event as touch event\n    injectMouseEvent(&var_scrinfo, buttonMask, x, y);\n}\n\n/*****************************************************************************/\n\nstatic void init_fb_server(int argc, char **argv, rfbBool enable_touch, rfbBool enable_mouse)\n{\n    info_print(\"Initializing server...\\n\");\n\n    int rbytespp = bits_per_pixel == 1 ? 1 : bytespp;\n    int rframe_size = bits_per_pixel == 1 ? frame_size * 8 : frame_size;\n    /* Allocate the VNC server buffer to be managed (not manipulated) by\n     * libvncserver. */\n    vncbuf = malloc(rframe_size);\n    assert(vncbuf != NULL);\n    memset(vncbuf, bits_per_pixel == 1 ? 0xFF : 0x00, rframe_size);\n\n    /* Allocate the comparison buffer for detecting drawing updates from frame\n     * to frame. */\n    fbbuf = calloc(frame_size, 1);\n    assert(fbbuf != NULL);\n\n    /* TODO: This assumes var_scrinfo.bits_per_pixel is 16. */\n    server = rfbGetScreen(&argc, argv, fb_xres, fb_yres, BITS_PER_SAMPLE, SAMPLES_PER_PIXEL, rbytespp);\n    assert(server != NULL);\n\n    server->desktopName = \"framebuffer\";\n    server->frameBuffer = (char *)vncbuf;\n    server->alwaysShared = TRUE;\n    server->httpDir = NULL;\n    server->port = vnc_port;\n\n    server->kbdAddEvent = keyevent;\n    if (enable_touch)\n    {\n        server->ptrAddEvent = ptrevent_touch;\n    }\n\n    if (enable_mouse)\n    {\n        server->ptrAddEvent = ptrevent_mouse;\n    }\n    \n\n    rfbInitServer(server);\n\n    /* Mark as dirty since we haven't sent any updates at all yet. */\n    rfbMarkRectAsModified(server, 0, 0, fb_xres, fb_yres);\n\n    /* No idea. */\n    varblock.r_offset = var_scrinfo.red.offset + var_scrinfo.red.length - BITS_PER_SAMPLE;\n    varblock.g_offset = var_scrinfo.green.offset + var_scrinfo.green.length - BITS_PER_SAMPLE;\n    varblock.b_offset = var_scrinfo.blue.offset + var_scrinfo.blue.length - BITS_PER_SAMPLE;\n    varblock.rfb_xres = fb_yres;\n    varblock.rfb_maxy = fb_xres - 1;\n}\n\n// sec\n#define LOG_TIME 5\n\nint timeToLogFPS()\n{\n    static struct timeval now = {0, 0}, then = {0, 0};\n    double elapsed, dnow, dthen;\n    gettimeofday(&now, NULL);\n    dnow = now.tv_sec + (now.tv_usec / 1000000.0);\n    dthen = then.tv_sec + (then.tv_usec / 1000000.0);\n    elapsed = dnow - dthen;\n    if (elapsed > LOG_TIME)\n        memcpy((char *)&then, (char *)&now, sizeof(struct timeval));\n    return elapsed > LOG_TIME;\n}\n\n/*****************************************************************************/\n//#define COLOR_MASK  0x1f001f\n#define COLOR_MASK (((1 << BITS_PER_SAMPLE) << 1) - 1)\n#define PIXEL_FB_TO_RFB(p, r_offset, g_offset, b_offset) \\\n    ((p >> r_offset) & COLOR_MASK) | (((p >> g_offset) & COLOR_MASK) << BITS_PER_SAMPLE) | (((p >> b_offset) & COLOR_MASK) << (2 * BITS_PER_SAMPLE))\n\nstatic void update_screen(void)\n{\n#ifdef LOG_FPS\n    if (verbose)\n    {\n        static int frames = 0;\n        frames++;\n        if (timeToLogFPS())\n        {\n            double fps = frames / LOG_TIME;\n            info_print(\"  fps: %f\\n\", fps);\n            frames = 0;\n        }\n    }\n#endif\n\n    varblock.min_i = varblock.min_j = 9999;\n    varblock.max_i = varblock.max_j = -1;\n\n    if (vnc_rotate == 0 && bits_per_pixel == 24)\n    {\n        uint8_t *f = (uint8_t *)fbmmap; /* -> framebuffer         */\n        uint8_t *c = (uint8_t *)fbbuf;  /* -> compare framebuffer */\n        uint8_t *r = (uint8_t *)vncbuf; /* -> remote framebuffer  */\n\n        if (memcmp(fbmmap, fbbuf, frame_size) != 0)\n        {\n            int y;\n            for (y = 0; y < (int)fb_yres; y++)\n            {\n                int x;\n                for (x = 0; x < (int)fb_xres; x++)\n                {\n                    uint32_t pixel = *(uint32_t *)f & 0x00FFFFFF;\n                    uint32_t comp = *(uint32_t *)c & 0x00FFFFFF;\n\n                    if (pixel != comp)\n                    {\n                        *(c + 0) = *(f + 0);\n                        *(c + 1) = *(f + 1);\n                        *(c + 2) = *(f + 2);\n                        uint32_t rem = PIXEL_FB_TO_RFB(pixel,\n                                                       varblock.r_offset, varblock.g_offset, varblock.b_offset);\n                        *(r + 0) = (uint8_t)((rem >> 0) & 0xFF);\n                        *(r + 1) = (uint8_t)((rem >> 8) & 0xFF);\n                        *(r + 2) = (uint8_t)((rem >> 16) & 0xFF);\n\n                        if (x < varblock.min_i)\n                            varblock.min_i = x;\n                        else if (x > varblock.max_i)\n                            varblock.max_i = x;\n\n                        if (y > varblock.max_j)\n                            varblock.max_j = y;\n                        else if (y < varblock.min_j)\n                            varblock.min_j = y;\n                    }\n\n                    f += bytespp;\n                    c += bytespp;\n                    r += bytespp;\n                }\n            }\n        }\n    }\n    else if (vnc_rotate == 0 && bits_per_pixel == 1)\n    {\n        uint8_t *f = (uint8_t *)fbmmap; /* -> framebuffer         */\n        uint8_t *c = (uint8_t *)fbbuf;  /* -> compare framebuffer */\n        uint8_t *r = (uint8_t *)vncbuf; /* -> remote framebuffer  */\n\n        int xstep = 8;\n        if (memcmp(fbmmap, fbbuf, frame_size) != 0)\n        {\n            int y;\n            for (y = 0; y < (int)fb_yres; y++)\n            {\n                int x;\n                for (x = 0; x < (int)fb_xres; x += xstep)\n                {\n                    uint8_t pixels = *f;\n\n                    if (pixels != *c)\n                    {\n                        *c = pixels;\n\n                        for (int bit = 0; bit < 8; bit++)\n                        {\n                            // *(r+bit) = ((pixels >> (7-bit)) & 0x1) ? 0xFF : 0x00;\n                            *(r + bit) = ((pixels >> (7 - bit)) & 0x1) ? 0x00 : 0xFF;\n                        }\n\n                        int x2 = x + xstep - 1;\n                        if (x < varblock.min_i)\n                            varblock.min_i = x;\n                        else if (x2 > varblock.max_i)\n                            varblock.max_i = x2;\n\n                        if (y > varblock.max_j)\n                            varblock.max_j = y;\n                        else if (y < varblock.min_j)\n                            varblock.min_j = y;\n                    }\n\n                    f += 1;\n                    c += 1;\n                    r += 8;\n                }\n            }\n        }\n    }\n    else if (vnc_rotate == 0)\n    {\n        uint32_t *f = (uint32_t *)fbmmap; /* -> framebuffer         */\n        uint32_t *c = (uint32_t *)fbbuf;  /* -> compare framebuffer */\n        uint32_t *r = (uint32_t *)vncbuf; /* -> remote framebuffer  */\n\n        if (memcmp(fbmmap, fbbuf, frame_size) != 0)\n        {\n            //        memcpy(fbbuf, fbmmap, size);\n\n            int xstep = 4 / bytespp;\n\n            int y;\n            for (y = 0; y < (int)fb_yres; y++)\n            {\n                /* Compare every 1/2/4 pixels at a time */\n                int x;\n                for (x = 0; x < (int)fb_xres; x += xstep)\n                {\n                    uint32_t pixel = *f;\n\n                    if (pixel != *c)\n                    {\n                        *c = pixel;\n\n#if 0\n                /* XXX: Undo the checkered pattern to test the efficiency\n                 * gain using hextile encoding. */\n                if (pixel == 0x18e320e4 || pixel == 0x20e418e3)\n                    pixel = 0x18e318e3;\n#endif\n                        if (bytespp == 4)\n                        {\n                            *r = PIXEL_FB_TO_RFB(pixel,\n                                                 varblock.r_offset, varblock.g_offset, varblock.b_offset);\n                        }\n                        else if (bytespp == 2)\n                        {\n                            *r = PIXEL_FB_TO_RFB(pixel,\n                                                 varblock.r_offset, varblock.g_offset, varblock.b_offset);\n\n                            uint32_t high_pixel = (0xffff0000 & pixel) >> 16;\n                            uint32_t high_r = PIXEL_FB_TO_RFB(high_pixel, varblock.r_offset, varblock.g_offset, varblock.b_offset);\n                            *r |= (0xffff & high_r) << 16;\n                        }\n                        else if (bytespp == 1)\n                        {\n                            *r = pixel;\n                        }\n                        else\n                        {\n                            // TODO\n                        }\n\n                        int x2 = x + xstep - 1;\n                        if (x < varblock.min_i)\n                            varblock.min_i = x;\n                        else if (x2 > varblock.max_i)\n                            varblock.max_i = x2;\n\n                        if (y > varblock.max_j)\n                            varblock.max_j = y;\n                        else if (y < varblock.min_j)\n                            varblock.min_j = y;\n                    }\n\n                    f++;\n                    c++;\n                    r++;\n                }\n            }\n        }\n    }\n    else if (bits_per_pixel == 16)\n    {\n        uint16_t *f = (uint16_t *)fbmmap; /* -> framebuffer         */\n        uint16_t *c = (uint16_t *)fbbuf;  /* -> compare framebuffer */\n        uint16_t *r = (uint16_t *)vncbuf; /* -> remote framebuffer  */\n\n        switch (vnc_rotate)\n        {\n        case 0:\n        case 180:\n            server->width = fb_xres;\n            server->height = fb_yres;\n            server->paddedWidthInBytes = fb_xres * bytespp;\n            break;\n\n        case 90:\n        case 270:\n            server->width = fb_yres;\n            server->height = fb_xres;\n            server->paddedWidthInBytes = fb_yres * bytespp;\n            break;\n        }\n\n        if (memcmp(fbmmap, fbbuf, frame_size) != 0)\n        {\n            int y;\n            for (y = 0; y < (int)fb_yres; y++)\n            {\n                /* Compare every pixels at a time */\n                int x;\n                for (x = 0; x < (int)fb_xres; x++)\n                {\n                    uint16_t pixel = *f;\n\n                    if (pixel != *c)\n                    {\n                        int x2, y2;\n\n                        *c = pixel;\n                        switch (vnc_rotate)\n                        {\n                        case 0:\n                            x2 = x;\n                            y2 = y;\n                            break;\n\n                        case 90:\n                            x2 = fb_yres - 1 - y;\n                            y2 = x;\n                            break;\n\n                        case 180:\n                            x2 = fb_xres - 1 - x;\n                            y2 = fb_yres - 1 - y;\n                            break;\n\n                        case 270:\n                            x2 = y;\n                            y2 = fb_xres - 1 - x;\n                            break;\n                        default:\n                            error_print(\"rotation is invalid\\n\");\n                            exit(EXIT_FAILURE);\n                        }\n\n                        r[y2 * server->width + x2] = PIXEL_FB_TO_RFB(pixel, varblock.r_offset, varblock.g_offset, varblock.b_offset);\n\n                        if (x2 < varblock.min_i)\n                            varblock.min_i = x2;\n                        else\n                        {\n                            if (x2 > varblock.max_i)\n                                varblock.max_i = x2;\n\n                            if (y2 > varblock.max_j)\n                                varblock.max_j = y2;\n                            else if (y2 < varblock.min_j)\n                                varblock.min_j = y2;\n                        }\n                    }\n\n                    f++;\n                    c++;\n                }\n            }\n        }\n    }\n    else\n    {\n        error_print(\"not supported color depth or rotation\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    if (varblock.min_i < 9999)\n    {\n        if (varblock.max_i < 0)\n            varblock.max_i = varblock.min_i;\n\n        if (varblock.max_j < 0)\n            varblock.max_j = varblock.min_j;\n\n        debug_print(\"Dirty page: %dx%d+%d+%d...\\n\",\n                    (varblock.max_i + 2) - varblock.min_i, (varblock.max_j + 1) - varblock.min_j,\n                    varblock.min_i, varblock.min_j);\n\n        rfbMarkRectAsModified(server, varblock.min_i, varblock.min_j,\n                              varblock.max_i + 2, varblock.max_j + 1);\n    }\n}\n\n/*****************************************************************************/\n\nvoid print_usage(char **argv)\n{\n    info_print(\"%s [-f device] [-p port] [-t touchscreen] [-m mouse] [-k keyboard] [-r rotation] [-R touchscreen rotation] [-F FPS] [-v] [-h]\\n\"\n               \"-p port: VNC port, default is 5900\\n\"\n               \"-f device: framebuffer device node, default is /dev/fb0\\n\"\n               \"-k device: keyboard device node (example: /dev/input/event0)\\n\"\n               \"-t device: touchscreen device node (example:/dev/input/event2)\\n\"\n               \"-m device: mouse device node (example:/dev/input/event2)\\n\"\n               \"-r degrees: framebuffer rotation, default is 0\\n\"\n               \"-R degrees: touchscreen rotation, default is same as framebuffer rotation\\n\"\n               \"-F FPS: Maximum target FPS, default is 10\\n\"\n               \"-v: verbose\\n\"\n               \"-h: print this help\\n\",\n               *argv);\n}\n\nint main(int argc, char **argv)\n{\n    if (argc > 1)\n    {\n        int i = 1;\n        while (i < argc)\n        {\n            if (*argv[i] == '-')\n            {\n                switch (*(argv[i] + 1))\n                {\n                case 'h':\n                    print_usage(argv);\n                    exit(0);\n                    break;\n                case 'f':\n                    i++;\n                    if (argv[i])\n                        strcpy(fb_device, argv[i]);\n                    break;\n                case 't':\n                    i++;\n                    if (argv[i])\n                        strcpy(touch_device, argv[i]);\n                    break;\n                case 'm':\n                    i++;\n                    if (argv[i])\n                        strcpy(mouse_device, argv[i]);\n                    break;                    \n                case 'k':\n                    i++;\n                    strcpy(kbd_device, argv[i]);\n                    break;\n                case 'p':\n                    i++;\n                    if (argv[i])\n                        vnc_port = atoi(argv[i]);\n                    break;\n                case 'r':\n                    i++;\n                    if (argv[i])\n                        vnc_rotate = atoi(argv[i]);\n                    break;\n                case 'R':\n                    i++;\n                    if (argv[i])\n                        touch_rotate = atoi(argv[i]);\n                    break;\n               case 'F':\n                    i++;\n                    if (argv[i])\n                        target_fps = atoi(argv[i]);\n                    break;\n                case 'v':\n                    verbose = 1;\n                    break;\n                }\n            }\n            i++;\n        }\n    }\n\n    if (touch_rotate < 0)\n        touch_rotate = vnc_rotate;\n\n    info_print(\"Initializing framebuffer device %s...\\n\", fb_device);\n    init_fb();\n    if (strlen(kbd_device) > 0)\n    {\n        int ret = init_kbd(kbd_device);\n        if (!ret)\n            info_print(\"Keyboard device %s not available.\\n\", kbd_device);\n    }\n    else\n    {\n        info_print(\"No keyboard device\\n\");\n    }\n\n    rfbBool enable_touch = FALSE;\n    rfbBool enable_mouse = FALSE;\n    if(strlen(touch_device) > 0 && strlen(mouse_device) > 0)\n    {\n        error_print(\"It can't using both mouse and touch device.\\n\");\n        exit(EXIT_FAILURE);\n    }\n    else if (strlen(touch_device) > 0)\n    {\n        // init touch only if there is a touch device defined\n        int ret = init_touch(touch_device, touch_rotate);\n        enable_touch = (ret > 0);\n    }\n    else if(strlen(mouse_device) > 0)\n    {\n        // init touch only if there is a mouse device defined\n        int ret = init_mouse(mouse_device, touch_rotate);\n        enable_mouse = (ret > 0);        \n    }\n    else\n    {\n        info_print(\"No touch or mouse device\\n\");\n    }\n\n    info_print(\"Initializing VNC server:\\n\");\n    info_print(\"\twidth:  %d\\n\", (int)fb_xres);\n    info_print(\"\theight: %d\\n\", (int)fb_yres);\n    info_print(\"\tbpp:    %d\\n\", (int)var_scrinfo.bits_per_pixel);\n    info_print(\"\tport:   %d\\n\", (int)vnc_port);\n    info_print(\"\trotate: %d\\n\", (int)vnc_rotate);\n    info_print(\"  mouse/touch rotate: %d\\n\", (int)touch_rotate);\n    info_print(\"    target FPS: %d\\n\", (int)target_fps);\n    init_fb_server(argc, argv, enable_touch, enable_mouse);\n\n    /* Implement our own event loop to detect changes in the framebuffer. */\n    while (1)\n    {\n        rfbRunEventLoop(server, 100 * 1000, TRUE);\n        while (rfbIsActive(server))\n        {\n            if (server->clientHead != NULL)\n                update_screen();\n\n            if (target_fps > 0)\n                usleep(1000 * 1000 / target_fps);\n            else if (server->clientHead == NULL)\n                usleep(100 * 1000);\n        }\n    }\n\n    info_print(\"Cleaning up...\\n\");\n    cleanup_fb();\n    cleanup_kbd();\n    cleanup_touch();\n}\n"
  },
  {
    "path": "src/keyboard.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <unistd.h>\n#include <sys/mman.h>\n#include <sys/ioctl.h>\n\n#include <sys/stat.h>\n#include <sys/sysmacros.h> /* For makedev() */\n\n#include <fcntl.h>\n#include <linux/fb.h>\n#include <linux/input.h>\n\n#include <assert.h>\n#include <errno.h>\n\n/* libvncserver */\n#include \"rfb/rfb.h\"\n#include \"rfb/keysym.h\"\n\n#include \"keyboard.h\"\n#include \"logging.h\"\n\n#ifndef input_event_sec\n#define input_event_sec time.tv_sec\n#define input_event_usec time.tv_usec\n#endif\n\n//static char KBD_DEVICE[256] = \"/dev/input/event1\";\nstatic int kbdfd = -1;\n\nint init_kbd(const char *kbd_device)\n{\n    info_print(\"Initializing keyboard device %s ...\\n\", kbd_device);\n    if ((kbdfd = open(kbd_device, O_RDWR)) == -1)\n    {\n        error_print(\"cannot open kbd device %s\\n\", kbd_device);\n        return 0;\n    }\n    else\n    {\n        return 1;\n    }\n}\n\nvoid cleanup_kbd()\n{\n    if (kbdfd != -1)\n    {\n        close(kbdfd);\n    }\n}\n\nvoid injectKeyEvent(uint16_t code, uint16_t value)\n{\n    struct input_event ev;\n    memset(&ev, 0, sizeof(ev));\n\n    struct timeval time;\n    gettimeofday(&time, 0);\n    ev.input_event_sec = time.tv_sec;\n    ev.input_event_usec = time.tv_usec;\n\n    ev.type = EV_KEY;\n    ev.code = code;\n    ev.value = value;\n    if (write(kbdfd, &ev, sizeof(ev)) < 0)\n    {\n        error_print(\"write event failed, %s\\n\", strerror(errno));\n    }\n\n    // Finally send the SYN\n    gettimeofday(&time, 0);\n    ev.input_event_sec = time.tv_sec;\n    ev.input_event_usec = time.tv_usec;\n\n    ev.type = EV_SYN;\n    ev.code = 0;\n    ev.value = 0;\n    if (write(kbdfd, &ev, sizeof(ev)) < 0)\n    {\n        error_print(\"write event failed, %s\\n\", strerror(errno));\n    }\n\n    debug_print(\"injectKey (%d, %d)\\n\", code, value);\n}\n\nint keysym2scancode(rfbKeySym key, rfbClientPtr cl)\n{\n    int scancode = 0;\n\n    int code = (int)key;\n    if (code >= '0' && code <= '9')\n    {\n        scancode = (code & 0xF) - 1;\n        if (scancode < 0)\n            scancode += 10;\n        scancode += KEY_1;\n    }\n    else if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z'))\n    {\n        static const uint16_t map[] = {\n            KEY_A, KEY_B, KEY_C, KEY_D, KEY_E,\n            KEY_F, KEY_G, KEY_H, KEY_I, KEY_J,\n            KEY_K, KEY_L, KEY_M, KEY_N, KEY_O,\n            KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T,\n            KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z};\n        scancode = map[(code & 0x5F) - 'A'];\n    }\n    else\n    {\n        switch (code)\n        {\n        case XK_space:          scancode = KEY_SPACE;   break;  //20\n        case XK_exclam:         scancode = KEY_1;       break;  //21\n        case XK_quotedbl:       scancode = KEY_APOSTROPHE; break; //22\n        case XK_numbersign:     scancode = KEY_3;       break;  //23\n        case XK_dollar:         scancode = KEY_4;       break;  //24\n        case XK_percent:        scancode = KEY_5;       break;  //25\n        case XK_ampersand:      scancode = KEY_7;       break;  //26\n        case XK_apostrophe:     scancode = KEY_APOSTROPHE; break; //27\n        case XK_parenleft:      scancode = KEY_9;       break;  //28\n        case XK_parenright:     scancode = KEY_0;       break;  //29\n        case XK_asterisk:       scancode = KEY_8;       break;  //2a\n        case XK_plus:           scancode = KEY_MINUS;   break;  //2b\n        case XK_comma:          scancode = KEY_EQUAL;   break;  //2c\n        case XK_minus:          scancode = KEY_MINUS;   break;  //2d\n        case XK_period:         scancode = KEY_DOT;     break;  //2e\n        case XK_slash:          scancode = KEY_SLASH;   break;  //2f\n        // XK_0 .. XK_9         // 30 .. 39\n        case XK_colon:          scancode = KEY_SEMICOLON; break; //3a\n        case XK_semicolon:      scancode = KEY_SEMICOLON; break; //3b\n        case XK_less:           scancode = KEY_COMMA;   break;  //3c\n        case XK_equal:          scancode = KEY_EQUAL;   break;  //3d\n        case XK_greater:        scancode = KEY_DOT;     break;  //3e\n        case XK_question:       scancode = KEY_SLASH;   break;  //3f\n        case XK_at:             scancode = KEY_2;       break;  //40\n        // XK_A .. XK_Z         // 41 .. 5a\n        case XK_bracketleft:    scancode = KEY_LEFTBRACE; break; //5b\n        case XK_backslash:      scancode = KEY_BACKSLASH; break; //5c\n        case XK_bracketright:   scancode = KEY_RIGHTBRACE; break; //5d\n        case XK_asciicircum:    scancode = KEY_6;       break;  //5e\n        case XK_underscore:     scancode = KEY_MINUS;   break;  //5f\n        case XK_grave:          scancode = KEY_GRAVE;   break;  //60\n        // XK_a .. XK_z         // 61 .. 7a\n        case XK_braceleft:      scancode = KEY_LEFTBRACE; break; //7b\n        case XK_bar:            scancode = KEY_BACKSLASH; break; //7c\n        case XK_braceright:     scancode = KEY_RIGHTBRACE; break; //7d\n        case XK_asciitilde:     scancode = KEY_GRAVE;   break;  //7e\n\n        case XK_BackSpace:      scancode = KEY_BACKSPACE;       break;  //ff08\n        case XK_Escape:         scancode = KEY_ESC;     break;  //ff1b\n        case XK_Tab:            scancode = KEY_TAB;     break;  //ff09\n        case XK_Return:         scancode = KEY_ENTER;   break;  //ff0d\n        case XK_F1:             scancode = KEY_F1;      break;  //ffbe\n        case XK_F2:             scancode = KEY_F2;      break;  //ffbf\n        case XK_F3:             scancode = KEY_F3;      break;  //ffc0\n        case XK_F4:             scancode = KEY_F4;      break;  //ffc1\n        case XK_F5:             scancode = KEY_F5;      break;  //ffc2\n        case XK_F6:             scancode = KEY_F6;      break;  //ffc3\n        case XK_F7:             scancode = KEY_F7;      break;  //ffc4\n        case XK_F8:             scancode = KEY_F8;      break;  //ffc5\n        case XK_F9:             scancode = KEY_F9;      break;  //ffc6\n        case XK_F10:            scancode = KEY_F10;     break;  //ffc7\n        //case XK_F11:          scancode = KEY_F11;     break;  //ffc8\n        case XK_F12:            scancode = KEY_F12;     break;  //ffc9\n        case XK_F11:\n            rfbShutdownServer(cl->screen, TRUE);\n            break;      //ffc8\n\n        case XK_Home:           scancode = KEY_HOME;    break;  //ff50\n        case XK_Left:           scancode = KEY_LEFT;    break;  //ff51\n        case XK_Up:             scancode = KEY_UP;      break;  //ff52\n        case XK_Right:          scancode = KEY_RIGHT;   break;  //ff53\n        case XK_Down:           scancode = KEY_DOWN;    break;  //ff54\n        case XK_Page_Up:        scancode = KEY_PAGEUP;  break;  //ff55\n        case XK_Page_Down:      scancode = KEY_PAGEDOWN; break; //ff56\n        case XK_End:            scancode = KEY_END;     break;  //ff57\n        case XK_Begin:          scancode = KEY_HOME;    break;  //ff58\n\n        case XK_Shift_L:        scancode = KEY_LEFTSHIFT; break; //ffe1\n        case XK_Shift_R:        scancode = KEY_RIGHTSHIFT; break; //ffe2\n        case XK_Control_L:      scancode = KEY_LEFTCTRL; break; //ffe3\n        case XK_Control_R:      scancode = KEY_RIGHTCTRL; break; //ffe4\n        case XK_Alt_L:          scancode = KEY_LEFTALT; break;  //ffe9\n        case XK_Alt_R:          scancode = KEY_RIGHTALT; break; //ffea\n        }\n    }\n\n    return scancode;\n}\n"
  },
  {
    "path": "src/keyboard.h",
    "content": "#pragma once\n\nint init_kbd(const char *);\nvoid cleanup_kbd();\n\nvoid injectKeyEvent(uint16_t, uint16_t);\nint keysym2scancode(rfbKeySym key, rfbClientPtr cl);\n"
  },
  {
    "path": "src/logging.h",
    "content": "#pragma once\n\n#define error_print(...)              \\\n    do                                \\\n    {                                 \\\n        fprintf(stderr, __VA_ARGS__); \\\n    } while (0)\n\n#define info_print(...)               \\\n    do                                \\\n    {                                 \\\n        fprintf(stderr, __VA_ARGS__); \\\n    } while (0)\n\nextern int verbose;\n\n#define debug_print(...)                  \\\n    do                                    \\\n    {                                     \\\n        if (verbose)                      \\\n            fprintf(stderr, __VA_ARGS__); \\\n    } while (0)\n"
  },
  {
    "path": "src/mouse.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <unistd.h>\n#include <sys/mman.h>\n#include <sys/ioctl.h>\n\n#include <sys/stat.h>\n#include <sys/sysmacros.h> /* For makedev() */\n\n#include <fcntl.h>\n#include <linux/fb.h>\n#include <linux/input.h>\n\n#include <assert.h>\n#include <errno.h>\n\n/* libvncserver */\n#include \"rfb/rfb.h\"\n\n#include \"mouse.h\"\n#include \"logging.h\"\n\n\nstatic int mousefd = -1;\n\nstatic int xmin, xmax;\nstatic int ymin, ymax;\nstatic int rotate;\nstatic int trkg_id = -1;\nstatic bool is_wheel_hires = false;\n\n#ifndef input_event_sec\n#define input_event_sec time.tv_sec\n#define input_event_usec time.tv_usec\n#endif\n\ntypedef struct\n{\n    const char *name;\n    const int value;\n} map_t;\n\n#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))\n#define MAP(x) { #x,x }\n#define WHEEL_UP 3\n#define WHEEL_DOWN 4\n\nint init_mouse(const char *touch_device, int vnc_rotate)\n{\n\tint size = (REL_CNT/32) + 1;\n\tunsigned int evtype_bitmask[size];\n\t/* Clean evtype_bitmask structure */\n\tmemset(evtype_bitmask, 0, sizeof(evtype_bitmask));\n\n    info_print(\"Initializing mouse device %s ...\\n\", touch_device);\n    struct input_absinfo info;\n    if ((mousefd = open(touch_device, O_RDWR)) == -1)\n    {\n        error_print(\"cannot open mouse device %s\\n\", touch_device);\n        return 0;\n    }\n\n\t//REL_WHEEL_HI_RES\n\tif (ioctl(mousefd, EVIOCGBIT(EV_REL, sizeof(evtype_bitmask)), evtype_bitmask) < 0) {\n\t\terror_print(\"%s  can't get evdev features: %s\",touch_device, strerror(errno));\n\t\treturn 0;\n\t}\n\n#ifdef REL_WHEEL_HI_RES\n\tint index = REL_WHEEL_HI_RES/32;\n    int offset = REL_WHEEL_HI_RES - (index*32);\n\tif(CHECK_BIT(evtype_bitmask[index],offset))\n\t{\n\t\tinfo_print(\"%s has hi res wheel.\\n\",touch_device);\n\t\tis_wheel_hires = true;\n\t}\n#endif \n\n    // Get the Range of X and Y\n    if (ioctl(mousefd, EVIOCGABS(ABS_X), &info))\n    {\n        error_print(\"cannot get ABS_X info, %s\\n\", strerror(errno));\n        return 0;\n    }\n    xmin = info.minimum;\n    xmax = info.maximum;\n    if (ioctl(mousefd, EVIOCGABS(ABS_Y), &info))\n    {\n        error_print(\"cannot get ABS_Y, %s\\n\", strerror(errno));\n        return 0;\n    }\n    ymin = info.minimum;\n    ymax = info.maximum;\n    rotate = vnc_rotate;\n\n    info_print(\"  x:(%d %d)  y:(%d %d) \\n\", xmin, xmax, ymin, ymax);\n    return 1;\n}\n\nvoid cleanup_mouse()\n{\n    if (mousefd != -1)\n    {\n        close(mousefd);\n    }\n}\n\nvoid injectMouseEvent(struct fb_var_screeninfo *scrinfo, int buttonMask, int x, int y)\n{\n    /* Indicates either pointer movement or a pointer button press or release. The pointer is\n    now at (x-position, y-position), and the current state of buttons 1 to 8 are represented\n    by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).\n    On a conventional mouse, buttons 1, 2 and 3 correspond to the left, middle and right\n    buttons on the mouse. On a wheel mouse, each step of the wheel upwards is represented\n    by a press and release of button 4, and each step downwards is represented by\n    a press and release of button 5.\n      From: http://www.vislab.usyd.edu.au/blogs/index.php/2009/05/22/an-headerless-indexed-protocol-for-input-1?blog=61 */\n    \n    static map_t mouseButtonMap[] = {\n        MAP(BTN_LEFT),\n        MAP(BTN_MIDDLE),\n        MAP(BTN_RIGHT),\n    };\n    static int buttonsNumber = sizeof(mouseButtonMap) / sizeof(mouseButtonMap[0]);\n    static int last_buttonMask;\n    static int last_x;\n    static int last_y;\n    static int wheel_tick;\n\tint last_wheel_tick = 0;\n    \n    \n    struct input_event ev;\n    int xin = x;\n    int yin = y;\n\n    switch (rotate)\n    {\n    case 90:\n        x = yin;\n        y = scrinfo->yres - 1 - xin;\n        break;\n    case 180:\n        x = scrinfo->xres - 1 - xin;\n        y = scrinfo->yres - 1 - yin;\n        break;\n    case 270:\n        x = scrinfo->xres - 1 - yin;\n        y = xin;\n        break;\n    }\n\n    // Calculate the final x and y\n    /* Fake touch screen always reports zero */\n    //???//if (xmin != 0 && xmax != 0 && ymin != 0 && ymax != 0)\n    {\n        x = xmin + (x * (xmax - xmin)) / (scrinfo->xres);\n        y = ymin + (y * (ymax - ymin)) / (scrinfo->yres);\n    }\n\n    memset(&ev, 0, sizeof(ev));\n    struct timeval time;\n\n    // Send buttons state\n    int buttonsChanged = last_buttonMask ^ buttonMask;\n    if (buttonsChanged)\n    {\n        for (int bi = 0; bi < buttonsNumber; bi++)\n        {\n            int isChanged = CHECK_BIT(buttonsChanged,bi);\n            int isPressed = CHECK_BIT(buttonMask,bi);\n\n            if(isChanged)\n            {\n                // Then send a BTN_* \n                gettimeofday(&time, 0);\n                ev.input_event_sec = time.tv_sec;\n                ev.input_event_usec = time.tv_usec;\n                ev.type = EV_KEY;\n                ev.code =  mouseButtonMap[bi].value;\n                ev.value = isPressed;\n                if (write(mousefd, &ev, sizeof(ev)) < 0)\n                {\n                    error_print(\"write event failed, %s\\n\", strerror(errno));\n                }\n                info_print(\"Button %s=%04X\\n\",mouseButtonMap[bi].name, mouseButtonMap[bi].value);\n            }\n        }\n        \n        if(CHECK_BIT(buttonMask,WHEEL_UP))\n        {\n            wheel_tick++;\n        }\n        else if(CHECK_BIT(buttonMask,WHEEL_DOWN))\n        {\n            wheel_tick--;\n        }\n\n        if(wheel_tick)\n        {\n            // Then send the WHEEL\n            gettimeofday(&time, 0);\n            ev.input_event_sec = time.tv_sec;\n            ev.input_event_usec = time.tv_usec;\n            ev.type = EV_REL;\n\t\t\tif(is_wheel_hires)\n\t\t\t{\n#ifdef REL_WHEEL_HI_RES\n\n\t\t\t\tinfo_print(\"HI RES WHEEL %d\\n\", wheel_tick);\n            \tev.code = REL_WHEEL_HI_RES;\n            \tev.value = wheel_tick*120;\n#endif \n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tinfo_print(\"WHEEL %d\\n\", wheel_tick);\n    \t        ev.code = REL_WHEEL;\n        \t    ev.value = wheel_tick;\n\t\t\t}\t\n            if (write(mousefd, &ev, sizeof(ev)) < 0)\n            {\n                error_print(\"write event failed, %s\\n\", strerror(errno));\n            }\n\t\t\tlast_wheel_tick = wheel_tick;\n            wheel_tick = 0;\n        }\n        last_buttonMask = buttonMask;\n    }\n\n    int dx = x - last_x;\n    int dy = y - last_y;\n\n    if (dx)\n    {\n        // Then send the X\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n        ev.input_event_usec = time.tv_usec;\n        ev.type = EV_ABS;\n        ev.code = ABS_X;\n        ev.value = x;\n        if (write(mousefd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n        last_x = x;\n    }\n\n    if(dy)\n    {\n        // Then send the Y\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n        ev.input_event_usec = time.tv_usec;\n        ev.type = EV_ABS;\n        ev.code = ABS_Y;\n        ev.value = y;\n        if (write(mousefd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n        last_y = y;\n    }\n\n    // Finally send the SYN\n    gettimeofday(&time, 0);\n    ev.input_event_sec = time.tv_sec;\n    ev.input_event_usec = time.tv_usec;\n    ev.type = EV_SYN;\n    ev.code = 0;\n    ev.value = 0;\n    if (write(mousefd, &ev, sizeof(ev)) < 0)\n    {\n        error_print(\"write event failed, %s\\n\", strerror(errno));\n    }\n    debug_print(\"injectMouseEvent (screen(%d,%d) -> mouse(%d,%d), button=%d, wheel tick=%d)\\n\", xin, yin, x, y, buttonMask, last_wheel_tick);\n}\n"
  },
  {
    "path": "src/mouse.h",
    "content": "#pragma once\n\nint init_mouse(const char *touch_device, int vnc_rotate);\nvoid cleanup_mouse();\nvoid injectMouseEvent(struct fb_var_screeninfo *scrinfo, int buttonMask, int x, int y);\n"
  },
  {
    "path": "src/touch.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <unistd.h>\n#include <sys/mman.h>\n#include <sys/ioctl.h>\n\n#include <sys/stat.h>\n#include <sys/sysmacros.h> /* For makedev() */\n\n#include <fcntl.h>\n#include <linux/fb.h>\n#include <linux/input.h>\n\n#include <assert.h>\n#include <errno.h>\n\n/* libvncserver */\n#include \"rfb/rfb.h\"\n\n#include \"touch.h\"\n#include \"logging.h\"\n\n//static char TOUCH_DEVICE[256] = \"/dev/input/event2\";\nstatic int touchfd = -1;\n\nstatic int xmin, xmax;\nstatic int ymin, ymax;\nstatic int rotate;\nstatic int trkg_id = -1;\n\n#ifndef input_event_sec\n#define input_event_sec time.tv_sec\n#define input_event_usec time.tv_usec\n#endif\n\nint init_touch(const char *touch_device, int vnc_rotate)\n{\n    info_print(\"Initializing touch device %s ...\\n\", touch_device);\n    struct input_absinfo info;\n    if ((touchfd = open(touch_device, O_RDWR)) == -1)\n    {\n        error_print(\"cannot open touch device %s\\n\", touch_device);\n        return 0;\n    }\n    // Get the Range of X and Y\n    if (ioctl(touchfd, EVIOCGABS(ABS_X), &info))\n    {\n        error_print(\"cannot get ABS_X info, %s\\n\", strerror(errno));\n        return 0;\n    }\n    xmin = info.minimum;\n    xmax = info.maximum;\n    if (ioctl(touchfd, EVIOCGABS(ABS_Y), &info))\n    {\n        error_print(\"cannot get ABS_Y, %s\\n\", strerror(errno));\n        return 0;\n    }\n    ymin = info.minimum;\n    ymax = info.maximum;\n    rotate = vnc_rotate;\n\n    info_print(\"  x:(%d %d)  y:(%d %d) \\n\", xmin, xmax, ymin, ymax);\n    return 1;\n}\n\nvoid cleanup_touch()\n{\n    if (touchfd != -1)\n    {\n        close(touchfd);\n    }\n}\n\nvoid injectTouchEvent(enum MouseAction mouseAction, int x, int y, struct fb_var_screeninfo *scrinfo)\n{\n    struct input_event ev;\n    int xin = x;\n    int yin = y;\n\n    switch (rotate)\n    {\n    case 90:\n        x = yin;\n        y = scrinfo->yres - 1 - xin;\n        break;\n    case 180:\n        x = scrinfo->xres - 1 - xin;\n        y = scrinfo->yres - 1 - yin;\n        break;\n    case 270:\n        x = scrinfo->xres - 1 - yin;\n        y = xin;\n        break;\n    }\n\n    // Calculate the final x and y\n    /* Fake touch screen always reports zero */\n    //???//if (xmin != 0 && xmax != 0 && ymin != 0 && ymax != 0)\n    {\n        x = xmin + (x * (xmax - xmin)) / (scrinfo->xres);\n        y = ymin + (y * (ymax - ymin)) / (scrinfo->yres);\n    }\n\n    memset(&ev, 0, sizeof(ev));\n\n    bool sendPos;\n    bool sendTouch;\n    int trkIdValue;\n    int touchValue;\n    struct timeval time;\n\n    switch (mouseAction)\n    {\n    case MousePress:\n        sendPos = true;\n        sendTouch = true;\n        trkIdValue = ++trkg_id;\n        touchValue = 1;\n        break;\n    case MouseRelease:\n        sendPos = false;\n        sendTouch = true;\n        trkIdValue = -1;\n        touchValue = 0;\n        break;\n    case MouseDrag:\n        sendPos = true;\n        sendTouch = false;\n        break;\n    default:\n        error_print(\"invalid mouse action\\n\");\n        exit(EXIT_FAILURE);\n    }\n\n    if (sendTouch)\n    {\n        // Then send a ABS_MT_TRACKING_ID\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n\n        ev.type = EV_ABS;\n        ev.code = ABS_MT_TRACKING_ID;\n        ev.value = trkIdValue;\n        if (write(touchfd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n\n        // Then send a BTN_TOUCH\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n        ev.input_event_usec = time.tv_usec;\n        ev.type = EV_KEY;\n        ev.code = BTN_TOUCH;\n        ev.value = touchValue;\n        if (write(touchfd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n    }\n\n    if (sendPos)\n    {\n        // Then send a ABS_MT_POSITION_X\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n        ev.input_event_usec = time.tv_usec;\n        ev.type = EV_ABS;\n        ev.code = ABS_MT_POSITION_X;\n        ev.value = x;\n        if (write(touchfd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n\n        // Then send a ABS_MT_POSITION_Y\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n        ev.input_event_usec = time.tv_usec;\n        ev.type = EV_ABS;\n        ev.code = ABS_MT_POSITION_Y;\n        ev.value = y;\n        if (write(touchfd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n\n        // Then send the X\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n        ev.input_event_usec = time.tv_usec;\n        ev.type = EV_ABS;\n        ev.code = ABS_X;\n        ev.value = x;\n        if (write(touchfd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n\n        // Then send the Y\n        gettimeofday(&time, 0);\n        ev.input_event_sec = time.tv_sec;\n        ev.input_event_usec = time.tv_usec;\n        ev.type = EV_ABS;\n        ev.code = ABS_Y;\n        ev.value = y;\n        if (write(touchfd, &ev, sizeof(ev)) < 0)\n        {\n            error_print(\"write event failed, %s\\n\", strerror(errno));\n        }\n    }\n\n    // Finally send the SYN\n    gettimeofday(&time, 0);\n    ev.input_event_sec = time.tv_sec;\n    ev.input_event_usec = time.tv_usec;\n    ev.type = EV_SYN;\n    ev.code = 0;\n    ev.value = 0;\n    if (write(touchfd, &ev, sizeof(ev)) < 0)\n    {\n        error_print(\"write event failed, %s\\n\", strerror(errno));\n    }\n    debug_print(\"injectTouchEvent (screen(%d,%d) -> touch(%d,%d), mouse=%d)\\n\", xin, yin, x, y, mouseAction);\n}\n"
  },
  {
    "path": "src/touch.h",
    "content": "#pragma once\n\nenum MouseAction\n{\n    MouseDrag = -1,\n    MouseRelease,\n    MousePress\n};\n\nint init_touch(const char *touch_device, int vnc_rotate);\nvoid cleanup_touch();\nvoid injectTouchEvent(enum MouseAction mouseAction, int x, int y, struct fb_var_screeninfo *scrinfo);\n"
  },
  {
    "path": "tests/vfb/Makefile",
    "content": "ifneq ($(KERNELRELEASE),)\nobj-m   := vfb.o\nelse\nKDIR    := /lib/modules/$(shell uname -r)/build\nPWD     := $(shell pwd)\nall:\n\t$(MAKE) -C $(KDIR) M=$(shell pwd) modules\ninstall:\n\t$(MAKE) -C $(KDIR) M=$(shell pwd) modules_install\n%:\n\t$(MAKE) -C $(KDIR) M=$(shell pwd) $@\nendif\n"
  },
  {
    "path": "tests/vfb/README",
    "content": "https://github.com/torvalds/linux/blob/v4.15/drivers/video/fbdev/vfb.c\n\nThis is a `virtual' frame buffer device. It operates on a chunk of\nunswappable kernel memory instead of on the memory of a graphics\nboard. This means you cannot see any output sent to this frame\nbuffer device, while it does consume precious memory. The main use\nof this frame buffer device is testing and debugging the frame\nbuffer subsystem. Do NOT enable it for normal systems! To protect\nthe innocent, it has to be enabled explicitly at boot time using the\nkernel option `video=vfb:'.\n"
  },
  {
    "path": "tests/vfb/ins.sh",
    "content": "#!/bin/sh\nmodinfo vfb.ko\nsudo modprobe fb_sys_fops\nsudo modprobe sysfillrect\nsudo modprobe syscopyarea\nsudo modprobe sysimgblt  \nsudo insmod vfb.ko vfb_enable=1 videomemorysize=32000000\n"
  },
  {
    "path": "vagrant.sh",
    "content": "#!/bin/bash\nexport DEBIAN_FRONTEND=noninteractive\nsudo update-locale LANG=en_US.UTF-8 LANGUAGE=en.UTF-8\n\n# tools\nsudo apt-get update\nsudo apt-get install -y mc htop\nsudo apt-get install -y evtest\nsudo apt-get install -y xvfb\nsudo apt-get install -y python3-pip\nsudo apt-get install -y libvncserver-dev\nsudo apt-get install -y build-essential flex bison\nsudo apt-get install -y cmake\nsudo apt-get install -y qt5-qmake\nsudo apt-get install -y qt5-qmake-bin\nsudo apt-get install -y qtbase5-dev\nsudo apt-get install -y linux-source libssl-dev libelf-dev\nsudo apt-get install -y fbset fbcat fbterm fbi\nsudo apt-get install -y qmlscene\nsudo apt-get install -y x11vnc\nsudo pip3 install entrypoint2\n\n# fb-test\ncd /home/vagrant\ngit clone https://github.com/ponty/fb-test-app.git\ncd fb-test-app\nmake\ncp perf /usr/local/bin\ncp rect /usr/local/bin\ncp fb-test /usr/local/bin\ncp fb-string /usr/local/bin\n\n# vfb\ncd /home/vagrant\ntar xaf /usr/src/linux-source-*.tar.*\n#cd linux-source-*/\nmkdir -p vfb && cd vfb\nln -s /home/vagrant/linux-source-*/drivers/video/fbdev/vfb.c vfb.c\nln -s /vagrant/tests/vfb/ins.sh ins.sh\nln -s /vagrant/tests/vfb/Makefile Makefile\nmake\n#./ins.sh\n\necho '#!/bin/bash\nmodinfo /home/vagrant/vfb/vfb.ko\nmodprobe fb_sys_fops\nmodprobe sysfillrect\nmodprobe syscopyarea\nmodprobe sysimgblt\ninsmod /home/vagrant/vfb/vfb.ko vfb_enable=1 videomemorysize=32000000\n  ' >/usr/local/bin/vfbload.sh\nchmod +x /usr/local/bin/vfbload.sh\n/usr/local/bin/vfbload.sh >/tmp/vfbload.log 2>&1\n\necho 'ENV{ID_INPUT_MOUSE}==\"?*\",ENV{ID_PATH}==\"pci-0000:00:04.0\", SYMLINK+=\"input/ms\"' >/etc/udev/rules.d/98-input.rules\necho 'ENV{ID_INPUT_KEYBOARD}==\"?*\", SYMLINK+=\"input/kbd\"' >>/etc/udev/rules.d/98-input.rules\nudevadm control --reload-rules\nudevadm trigger\n\necho 'SHELL=/bin/sh\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n@reboot   root    vfbload.sh;sleep 0.1;fbset -g 640 480 640 480 16;/home/vagrant/build/framebuffer-vncserver -t /dev/input/ms -k /dev/input/kbd > /tmp/framebuffer-vncserver.log 2>&1\n  ' >/etc/cron.d/framebuffer-vncserver\n\n# https://askubuntu.com/questions/168279/how-do-i-build-a-single-in-tree-kernel-module\n# https://askubuntu.com/questions/515407/how-recipe-to-build-only-one-kernel-module\n#cd /usr/src/\n#tar xaf linux-source-*.tar.*\n#cd linux-source-*/\n#make oldconfig # it copies .config to ./\n#echo 'CONFIG_FB_VIRTUAL=m' >>  .config\n#make scripts\n#make drivers/video/fbdev/vfb.ko\n\n# cmake build\ncd /home/vagrant\nmkdir -p build && cd build\ncmake /vagrant\nmake\n\n# qmake build\ncd /home/vagrant\nmkdir -p buildqt && cd buildqt\nqmake /vagrant\nmake\n\nfbset -g 640 480 640 480 16\n/home/vagrant/build/framebuffer-vncserver -t /dev/input/ms -k /dev/input/kbd >/tmp/framebuffer-vncserver.log 2>&1 &\n"
  },
  {
    "path": "vfb.py",
    "content": "import os\nimport sys\nimport threading\nimport time\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nfrom time import sleep\n\nimport fabric\nimport vagrant\nfrom entrypoint2 import entrypoint\nfrom PIL import Image, ImageChops\n\nfrom vncdotool import api\n\n# pip3 install fabric vncdotool python-vagrant entrypoint2\n\n\nprint(sys.version)\n\n\ndef build(conn):\n    # with c.cd(\"/home/vagrant/build\"): # bug in invoke: https://github.com/pyinvoke/invoke/issues/459\n    conn.sudo('sh -c \"cd /home/vagrant/build;cmake /vagrant\"')\n    conn.sudo('sh -c \"cd /home/vagrant/build;make\"')\n\n\ndef set_resolution(conn, *res):\n    (w, h, depth) = res\n    conn.sudo(\"fbset -g %s %s %s %s %s\" % (w, h, w, h, depth))\n\n\ndef run_in_background(conn, cmd):\n    # https://docs.fabfile.org/en/1.3.8/faq.html#why-can-t-i-run-programs-in-the-background-with-it-makes-fabric-hang\n\n    def thread_function(a):\n        conn.sudo(cmd, pty=False, warn=True)\n\n    x = threading.Thread(target=thread_function, args=(1,))\n    x.start()\n\n\ndef start_server(conn, rotation, res):\n    conn.sudo(\"killall framebuffer-vncserver\", warn=True)\n    command = f\"/home/vagrant/build/framebuffer-vncserver -r {rotation}\"\n    print(f\"command: {command}\")\n    run_in_background(conn, command)\n\n\ndef start_server_x11vnc(conn, rotation, res):\n    (w, h, depth) = res\n    conn.sudo(\"killall framebuffer-vncserver\", warn=True)\n    conn.sudo(\"killall x11vnc\", warn=True)\n    command = f\"/usr/bin/x11vnc  -shared -forever -rawfb map:/dev/fb0@{w}x{h}x{depth}\"\n    print(f\"command: {command}\")\n    run_in_background(conn, command)\n\n\ndef cls(conn):\n    conn.sudo(\"dd if=/dev/zero of=/dev/fb0\", warn=True)\n\n\ndef grab():\n    with TemporaryDirectory() as tmpdirname:\n        f = Path(tmpdirname) / \"grab.png\"\n        with api.connect(\"localhost:0\") as client:\n            client.timeout = 5\n            client.captureScreen(f)\n        im = Image.open(f)\n        return im\n\n\ndef _grab_and_sleep(blink_time):\n    start = time.time()\n    im = grab()\n    dt = time.time() - start\n    t = blink_time / 4.0 - dt\n    if t > 0:\n        sleep(t)\n    return im\n\n\ndef img_list_min(ls):\n    immin = ls[0]\n    for im in ls[1:]:\n        # ImageChops.subtract= max((a-b),0)\n        diff = ImageChops.subtract(immin, im)\n        immin = ImageChops.subtract(immin, diff)\n    return immin\n\n\ndef grab_no_blink(blink_time=1.2):\n    lsim = [_grab_and_sleep(blink_time) for _ in range(4)]\n    im = img_list_min(lsim)\n    return im\n\n\ndef shot(conn, directory, png, rotation, *res):\n    (w, h, depth) = res\n\n    set_resolution(conn, *res)\n    start_server(conn, rotation, res)\n\n    if depth != 8:\n        cls(conn)\n        run_in_background(conn, \"qmlscene -platform linuxfb\")\n        sleep(0.5)\n        grab_no_blink().save(directory + \"qmlscene_\" + png)\n        conn.sudo(\"killall qmlscene\")\n\n    if depth > 1:\n        cls(conn)\n        conn.sudo(\"fb-test\")\n        grab().save(directory + \"fbtest_\" + png)\n\n        cls(conn)\n        conn.sudo(\n            f\"python3 /vagrant/gradient.py --width {w} --height {h} --colorbit {depth}\"\n        )\n        grab().save(directory + \"gradient_\" + png)\n\n\nIMGDIR = \"img/\"\n\n\ndef tshot(conn, rotation, *res):\n    (w, h, depth) = res\n    fname = f\"{w}x{h}_c{depth}_rot{rotation}.png\"\n    shot(conn, IMGDIR, fname, rotation, *res)\n\n\nw, h = 160, 120\n\n\n@entrypoint\ndef main():\n    v = vagrant.Vagrant()\n    v.up()\n    with fabric.Connection(\n        v.user_hostname_port(),\n        connect_kwargs={\n            \"key_filename\": v.keyfile(),\n        },\n    ) as conn:\n        build(conn)\n        os.makedirs(IMGDIR, exist_ok=True)\n        for f in Path(IMGDIR).glob(\"*.png\"):\n            f.unlink()\n        conn.sudo(\"killall qmlscene\", warn=True)\n\n        for rot in [0]:\n            tshot(conn, rot, w, h, 1)\n            tshot(conn, rot, w, h, 8)\n            tshot(conn, rot, w, h, 16)\n            tshot(conn, rot, w, h, 24)\n            tshot(conn, rot, w, h, 32)\n        for rot in [90, 180, 270]:\n            tshot(conn, rot, w, h, 16)\n"
  },
  {
    "path": "yocto/framebuffer-vncserver_git.bb",
    "content": "DESCRIPTION = \"VNC server running on top of framebuffer\"\nHOMEPAGE = \"https://github.com/ponty/framebuffer-vncserver\"\nLICENSE = \"GPLv2\"\nDEPENDS = \"libvncserver\"\nRDEPENDS_${PN} = \"libvncserver\"\nSRC_URI = \"git://github.com/ponty/framebuffer-vncserver.git\"\nLIC_FILES_CHKSUM = \"file://LICENSE;md5=8264535c0c4e9c6c335635c4026a8022\"\nPR = \"r1\"\nPR_append = \"+gitr${SRCPV}\"\nS = \"${WORKDIR}/git\"\ninherit cmake\n\nSRCREV = \"d3450b1a5ba7ebd7c3b6bcf5affda0975441cee2\"\n\n"
  }
]