Software Development Kit

Recognising symbols drwan ion a pdf File

I have developed an Android app that uses PDFTron PDFNet SDK and I have added MyScript for performing hand drawn symbols but I can't seem to integrate these tools together. Is it possible to add other components on the MyScript widgets.Below is my Source code.

 

package com.myscript.atk.diagram.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.myscript.atk.geometry.widget.GeometryWidgetApi;
import com.myscript.certificate.MyCertificate;
import com.pdftron.common.Matrix2D;
import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.Element;
import com.pdftron.pdf.ElementBuilder;
import com.pdftron.pdf.ElementWriter;
import com.pdftron.pdf.Image;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.pdf.PDFNet;
import com.pdftron.pdf.PDFViewCtrl;
import com.pdftron.pdf.Page;
import com.pdftron.pdf.tools.ToolManager;
import com.pdftron.sdf.SDFDoc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;


/**
 * Created by Adriaan on 2016/07/15.
 */

public class AssessAndAnnotate extends Activity implements
        GeometryWidgetApi.OnConfigureListener,
        GeometryWidgetApi.OnRecognitionListener {
    private static final String TAG = "GeometryDemo";

    private GeometryWidgetApi widget;

    TextView QuestionNumber, MarkAllocation, stuName, stuNum, qText, qAnswer, markingMode, txtMarkingWords, moderationMarkTextView;
    //EditText stuAnswer;
    ImageButton btnRedHighlighter, btnSubtractMark, btnComment, btnPenMarking, btnRedo, previousQ, nextQ, btnPlus1; //btnMultiMark
    ImageButton removeCheckMark;
    private DBHelper lecturerDB;
    int questionIndex;
    ArrayList<Question> questions;
    boolean isPenMarkingActive;
    String curAnswerDir;
    boolean isMarkingQuestionAtAtime;
    Question curQuestion;
    ArrayList<Student> students;

    PDFViewCtrl mPDFViewCtrl;
    ToolManager TM;
    PDFDoc doc;
    Answer curAnswer;
    boolean isShowingInfo;
    boolean isCommenting;
    Student curStudent;

    /*SK*/
    boolean isModerator;

    private String folderForFeedbackFiles = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "MobileAssessmentToolPDFs" + File.separator;

    /***This method initializes PDFNet and sets the PDFDoc instance to null.
     * The method gets the intent which is used to determine whether the user is marking
     * in question or submission mode, if marks questions at a time then we get
     * the assignmentID of the selected assignment sent as an intent.
     *
     * If its on submission mode, the code extracts the submissionID from the intent.
     * and then assigns assID to the submission's id.
     *
     * isShowInfo is from the toggle button grants the user the option to show
     * questions and memo or not. Ig this is true, it use the layout file with
     * question and memo otherwise it will use the layout file with no question and memo.
     *
     * The method calls the initializeComponents method, to initialize UI elements and creates the instance
     * of a database.
     *
     * The method gets the list of questions form the database.
     *
     * Then the method checkingMarking style is invoked.
     *
     * */
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        try {
            /*Initializing the library*/
            PDFNet.initialize(this, R.raw.pdfnet);
            doc = null;
        } catch (PDFNetException e) {
            e.printStackTrace();
        }

        isMarkingQuestionAtAtime = (boolean) getIntent().getSerializableExtra("markingMode");
        Submission sub = null;
        final String assID;
        if (isMarkingQuestionAtAtime) {
            curQuestion = (Question) getIntent().getSerializableExtra("question");
            assID = curQuestion.getAssID();
        } else {
            sub = (Submission) getIntent().getSerializableExtra("submission");
            assID = sub.getAssID();
        }
        isCommenting = false;
        //sets the layout depending on if we are working by submission or question at a time/
        isShowingInfo = (boolean) getIntent().getSerializableExtra("showInfo");


        // Inflate the view and get a reference to PDFViewCtrl
        if (isShowingInfo)
            setContentView(R.layout.assessment_screen);
        else
            setContentView(R.layout.assessment_screen_no_info);

        initializeComponents();
        // lecturerDB = DBHelper.getDatabaseHelperInstance(this);
        lecturerDB = new DBHelper(this);
        curAnswerDir = "";
        questions = getListOfQuestionsFromDB(assID);
        ////////////////////////////////////////////////////////////////////////
        //////////////split up into question mode or submission mode////////////
        ////////////////////////////////////////////////////////////////////////
        checkMarkingStyle(sub, assID);

        nextQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveMarkToDB();
                if (TM.getTool().getMode() != 1 || TM.getTool().getMode() != 7) {
                    ToolManager.Tool tool = ToolManager.createDefaultTool();
                    ToolManager.setTool(tool);
                }


                if (isMarkingQuestionAtAtime) {
                    loadQuestionQuestionsAtATime(1, assID);
                } else {
                    loadQuestionSubmissionAtATime(1, assID, curStudent.getStudentNo(), curStudent.getStudentName());
                }
            }
        });

        previousQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveMarkToDB();
                if (TM.getTool().getMode() != 1 || TM.getTool().getMode() != 7) {
                    ToolManager.Tool tool = ToolManager.createDefaultTool();
                    ToolManager.setTool(tool);
                }
                if (isMarkingQuestionAtAtime) {
                    loadQuestionQuestionsAtATime(-1, assID);
                } else {
                    loadQuestionSubmissionAtATime(-1, assID, curStudent.getStudentNo(), curStudent.getStudentName());
                }
            }
        });

        btnRedo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(AssessAndAnnotate.this)
                        .setTitle("Reset PDF")
                        .setMessage("Are you sure you want to revert all changes to this answer?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                                if (isMarkingQuestionAtAtime) {
                                    loadAllViewInfoForQuestion(assID, curStudent.getStudentNo(), curStudent, true);
                                } else
                                    loadAllViewInfoForQuestion(assID, curStudent.getStudentNo(), null, true);


                            }
                        })
                        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // do nothing
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();

//                final Dialog dialog = new Dialog(getApplicationContext());
//                dialog.setContentView(R.layout.reset_pdf_dialog);
//                dialog.setTitle("Are you sure you want to reset this PDF to its original version?");
//                Button btnConfirmReset = (Button) dialog.findViewById(R.id.btnConfirmReset);
//                btnConfirmReset.setOnClickListener(new View.OnClickListener()
//                {
//                    @Override
//                    public void onClick(View v) {
//                        dialog.dismiss();
//                        if (isMarkingQuestionAtAtime) {
//                            ///curStudent = TStud;
//                            loadAllViewInfoForQuestion(assID, curStudent.getStudentNo(), curStudent, true);
//                        }
//                        else
//                            loadAllViewInfoForQuestion(assID,curStudent.getStudentNo(), null, true);
//                    }
//                });
//
//                Button btnCancelReset = (Button) dialog.findViewById(R.id.btnCancelReset);
//                btnCancelReset.setOnClickListener(new View.OnClickListener()
//                {
//                    @Override
//                    public void onClick(View v) {
//                        dialog.dismiss();
//                    }
//                });
//
//                dialog.show();
            }
        });
        otherButtonListeners();

        mPDFViewCtrl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (ToolManager.isRedHighlight)
                    btnRedHighlighter.setImageResource(R.drawable.redhighlighter);
                if (isCommenting) {
                    btnComment.setImageResource(R.drawable.comment);
                    isCommenting = false;
                }
                return false;
            }
        });

        performRemoveByButton();
    }

    /**
     * @param sub   the submission chosen from the list of submissions
     * @param assID the assignment id associated with a submission
     *              <p>
     *              Process: if the marking mode is Submission the we get the student number
     *              from the submission file.  Then we extract the student with this studNo
     *              curStudent: is a global instance of Student. Its assigned to
     *              the student returned from the database.
     *              <p>
     *              Question Index:
     *              <p>
     *              Then we initialise mPDFViewCtrl and initialises the ToolManager instance TM.
     *              then setToolManager of mPDFViewCtrl is invoked and passed the TM
     *              instance
     */
    private void checkMarkingStyle(Submission sub, String assID) { /*m1*/
        if (!isMarkingQuestionAtAtime) {
            final int studentNum = sub.getStdNo();
            Cursor cursor = lecturerDB.getStudent(studentNum);
            curStudent = parseStudent(cursor);
            questionIndex = 0;
            mPDFViewCtrl = (PDFViewCtrl) findViewById(R.id.pdfdrawview);
            TM = new ToolManager(mPDFViewCtrl, this, assID, MarkAllocation, moderationMarkTextView, removeCheckMark);
            mPDFViewCtrl.setToolManager(TM);
            loadAllViewInfoForQuestion(assID, studentNum, null, false);

            stuNum.setText("Student Number: " + String.valueOf(studentNum).toString());
            stuName.setText("Student Name: " + curStudent.getStudentName().toString());
        } else {
            students = getListOfStudents(assID);
            questionIndex = 0;
            curStudent = students.get(questionIndex);
            final int studentNum = curStudent.getStudentNo();
            mPDFViewCtrl = (PDFViewCtrl) findViewById(R.id.pdfdrawview);
            TM = new ToolManager(mPDFViewCtrl, this, assID, MarkAllocation, moderationMarkTextView, removeCheckMark);
            mPDFViewCtrl.setToolManager(TM);
            /*--------------------SK:-----------------------*/
            isModerator = getIntent().getBooleanExtra("moderator", false);
            System.out.println(isModerator);
            ToolManager.isModerator = isModerator;
        /*-------------------------------------------*/


//            Cursor cursor = lecturerDB.getStudent(curStudent.getStudentNo());
            //sub = parseSubmission(cursor);
            loadAllViewInfoForQuestion(assID, curStudent.getStudentNo(), curStudent, false);
            stuNum.setText("Student Number: " + String.valueOf(curStudent.getStudentNo()).toString());
            stuName.setText("Student Name: " + curStudent.getStudentName().toString());
        }
    }


    /**
     * @param assID         the ID of an Assignment
     * @param studentNumber the student number of the student who wrote the assignment
     * @param cStudent      the student who wrote the assignment
     * @param isResetting   boolean variable used to reset the pdf.
     *                      <p>
     *                      The method checks if doc is not equal to null and the boolean isResetting is also null.
     *                      If these logical conditions are true then the method invokes the saveCurrentPDF method.
     *                      <p>
     *                      The method checks whether the person is not marking 1 question at a time, if this hold then
     *                      The method checks whether the person is not marking 1 question at a time, if this hold then
     *                      the curQuestion instance is assigned to the question at index 0. This means that when you open the
     *                      submission, the first question will always be the first 1 to mark.
     *                      <p>
     *                      Otherwise, the method takes uses curQuestion to get the question from
     *                      the database. The JSONFileLoc for the curQuestion is set to the one extracted
     *                      from the database. the Question instance q, is assigned to curQuestion (curQuestion has a value
     *                      equal to the item clicked on main activity). We then set the name and student number
     *                      of a student.
     *                      <p>
     *                      The Answer instance curAnswer is assigned to the answer extracted from the database
     *                      <p>
     *                      The method then reads the JSON file then creates the JSONQuestionConverter instance
     *                      The method proceeds to set the question text and answer for the instance.
     *                      <p>
     *                      The method sets the question number, mark allocated by assessor and the mark allocated by moderator.
     */
    public void loadAllViewInfoForQuestion(String assID, int studentNumber, Student cStudent, boolean isResetting) { /*m2*/
        //save currently open question
        if (doc != null && !isResetting) {
            saveCurrentPDF(curAnswerDir);
        }

        final Question q;
        if (!isMarkingQuestionAtAtime) {
            q = questions.get(questionIndex);
            curQuestion = q;
        } else {
            Cursor cursor = lecturerDB.getQuestion(curQuestion.getqPK());  /*curQuestion is a Question instance attained from an intent.
                                                                            When user clicks on the list view of questions on the Main
                                                                             Activity*/
            Question tempQ = parseQuestion(cursor);
            curQuestion.setJSONFileLoc(tempQ.getJSONFileLoc());
            q = curQuestion;
            stuNum.setText(String.format("Student Number: %s", String.valueOf(cStudent.getStudentNo()).toString()));
            stuName.setText(String.format("Student Name: %s", cStudent.getStudentName().toString()));
        }
        TM.setQuestionNo(q.getqNumber());
        Cursor cursorAnswer = lecturerDB.getAnswer(studentNumber, assID, q.getqNumber());
        curAnswer = parseAnswer(cursorAnswer);

        jsonQuestionConverter ques;
        try {
            ObjectMapper mapper = new ObjectMapper();
            ques = mapper.readValue(new File(q.getJSONFileLoc()), jsonQuestionConverter.class);
            ques.setqAnswer(ques.getqAnswer().replace("&#123;", "{"));
            ques.setqAnswer(ques.getqAnswer().replace("&#125;", "}"));
            ques.setQuestion(ques.getQuestion().replace("&#123;", "{"));
            ques.setQuestion(ques.getQuestion().replace("&#125;", "}"));

            if (isShowingInfo) {
                qAnswer.setText(ques.getqAnswer());
                qText.setText(ques.getQuestion());
            }


            QuestionNumber.setText("Question " + q.getqNumber().replace(")", "."));
            MarkAllocation.setText(curAnswer.getMarkReceived() + "/" + String.valueOf(q.getMarkAllocation()));
            moderationMarkTextView.setText(curAnswer.getModeratedMarkReceived() + "/" + String.valueOf(q.getMarkAllocation()));

            String loadPath = checkForAnnotatedSubmission(curAnswer.getJSONFileLoc(), q.getqNumber());
            if (isResetting && !loadPath.equals(curAnswer.getJSONFileLoc())) {  /*This is the case whereby an absolute path of the marked file is returned*/
                String delPath = loadPath;
                loadPath = curAnswer.getJSONFileLoc();
                doc = new PDFDoc(loadPath);
                curAnswerDir = curAnswer.getJSONFileLoc();
                mPDFViewCtrl.setDoc(doc);
                curAnswer.setHasBeenMarked(false);
                curAnswer.setMarkReceived("0");

                /*--------------Moderation Setup--------------*/
                curAnswer.setModeratedMarkReceived("0");
                curAnswer.setToBeModerated(false);
                curAnswer.setHasBeenModerated(false);
                /*--------------Moderation Setup--------------*/
                lecturerDB.updateAnswer(curAnswer.getAssID(), curAnswer.getStudentNo(), curAnswer.getQuestionNumber(),
                        curAnswer.getMarkReceived(), 0, curAnswer.getJSONFileLoc(), curAnswer.getModeratedMarkReceived(),
                        0, 0);
                MarkAllocation.setText(curAnswer.getMarkReceived() + "/" + String.valueOf(q.getMarkAllocation()));
                moderationMarkTextView.setText(curAnswer.getModeratedMarkReceived() + "/" + String.valueOf(q.getMarkAllocation()));
                boolean isDeleted = deletePDF(delPath);
                if (isDeleted) {
                    showToastLong("File successfully reset");
                }
            } else {


                /*=============== ADDING IMAGE ===============================*/

                doc = new PDFDoc(loadPath); /*Open an existing PDF document.*/
                ImageDetails imageDetails = lecturerDB.getImageForAnswer(curAnswer.getStudentNo(), Integer.valueOf(curAnswer.getAssID()), curAnswer.getQuestionNumber());
                if (imageDetails != null) {
                    Log.d("ImageTest", "Image - Answer ==> img Question Number: " + imageDetails.getQuestionNumber() + " Answer Question Number: " +
                            curAnswer.getQuestionNumber() + " Image studNo: " + imageDetails.getStudentNumber() + "Answer studNo: " + curAnswer.getStudentNo());

                    ElementBuilder f = new ElementBuilder();
                    ElementWriter writer = new ElementWriter();

               //     List<Page> pages = (List<Page>) doc.getPages();
                    String TAG = "crtlPages";
                    int pageIndex = questionIndex + 1;
                    Log.d(TAG, "page instance: " + doc.getPageCount() );
                    if(pageIndex<=doc.getPageCount()) {
                        Page page = doc.getPage(pageIndex); //Page number for an Answer!!!!1

                        Log.d(TAG, "Number of pages: " + pageIndex );
                        Log.d(TAG, "page instance: " + page.getIndex() );
                        writer.begin(page);

                        Image image = Image.create(doc.getSDFDoc(), imageDetails.getImageLocation());
                        Element element = f.createImage(image, new Matrix2D(200, 0, 0, 250, 50, mPDFViewCtrl.getHeight()));
                        //writer.writeElement(element);
                        writer.writePlacedElement(element);
                        writer.end();
                        // doc.save(folderForFeedbackFiles+"K.pdf",SDFDoc.e_linearized,null);
                        //   doc.close();

                        File file = new File(imageDetails.getImageLocation());
                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                    }
                }
                curAnswerDir = curAnswer.getJSONFileLoc();

                mPDFViewCtrl.setDoc(doc);
            }
            ToolManager.scalePDFZoom();
        } catch (PDFNetException | IOException e) {
            e.printStackTrace();
        }

//        btnMultiMark.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View v) {
//                if (isPenMarkingActive)
//                    deactivateMarking();
//                multimark(q);
//            }
//        });

        btnPlus1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPenMarkingActive)
                    deactivateMarking();
                addMark();
            }
        });

        txtMarkingWords.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPenMarkingActive)
                    deactivateMarking();
                multimark(q);
            }
        });
        MarkAllocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPenMarkingActive)
                    deactivateMarking();
                multimark(q);
            }
        });
    }

    /**
     * @param jsonFileLoc the location for a submitted file.
     *                    /storage/emulated/0/MobileAssessmentToolPDFs/JSONFiles/1/singleSubmissions/212289047/1)1.pdf
     *                    This location stores the location of a singleAnswer file by a student
     * @param qNo         the question number for that submission
     *                    <p>
     *                    Process: This method creates file that takes the path of the JSOnFileLoc.The
     *                    parent of the file is retrieved and from then on a list of
     *                    files on the parent are stored on an array.
     *                    the array is then iterated and a check is made for files that contain the work MARKED and a check
     *                    of whether the question number e.g 1)1 matches. If this is true then the absolute path of that string is returned
     * @return A string path of the marked file
     */
    private String checkForAnnotatedSubmission(String jsonFileLoc, String qNo) { /*m3*/
        String out = jsonFileLoc;
        File f = new File(out);
        String dir = f.getParent();
        f = new File(dir);
        File[] files = f.listFiles();
        for (File ff : files) {
            if ((ff.getName().contains("-MARKED")) && (ff.getName().contains(qNo))) {
                return ff.getAbsolutePath();
            }
        }
        return out;
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (doc != null) {
            saveCurrentPDF(curAnswerDir);
        }
        saveMarkToDB();
        showToastShort("Question Saved");

        // Although not good, it clears the memory.
        finish();
        System.exit(1);
        //  TM.setMannotToNull();

    }

    private void loadQuestionQuestionsAtATime(int updowncenter, String assID) {
        if (updowncenter == 1) {
            //load the same question from the next submission
            questionIndex++;
            if (questionIndex == students.size()) {
                showToastLong("Done marking all of question: " + curQuestion.getqNumber());
                if (doc != null) {
                    saveCurrentPDF(curAnswerDir);
                }
                finish();
            } else {
                curStudent = students.get(questionIndex);
                loadAllViewInfoForQuestion(assID, curStudent.getStudentNo(), curStudent, false);
            }
        } else if (updowncenter == -1) {
            questionIndex--;
            if (questionIndex == -1) {
                showToastShort("This is the first submission for this question");
                questionIndex++;
            } else {
                curStudent = students.get(questionIndex);
                loadAllViewInfoForQuestion(curQuestion.getAssID(), curStudent.getStudentNo(), curStudent, false);
            }
        }
    }

    public void loadQuestionSubmissionAtATime(int updowncenter, String assID, int sNo, String sName) {
        if (updowncenter == -1 && questionIndex == 0) //check: cannot go back on a question that is at the start already
            showToastShort("No Previous Question");
        else if (updowncenter == 1 && questionIndex == questions.size() - 1) {
            showToastLong("Finished Marking Student: " + sName);
            if (doc != null) {
                saveCurrentPDF(curAnswerDir);
            }
            finish();
        } else //the loading of the question is valid
        {
            questionIndex = questionIndex + updowncenter; //update the question counter
            loadAllViewInfoForQuestion(assID, sNo, null, false);
        }
    }

    private boolean deletePDF(String delPath) {
        File file = new File(delPath);
        return file.delete();
    }

    private void otherButtonListeners() {
        btnRedHighlighter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPenMarkingActive)
                    deactivateMarking();
                if (isCommenting) {
                    isCommenting = false;
                    btnComment.setImageResource(R.drawable.comment);
                }
                if (!ToolManager.isRedHighlight) {
                    btnRedHighlighter.setImageResource(R.drawable.selected_redhighlighter);
                    ToolManager.activateRedHighlight();
                } else {
                    ToolManager.isRedHighlight = false;
                    ToolManager.Tool tool = ToolManager.createDefaultTool();
                    ToolManager.setTool(tool);
                    btnRedHighlighter.setImageResource(R.drawable.redhighlighter);
                }
            }
        });
        btnPenMarking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCommenting) {
                    isCommenting = false;
                    btnComment.setImageResource(R.drawable.comment);
                }
                if (ToolManager.isRedHighlight) {
                    ToolManager.isRedHighlight = false;
                    btnRedHighlighter.setImageResource(R.drawable.redhighlighter);
                }

                if (isPenMarkingActive == false) {
                    isPenMarkingActive = true;
                    ToolManager.isPenMarkActive = true;
                    btnPenMarking.setImageResource(R.drawable.selected_penmark);
                    ToolManager.activatePenMarking();

                } else {
                    isPenMarkingActive = false;
                    ToolManager.isPenMarkActive = false;
                    btnPenMarking.setImageResource(R.drawable.penmark);
                    ToolManager.Tool tool = ToolManager.createDefaultTool();
                    ToolManager.setTool(tool);
                }
            }
        });
//        btnGreenhighlighter.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View v)
//            {
//                if (isPenMarkingActive)
//                    deactivateMarking();
//                TM.activateFingerHighlighter();
//            }
//        });
        btnSubtractMark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPenMarkingActive)
                    deactivateMarking();
                subtractMark();
            }
        });
        btnComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPenMarkingActive)
                    deactivateMarking();
                if (ToolManager.isRedHighlight) {
                    ToolManager.isRedHighlight = false;
                    btnRedHighlighter.setImageResource(R.drawable.redhighlighter);
                }

                if (!isCommenting) {
                    btnComment.setImageResource(R.drawable.selected_comment);
                    ToolManager.Tool tool = ToolManager.createTool(8, ToolManager.mTool);
                    ToolManager.setTool(tool);
                    isCommenting = true;
                } else {
                    btnComment.setImageResource(R.drawable.comment);
                    ToolManager.Tool tool = ToolManager.createDefaultTool();
                    ToolManager.setTool(tool);
                    isCommenting = false;
                }
            }
        });
    }

    private void saveMarkToDB() {
        String markReceived = MarkAllocation.getText().toString();
        String[] parts = markReceived.split("/");
        int originalMark = Integer.parseInt(parts[0]);
        curAnswer.setMarkReceived(String.valueOf(originalMark));
        curAnswer.setHasBeenMarked(true);


        /*-----Saving Moderated Mark----*/
        String moderatedMarkReceived = moderationMarkTextView.getText().toString();
        String[] modParts = moderatedMarkReceived.split("/");
        int modOriginalMark = Integer.parseInt(modParts[0]);
        curAnswer.setModeratedMarkReceived(String.valueOf(modOriginalMark));
        curAnswer.setHasBeenModerated(true);
        curAnswer.setToBeModerated(true); /*To be reviewed*/

        /*-----Saving Moderated Mark----*/

        if (!isMarkingQuestionAtAtime)
            lecturerDB.updateAnswer(curAnswer.getAssID(), curAnswer.getStudentNo(), curAnswer.getQuestionNumber(), curAnswer.getMarkReceived(),
                    1, curAnswer.getJSONFileLoc(), curAnswer.getModeratedMarkReceived(), 1, 1);
        else
            lecturerDB.updateAnswer(curAnswer.getAssID(), curAnswer.getStudentNo(), curAnswer.getQuestionNumber(),
                    curAnswer.getMarkReceived(), 1, curAnswer.getJSONFileLoc(), curAnswer.getModeratedMarkReceived(), 1, 1);

        Cursor cursor = lecturerDB.getAssignment(curAnswer.getAssID());
        Assignment curAss = parseAssignment(cursor);
        curAss.setNoMarked((curAss.getNoMarked() + 1));
        lecturerDB.updateAssignment(curAss.getAssignmentID(), curAss.getAssignmentName(), curAss.getAssignmentSubject(), curAss.getAssignmentStatus(), curAss.getNoQuestions(), curAss.getNoMarked(), curAss.getNoSubmissions(), curAss.getTotalMarksOutOf());
    }

    private void deactivateMarking() {
        isPenMarkingActive = false;
        ToolManager.isPenMarkActive = false;
        btnPenMarking.setImageResource(R.drawable.penmark);
        ToolManager.Tool tool = ToolManager.createDefaultTool();
        ToolManager.setTool(tool);
    }


    /**
     * @param curAnswerDir the directory to student answer.
     */
    private void saveCurrentPDF(String curAnswerDir) {
        String[] parts = curAnswerDir.split("\\.(?=[^\\.]+$)");
        //String[] parts = curAnswerDir.split(".");
        String annotDir = parts[0] + "-MARKED";
        String newDir = annotDir + "." + parts[1];
        try {
            //doc.flattenAnnotations();
            doc.save(newDir, SDFDoc.e_linearized, null);
        } catch (PDFNetException e) {
            e.printStackTrace();
        }
    }

    private void subtractMark() {


        if (!isModerator) {
            String markReceived = MarkAllocation.getText().toString();
            String[] parts = markReceived.split("/");
            int originalMark = Integer.parseInt(parts[0]);
            int outOfMark = Integer.parseInt(parts[1]);
            if (originalMark == 0)
                showToastShort("Cannot give less than 0 Marks");
            else {
                int newMark = originalMark - 1;
                if (newMark <= 0)
                    newMark = 0;
                MarkAllocation.setText(newMark + "/" + outOfMark);
            }
        } else {
            if (curAnswer.isHasBeenMarked()) {
                String markReceived = moderationMarkTextView.getText().toString();
                String[] parts = markReceived.split("/");
                int originalMark = Integer.parseInt(parts[0]);
                int outOfMark = Integer.parseInt(parts[1]);
                if (originalMark == 0)
                    showToastShort("Cannot give less than 0 Marks");
                else {
                    int newMark = originalMark - 1;
                    if (newMark <= 0)
                        newMark = 0;
                    moderationMarkTextView.setText(newMark + "/" + outOfMark);
                }

            } else {
                showToastLong("Question not yet Marked!");
            }
        }
    }

    /**
     * Increments a mark for a given submission
     */
    private void addMark() {
        String markRecieved = MarkAllocation.getText().toString();


        String[] parts = markRecieved.split("/");
        int origialMark = Integer.parseInt(parts[0]);
        int outOfMark = Integer.parseInt(parts[1]);

        ToolManager.myOriginal = outOfMark;
        ToolManager.received = origialMark;

        /*=====SK=====*/
        String moderated = moderationMarkTextView.getText().toString();
        String[] modParts = moderated.split("/");
        int moderatedMark = Integer.parseInt(modParts[0]);
        int finalModeratedMark = Integer.parseInt(modParts[1]);
          /*=====SK=====*/

        if (!isModerator) {
            if (origialMark == outOfMark)
                showToastShort("Cannot give more than " + outOfMark + " marks");
            else {
                int newMark = origialMark + 1;
                if (newMark <= 0)
                    newMark = 0;
                //MarkAllocation.setText(markRecieved.substring(0, 2).replace(String.valueOf(origialMark), String.valueOf(newMark)) + markRecieved.substring(2, markRecieved.length()));
                MarkAllocation.setText(newMark + "/" + outOfMark);
            }

        }
           /*=====SK=====*/
        else if (curAnswer.isHasBeenMarked()) {

            if (moderatedMark == finalModeratedMark)
                showToastShort("Cannot give more than " + finalModeratedMark + " marks");
            else {
                int newMark = moderatedMark + 1;
                if (newMark <= 0)
                    newMark = 0;
                moderationMarkTextView.setText(newMark + "/" + outOfMark);
            }
        } else {
            showToastLong("Question not yet Marked!");
        }
           /*=====SK=====*/

    }

    public void showToastShort(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public void showToastLong(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    public String loadJSONfromFile(String path) {
        String json = "";

        try {
            File file = new File(path);
            BufferedReader br = new BufferedReader(new FileReader(file));
            StringBuilder text = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
            }
            br.close();
            json = text.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    //In: nothing
    //Process: query the DB for all of the assignments
    //Output: an arraylist of all of the assignments in the DB
    public ArrayList<Assignment> getListOfAssignmentsFromDB() {
        ArrayList<Assignment> listOfAssignmentsFromDB = new ArrayList<Assignment>();
        //Cursor cursor = lecturerDB.rawQuery("SELECT * FROM assignment", null);
        Cursor cursor = lecturerDB.getAssignments();
        if (cursor.getCount() == 0) {
            //showToastShort("No Assignments Found, Looking for new Assignments now");
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                Assignment assignment = parseAssignment(cursor);
                listOfAssignmentsFromDB.add(assignment);
                cursor.moveToNext();
            }
        }
        return listOfAssignmentsFromDB;
    }

    private Assignment parseAssignment(Cursor cursor) {
        Assignment assignment = new Assignment("", "", "", "", 0, 0, 0, 0);
        if (cursor.getCount() == 0) {
            //showToastShort("No Assignments Found, Looking for new Assignments now");
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                assignment.setAssignmentID(cursor.getString(0));
                assignment.setAssignmentName(cursor.getString(1));
                assignment.setAssignmentSubject(cursor.getString(2));
                assignment.setAssignmentStatus(cursor.getString(3));
                assignment.setNoQuestions(cursor.getInt(4));
                assignment.setNoMarked(cursor.getInt(5));
                assignment.setNoSubmissions(cursor.getInt(6));
                assignment.setTotalMarksOutOf(cursor.getInt(7));
                return assignment;
            }
        }
        return assignment;
    }

    public ArrayList<Question> getListOfQuestionsFromDB(String aID) {
        ArrayList<Question> listOfQuestionsFromDB = new ArrayList<Question>();
        Cursor cursor = lecturerDB.getQuestions(aID);
        if (cursor.getCount() == 0) {
            //showToastShort("No Assignments Found, Looking for new Assignments now");
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                Question q = new Question("", "", "", "", "", "", 0);//parseQuestion(cursor);
                q.setqPK(cursor.getString(0));
                q.setqNumber(cursor.getString(1));
                q.setMarkAllocation(cursor.getInt(2));
                q.setJSONFileLoc(cursor.getString(3));
                q.setAssID(String.valueOf(cursor.getInt(4)));
                listOfQuestionsFromDB.add(q);
                cursor.moveToNext();
            }
        }
        return listOfQuestionsFromDB;
    }

    private Question parseQuestion(Cursor cursor) {
        Question q = new Question("", "", "", "", "", "", 0);
        if (cursor.getCount() == 0) {
            //showToastShort("No Assignments Found, Looking for new Assignments now");
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                q.setqPK(cursor.getString(0));
                q.setqNumber(cursor.getString(1));
                q.setMarkAllocation(cursor.getInt(2));
                q.setJSONFileLoc(cursor.getString(3));
                return q;
            }
        }
        return q;
    }

    private ArrayList<Student> getListOfStudents(String assID) {
        ArrayList<Student> out = new ArrayList<>();
        Cursor cursor = lecturerDB.getStudents(assID);
        if (cursor.getCount() == 0) {
            return out;
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                Student stu = new Student(0, "", "");
                stu.setStudentNo(cursor.getInt(0));
                stu.setStudentName(cursor.getString(1));
                stu.setStudentEmailAdress(cursor.getString(2));
                out.add(stu);
                cursor.moveToNext();
            }
        }
        return out;
    }

    private Student parseStudent(Cursor cursor) {
        Student stu = new Student(12321, "Sibu", "");
        if (cursor.getCount() == 0) {
            //showToastShort("No Assignments Found, Looking for new Assignments now");
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                stu.setStudentNo(cursor.getInt(0));
                stu.setStudentName(cursor.getString(1));
                stu.setStudentEmailAdress(cursor.getString(2));
                return stu;
            }
        }
        return stu;
    }

    /**
     * Just getting Answer field values stored in the database
     */
    private Answer parseAnswer(Cursor cursor) {
        Answer a = new Answer("", 0, "", "", false, "", "", "0", false, false);

        if (cursor.getCount() == 0) {
            //showToastShort("No Assignments Found, Looking for new Assignments now");
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                a.setStudentNo(cursor.getInt(0));
                a.setAssID(cursor.getString(1));
                a.setQuestionNumber(cursor.getString(2));
                a.setMarkReceived(cursor.getString(3));
                int temp = cursor.getInt(4); //Has been Marked?
                boolean trueFalse = false;
                if (temp == 1)
                    trueFalse = true;
                a.setHasBeenMarked(trueFalse);
                ToolManager.hasBeenMarked = trueFalse;
                a.setJSONFileLoc(cursor.getString(5));


                String moderatedMark = cursor.getString(6);
                if (moderatedMark == null) {
                    a.setModeratedMarkReceived("0");
                } else
                    a.setModeratedMarkReceived(moderatedMark); /*It could be extracting a null*/
                return a;
            }
        }
        return a;
    }

    private Submission parseSubmission(Cursor cursor) {
        Submission sub = new Submission("", 0, "", 0);
        if (cursor.getCount() == 0) {
            //showToastShort("No Assignments Found, Looking for new Assignments now");
        } else {
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                sub.setAssID(cursor.getString(0));
                sub.setStdNo(cursor.getInt(1));
                sub.setJSONFileLoc(cursor.getString(2));
                sub.setFinalMark(cursor.getInt(3));
                cursor.moveToNext();
            }
        }

        return sub;
    }

    public static void disableSoftInputFromAppearing(EditText editText) {
//        if (Build.VERSION.SDK_INT >= 11) {
//            editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
//            editText.setTextIsSelectable(true);
//        } else {
//            editText.setRawInputType(InputType.TYPE_NULL);
//            editText.setFocusable(true);
//        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            editText.setShowSoftInputOnFocus(false);
        } else {
            try {
                final Method method = EditText.class.getMethod(
                        "setShowSoftInputOnFocus"
                        , boolean.class);
                method.setAccessible(true);
                method.invoke(editText, false);
            } catch (Exception e) {
                // ignore
            }
        }
    }


    /**
     * This method initializes the UI components
     */

    private void initializeComponents() {
        widget = (GeometryWidgetApi) findViewById(R.id.geometry_widget);
        if (!widget.registerCertificate(MyCertificate.getBytes()))
        {
            android.support.v7.app.AlertDialog.Builder dlgAlert  = new android.support.v7.app.AlertDialog.Builder(this);
            dlgAlert.setMessage("Please use a valid certificate.");
            dlgAlert.setTitle("Invalid certificate");
            dlgAlert.setCancelable(false);
            dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int which)
                {
                    //dismiss the dialog
                }
            });
            dlgAlert.create().show();
            return;
        }

        // Listen to widget events (see onConfigurationBegin and onRecognitionEnd APIs)
        widget.setOnConfigureListener(this);
        widget.setOnRecognitionListener(this);

        // references assets directly from the APK to avoid extraction in application
        // file system
        widget.addSearchDir("zip://" + getPackageCodePath() + "!/assets/conf");

        // The configuration is an asynchronous operation. Callbacks are provided to
        // monitor the beginning and end of the configuration process and update the UI
        // of the input method accordingly.
        //
        // "shape" references the shape bundle name in conf/shape.conf file in your assets.
        // "standard" references the configuration name in shape.conf
        widget.configure("shape", "standard");

        txtMarkingWords = (TextView) findViewById(R.id.txtMarksWord);
        //markingMode = (TextView) findViewById(R.id.markingMode);
        QuestionNumber = (TextView) findViewById(R.id.txtQuestionNo);
        MarkAllocation = (TextView) findViewById(R.id.txtMarks);
        moderationMarkTextView = (TextView) findViewById(R.id.txtMarksMod);
        removeCheckMark = (ImageButton) findViewById(R.id.rmvCm);
        stuName = (TextView) findViewById(R.id.txtName);
        stuNum = (TextView) findViewById(R.id.txtStudentNo);
        //stuAnswer = (TextView) findViewById(R.id.txtStudentAnswerToQuestion);
        if (isShowingInfo) {
            qText = (TextView) findViewById(R.id.txtQuestionPreview);
            qAnswer = (TextView) findViewById(R.id.txtMemo);
        }


//        if (isMarkingQuestionAtAtime)
//            markingMode.setText("QUESTION");

        previousQ = (ImageButton) findViewById(R.id.btnPreviousQuestion);
        nextQ = (ImageButton) findViewById(R.id.btnNextQuestion);
        //btnMultiMark = (ImageButton) findViewById(R.id.btnMultiMark);
        btnPlus1 = (ImageButton) findViewById(R.id.btnPlusOne);
        btnRedHighlighter = (ImageButton) findViewById(R.id.btnCrossHighlight);
        btnSubtractMark = (ImageButton) findViewById(R.id.btnSubtractMark);
        //btnGreenhighlighter = (ImageButton) findViewById(R.id.btnGreenHighlight);
        btnComment = (ImageButton) findViewById(R.id.btnComment);
        btnRedo = (ImageButton) findViewById(R.id.btnRedo);
        //btnUndo = (ImageButton) findViewById(R.id.btnUndo);
        btnPenMarking = (ImageButton) findViewById(R.id.btnPenMarking);


    }

    private void multimark(final Question currentQ) {
        final Dialog dialog = new Dialog(this);
        Window window = dialog.getWindow();
        dialog.setContentView(R.layout.multimark_dialog);
        dialog.setTitle("Multi Mark Loader");
        window.setGravity(Gravity.TOP | Gravity.CENTER);


        final EditText edit = (EditText) dialog.findViewById(R.id.edtMarkDialog);
        edit.setHint(edit.getHint() + String.valueOf(currentQ.getMarkAllocation()));
        edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
                    String markReceivedFromDialog = edit.getText().toString();
                    int newMark = 0;
                    if (!isNumeric(markReceivedFromDialog))
                        newMark = 0;
                    else {
                        newMark = Integer.parseInt(markReceivedFromDialog);
                        if (newMark <= currentQ.getMarkAllocation() && newMark >= 0) {
                            MarkAllocation.setText(newMark + "/" + currentQ.getMarkAllocation());
                        } else {
                            showToastLong("Please enter a mark within the mark allocation range");
                        }
                    }
                    dialog.dismiss();
                }
                return false;
            }
        });
        Button button = (Button) dialog.findViewById(R.id.btnOkMarkDialog);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String markReceivedFromDialog = edit.getText().toString();
                int newMark = 0;
                if (!isNumeric(markReceivedFromDialog))
                    newMark = 0;
                else {
                    newMark = Integer.parseInt(markReceivedFromDialog);
                    if (newMark <= currentQ.getMarkAllocation() && newMark >= 0) {
                        MarkAllocation.setText(newMark + "/" + currentQ.getMarkAllocation());
                    } else {
                        showToastLong("Please enter a mark within the mark allocation range");
                    }
                }
                dialog.dismiss();
            }
        });


        dialog.show();
    }

    private boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

    /**
     * Click the remove button then invoke a method that creates instance of my AnnotEdit. The instance should invoke the
     * method for deleting
     */

    public void performRemoveByButton() {
/*
        removeCheckMark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deactivateMarking();
                if (!isPenMarkingActive)
                {
                    TM.removeAnnotationUsingButton();

                }

            }
        });*/
    }


    @Override
    protected void onDestroy()
    {
        widget.setOnRecognitionListener(null);
        widget.setOnConfigureListener(null);

        // release widget's resources
        widget.release();
        super.onDestroy();
    }

    @Override
    public void onConfigurationBegin(GeometryWidgetApi widget)
    {
    }

    @Override
    public void onConfigurationEnd(GeometryWidgetApi widget, boolean success)
    {
        if(!success)
        {
            Toast.makeText(getApplicationContext(), widget.getErrorString(), Toast.LENGTH_LONG).show();
            Log.e(TAG, "Unable to configure the Geometry Widget: " + widget.getErrorString());
            return;
        }
        Toast.makeText(getApplicationContext(), "Geometry Widget Configured", Toast.LENGTH_SHORT).show();
        if(BuildConfig.DEBUG)
            Log.d(TAG, "Geometry Widget configured!");
    }

    @Override
    public void onRecognitionBegin(GeometryWidgetApi widget)
    {
    }

    @Override
    public void onRecognitionEnd(GeometryWidgetApi widget)
    {
        Toast.makeText(getApplicationContext(), "Recognition update", Toast.LENGTH_SHORT).show();
        if(BuildConfig.DEBUG)
        {
            Log.d(TAG, "Geometry Widget recognition");
        }
    }
}

 

      <com.myscript.atk.geometry.widget.GeometryWidget
                                android:id="@+id/geometry_widget"
                                android:layout_width="fill_parent"
                                android:layout_height="match_parent"
                                android:focusable="true"
                          >

                                <LinearLayout
                                    android:layout_width="match_parent"
                                    android:layout_height="match_parent"
                                    android:orientation="horizontal"
                                    >

                                <com.pdftron.pdf.PDFViewCtrl
                                    android:id="@+id/pdfdrawview"
                                    android:layout_width="fill_parent"
                                    android:layout_height="fill_parent"
                                    android:scrollbars="vertical|horizontal"
                                    android:focusable="false">
                                </com.pdftron.pdf.PDFViewCtrl>

                                </LinearLayout>

                            </com.myscript.atk.geometry.widget.GeometryWidget>

 

 

1 Comment

Dear Sibulele Kupelo,

Thank you for contacting us.

Currently, I am not sure to understand your use-case, what are you exactly trying to achieve:
1-Do you want to use the Diagram Widget to recognize shapes from a PDF?
2-Or do you want to write in the Diagram Widget, then export the diagram and add it into your PDF?
3-Or another use-case?

1-This can not be done, the Diagram Widget can only be used to recognize "x and y coordinates". You can not input an scan image.
2-If this use-case, you can export the recognized diagram (as image, svg or graphml), then import it into your pdf file.
3-If none of both above use-cases, can you provide us withg more specification, so that we can better understand your use-case.

Thank you,

Best regards,

Olivier
Login or Signup to post a comment