working on PCB sessions (3)

parent bf9a9ff0
......@@ -62,7 +62,7 @@ public class RestapiWrapper {
ask(operation, params, postOrGet, false, listener);
}
public void ask(String operation, Hashtable<String, String> params, String postOrGet, boolean json, iRestapiListener listener) {
Log.i(this.getClass().getCanonicalName(),"Asking for "+operation);
// call preExecute listener to show loading window
listener.preExecute();
// call AsynTask to perform network operation on separate thread
......@@ -130,16 +130,17 @@ public class RestapiWrapper {
private static JSONObject resultToJSON(HttpURLConnection urlConnection) throws IOException {
int responseCode=urlConnection.getResponseCode();
String response="";
StringBuilder response=new StringBuilder("");
String line;
JSONObject JSONresponse;
BufferedReader br = new BufferedReader(new InputStreamReader(responseCode == HttpsURLConnection.HTTP_OK
? urlConnection.getInputStream()
: urlConnection.getErrorStream()));
// Log.i(com.yottacode.net.RestapiWrapper.class.getName(), "starting to read server answer for"+urlConnection.getURL().toString());
while ((line=br.readLine()) != null) {
response+=line;
response.append(line);
}
if (response.length()==0) response="{\"result\":null}";
if (response.length()==0) response.append("{\"result\":null}");
try {
JSONresponse = new JSONObject("{ "+SERVER_RESULT+": " + response + (responseCode == HttpsURLConnection.HTTP_OK
......@@ -149,7 +150,7 @@ public class RestapiWrapper {
JSONresponse = null;
Log.e(RestapiWrapper.class.getCanonicalName(),e.getMessage());
}
Log.i(com.yottacode.net.RestapiWrapper.class.getName(), "server answer: " + JSONresponse.toString());
// Log.i(com.yottacode.net.RestapiWrapper.class.getName(), "server answer: " + JSONresponse.toString());
return JSONresponse;
}
......@@ -236,7 +237,7 @@ public class RestapiWrapper {
@Override
protected HttpAsyncTaskParams doInBackground(HttpAsyncTaskParams... params) {
try {
Log.i(com.yottacode.net.RestapiWrapper.class.getName(), " asking to the server for " + params[0].url+" params:"+params[0].url_params +" JSON?"+params[0].json_params);
Log.i(com.yottacode.net.RestapiWrapper.class.getName(), " Asking to the server for " + params[0].url+" params:"+params[0].url_params +" JSON?"+params[0].json_params);
JSONObject jresult = params[0].request_method.equalsIgnoreCase("GET")
? GET(params[0].url, params[0].url_params)
: POST(params[0].url, params[0].request_method, params[0].url_params, params[0].json_params);
......
......@@ -9,6 +9,7 @@ import com.yottacode.pictogram.tools.PCBcontext;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import java.util.Vector;
/**
......@@ -69,9 +70,11 @@ public class ActionTalk implements Emitter.Listener {
public void addListener(iActionListener listener) {
listeners.add(listener);
}
public void removeListener(iActionListener removedlistener) {
for (iActionListener listener:this.listeners )
if (listener==removedlistener) listeners.remove(removedlistener);
Iterator listeners=this.listeners.iterator();
while (listeners.hasNext() )
if (listeners.next()==removedlistener) listeners.remove();
}
/**
......
......@@ -124,7 +124,6 @@
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/builds" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/24.2.1/jars" />
......
......@@ -45,6 +45,7 @@ import com.yottacode.pictogram.grammar.iLocalPicto;
import com.yottacode.pictogram.net.websockets.VocabularyTalk;
import com.yottacode.pictogram.net.PictoUploader;
import com.yottacode.pictogram.tabletlibrary.R;
import com.yottacode.pictogram.tabletlibrary.gui.session.SessionActivity;
import com.yottacode.pictogram.tabletlibrary.net.NetServiceTablet;
import com.yottacode.pictogram.tools.Img;
import com.yottacode.pictogram.tools.PCBcontext;
......@@ -65,7 +66,7 @@ import java.util.concurrent.TimeUnit;
public class PictogramActivity extends Activity implements VocabularyTalk.iVocabularyListener {
public static final String PREFS_NAME = "MyPrefsFile";
float firstTouchX = -1;
// Main layout for this activity
RelativeLayout mainLayout;
// Adapter for de grid showing the categories grid (and main pictos)
......@@ -103,9 +104,9 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
ImageButton deleteButton;
ImageButton ttsButton;
int maxColumns,maxRows,maxInTape;
ScheduledThreadPoolExecutor exec_mirror=null;
Picto prev_picto=null;
int maxColumns, maxRows, maxInTape;
ScheduledThreadPoolExecutor exec_mirror = null;
Picto prev_picto = null;
private boolean feedback_read;
private boolean feedback_highlight;
......@@ -121,9 +122,9 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
this.currentCategory = null;
this.count_deletelong = 0;
if (!PCBcontext.is_user_logged()) {
Log.i(LOG_TAG,"No user logged. Restarting app");
PCBcontext.getNetService().restart_app(false);
return;
Log.i(LOG_TAG, "No user logged. Restarting app");
PCBcontext.getNetService().restart_app(false);
return;
}
this.vocabulary = PCBcontext.getVocabulary();
......@@ -138,7 +139,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
this.vocabulary.setImgDownloaderListener(new ImgDownloader.iImgDownloaderListener() {
@Override
public void loadComplete() {
PictogramActivity.this.refresh();
PictogramActivity.this.refresh();
}
@Override
......@@ -182,10 +183,10 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
ttsButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.i(this.getClass().getCanonicalName()," Changing mirror mode");
Log.i(this.getClass().getCanonicalName(), " Changing mirror mode");
if (PCBcontext.getPcbdb().getCurrentUser().is_supervisor()) {
int res_id=PCBcontext.getPcbdb().getCurrentUser().alter_mirror_mode()==true ? R.string.mirror_mode_on : R.string.mirror_mode_off;
Toast.makeText(PictogramActivity.this,res_id,Toast.LENGTH_SHORT).show();
int res_id = PCBcontext.getPcbdb().getCurrentUser().alter_mirror_mode() == true ? R.string.mirror_mode_on : R.string.mirror_mode_off;
Toast.makeText(PictogramActivity.this, res_id, Toast.LENGTH_SHORT).show();
}
return true;
}
......@@ -200,22 +201,22 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
this.tapeGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(this.getClass().getCanonicalName()," Delete item "+position+"("+PictogramActivity.this.tapeAdapter.getItem(position).get_translation()+")");
Log.i(this.getClass().getCanonicalName(), " Delete item " + position + "(" + PictogramActivity.this.tapeAdapter.getItem(position).get_translation() + ")");
PCBcontext.getActionLog().log(new TalkAction(TalkAction.DELETE, PictogramActivity.this.tapeAdapter.getItem(position)));
PictogramActivity.this.tapeAdapter.deleteItem(position);
PictogramActivity.this.tapeAdapter.notifyDataSetChanged();
}
});
((NetServiceTablet)PCBcontext.getNetService().getNetServiceDevice()).setPictogramActivity(this);
((NetServiceTablet) PCBcontext.getNetService().getNetServiceDevice()).setPictogramActivity(this);
if (PCBcontext.getPcbdb().getCurrentUser().is_picto_size_big()) {
maxColumns= getResources().getInteger(R.integer.columns_big);
maxRows= getResources().getInteger(R.integer.rows_big);
maxColumns = getResources().getInteger(R.integer.columns_big);
maxRows = getResources().getInteger(R.integer.rows_big);
maxInTape = getResources().getInteger(R.integer.maxInTape_big);
} else {
maxColumns= getResources().getInteger(R.integer.columns);
maxRows= getResources().getInteger(R.integer.rows);
maxColumns = getResources().getInteger(R.integer.columns);
maxRows = getResources().getInteger(R.integer.rows);
maxInTape = getResources().getInteger(R.integer.maxInTape);
}
PictogramActivity.this.pictoMainGridView.setNumColumns(PictogramActivity.this.maxColumns);
......@@ -232,54 +233,55 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
}
public void setConfig(){
public void setConfig() {
startTTS();
setFeedback(new View[] {deleteButton,ttsButton, this.showPictoCategoriesViewButton, this.pictoCategoryGridView,this.pictoMainGridView});
setFeedback(new View[]{deleteButton, ttsButton, this.showPictoCategoriesViewButton, this.pictoCategoryGridView, this.pictoMainGridView});
}
private void setFeedback(View views[]) {
boolean vibration=PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.VIBRATION);
boolean click=PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.BEEP);
this.feedback_read=PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.READ);
this.feedback_highlight=PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.HIGHLIGHT);
boolean vibration = PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.VIBRATION);
boolean click = PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.BEEP);
this.feedback_read = PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.READ);
this.feedback_highlight = PCBcontext.getPcbdb().getCurrentUser().input_feedback_on(User.JSON_STUDENT_INPUT_FEEDBACK.HIGHLIGHT);
Log.i(this.getClass().getCanonicalName(),"Feedback:"+" vibration:"+vibration+" Beep:"+click+" Read:"+feedback_read+" Highlight:"+feedback_highlight);
Log.i(this.getClass().getCanonicalName(), "Feedback:" + " vibration:" + vibration + " Beep:" + click + " Read:" + feedback_read + " Highlight:" + feedback_highlight);
View.OnTouchListener touchListener;
touchListener=
touchListener =
vibration ? new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean enable_haptic;
enable_haptic=!(v instanceof GridView);
if (!enable_haptic) {
int x=Math.round(event.getX());
int y=Math.round(event.getY());
int position=((GridView) v).pointToPosition(x,y);
Picto p = position>-1 ? (Picto)((GridView) v).getItemAtPosition(position) : null;
enable_haptic = (p != null && p.get_id() != 0 && !p.is_invisible() && p.is_enabled());
}
if (enable_haptic)
v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
return false;
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean enable_haptic;
enable_haptic = !(v instanceof GridView);
if (!enable_haptic) {
int x = Math.round(event.getX());
int y = Math.round(event.getY());
int position = ((GridView) v).pointToPosition(x, y);
Picto p = position > -1 ? (Picto) ((GridView) v).getItemAtPosition(position) : null;
enable_haptic = (p != null && p.get_id() != 0 && !p.is_invisible() && p.is_enabled());
}
if (enable_haptic)
v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
return false;
}
: click
}
: click
? new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
return false;
@Override
public boolean onTouch(View v, MotionEvent event) {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
: new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
......@@ -287,27 +289,27 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
}
};
for (View view : views)
view.setOnTouchListener(touchListener);
for (View view : views)
view.setOnTouchListener(touchListener);
}
public void startTTS() {
String engine=PCBcontext.getPcbdb().getCurrentUser().get_tts_engine_sup()==null
? getString(R.string.default_tts_engine)
: PCBcontext.getPcbdb().getCurrentUser().get_tts_engine_sup();
String tts_voice=PCBcontext.getPcbdb().getCurrentUser().get_json_attr("tts voice")==null
? PCBcontext.getPcbdb().getCurrentUser().get_gender_stu().charAt(0)=='M'
? getString(R.string.default_tts_voice_male)
: getString(R.string.default_tts_voice_female)
String engine = PCBcontext.getPcbdb().getCurrentUser().get_tts_engine_sup() == null
? getString(R.string.default_tts_engine)
: PCBcontext.getPcbdb().getCurrentUser().get_tts_engine_sup();
String tts_voice = PCBcontext.getPcbdb().getCurrentUser().get_json_attr("tts voice") == null
? PCBcontext.getPcbdb().getCurrentUser().get_gender_stu().charAt(0) == 'M'
? getString(R.string.default_tts_voice_male)
: getString(R.string.default_tts_voice_female)
: PCBcontext.getPcbdb().getCurrentUser().get_json_attr("tts voice");
tts = new TTSHelper(this, engine, new Locale(PCBcontext.getPcbdb().getCurrentUser().get_lang_stu()),tts_voice);
tts = new TTSHelper(this, engine, new Locale(PCBcontext.getPcbdb().getCurrentUser().get_lang_stu()), tts_voice);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
Log.d(LOG_TAG, "TTS tape read start"+utteranceId);
Log.d(LOG_TAG, "TTS tape read start" + utteranceId);
}
@Override
......@@ -336,16 +338,18 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
}
});
}
@Override
protected void onStop() {
super.onStop();
Log.i(LOG_TAG,"Closing app");
PCBcontext.getNetService().closeNotifyStatus();
super.onStop();
Log.i(LOG_TAG, "Closing app");
PCBcontext.getNetService().closeNotifyStatus();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (tts != null){
if (tts != null) {
tts.destroy();
}
}
......@@ -365,7 +369,8 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
this.hidePictoMainViewAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
this.hidePictoMainViewAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
......@@ -374,7 +379,8 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
}
@Override
public void onAnimationRepeat(Animation animation) {}
public void onAnimationRepeat(Animation animation) {
}
});
this.showPictoMainViewAnimation = new TranslateAnimation(-animationWidth, 0, 0, 0);
......@@ -389,10 +395,12 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
}
@Override
public void onAnimationEnd(Animation animation) {}
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {}
public void onAnimationRepeat(Animation animation) {
}
});
}
......@@ -448,10 +456,11 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
/**
* Order a linked list of pictos with "blank spaces" between them
*
* @param list
* @return
*/
public LinkedList<Picto> sort(LinkedList<Picto> list){
public LinkedList<Picto> sort(LinkedList<Picto> list) {
if (list == null) {
list = new LinkedList<>();
}
......@@ -465,7 +474,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
for (Picto p : list) {
if (PCBcontext.getPcbdb().getCurrentUser().has_categories()) {
if (p.get_column() != -1 && p.get_row() != -1
&& p.get_column() < maxRows && p.get_row() < maxColumns) {
&& p.get_column() < maxRows && p.get_row() < maxColumns) {
mp[p.get_column()][p.get_row()] = p;
}
} else {
......@@ -484,14 +493,13 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
"{\"magnify\":false,\"highlight\":false,\"coord_y\":1,\"id_cat\":12303,\"status\":\"invisible\",\"coord_x\":4}");
*/
for(int i=0; i<maxRows; i++){
for(int j=0; j<maxColumns; j++){
if(mp[i][j] != null) ll.add(mp[i][j]);
for (int i = 0; i < maxRows; i++) {
for (int j = 0; j < maxColumns; j++) {
if (mp[i][j] != null) ll.add(mp[i][j]);
else ll.add(null); // Add the "blank picto" simulating an empty position
}
}
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
......@@ -522,7 +530,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
@Override
public void change(action action, int picto_cat, int picto_id, JSONObject args) {
Log.i(LOG_TAG, "Vocabulary action listened: " + action);
if(args!=null) Log.d(LOG_TAG, "args: " + args.toString());
if (args != null) Log.d(LOG_TAG, "args: " + args.toString());
refresh();
}
......@@ -550,7 +558,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
if (m_Text.equalsIgnoreCase(keyword)) {
// Change the password
if(checkBox.isChecked()){
if (checkBox.isChecked()) {
// Show a new dialog
View dialogChangeEscapeCode = View.inflate(PCBcontext.getContext(), R.layout.dialog_change_escape_code, null);
final EditText input1 = (EditText) dialogChangeEscapeCode.findViewById(R.id.editText1);
......@@ -576,7 +584,8 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
// And exit PictogramActivity
finish();
} else Toast.makeText(PCBcontext.getContext(), getResources().getString(R.string.codesNotEqual), Toast.LENGTH_SHORT).show();
} else
Toast.makeText(PCBcontext.getContext(), getResources().getString(R.string.codesNotEqual), Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
......@@ -588,7 +597,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
builder.show();
}else {
} else {
// Finish this Activity it the code is ok and is not checked the checkbox to change the code
finish();
/*
......@@ -598,7 +607,8 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
*/
}
// Wrong code
} else Toast.makeText(PCBcontext.getContext(),getResources().getString(R.string.wrongCode), Toast.LENGTH_SHORT).show();
} else
Toast.makeText(PCBcontext.getContext(), getResources().getString(R.string.wrongCode), Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
......@@ -614,12 +624,13 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
/**
* Disable long power button press (system menu)
*
* @param hasFocus
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(!hasFocus) {
if (!hasFocus) {
// Close every kind of system dialog
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
......@@ -628,6 +639,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
/**
* Disable volume button on key event
*
* @param event
*/
@Override
......@@ -684,16 +696,16 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
// if the view is the tape_grid_view, we accept the drag item
// Destino tape_grid_view y origen panel_grid_view
if(v == findViewById(R.id.tape_grid_view) && (viewgroup == findViewById(R.id.picto_category_grid_view) || viewgroup==findViewById(R.id.picto_main_grid_view))) {
if (v == findViewById(R.id.tape_grid_view) && (viewgroup == findViewById(R.id.picto_category_grid_view) || viewgroup == findViewById(R.id.picto_main_grid_view))) {
Picto p = viewgroup == findViewById(R.id.picto_category_grid_view) ? pictoCategoryGridAdapter.getItem(position)
: pictoMainGridAdapter.getItem(position);
Log.d("Drag:", "Posición: " + position+ " es categoria:"+p.is_category());
if(!p.is_category() ) addPictoWord(p);
: pictoMainGridAdapter.getItem(position);
Log.d("Drag:", "Posición: " + position + " es categoria:" + p.is_category());
if (!p.is_category()) addPictoWord(p);
}
// Si el destino es el panel y el origen la cinta de frase
else if(v == findViewById(R.id.picto_category_grid_view) && viewgroup == findViewById(R.id.tape_grid_view)){
else if (v == findViewById(R.id.picto_category_grid_view) && viewgroup == findViewById(R.id.tape_grid_view)) {
Log.d("Drag:", "Posición: " + position);
Picto p = tapeAdapter.getItem(position);
tapeAdapter.deleteItem(position);
......@@ -717,57 +729,52 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
/**
* Class used for picto clicking feedback
*/
private class OnPictoClickListener implements AdapterView.OnItemClickListener{
private class OnPictoClickListener implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Picto p = getCurrentPictoGridAdapter().getItem(position);
if ( p != null && p.get_id() != 0 && !p.is_invisible() && p.is_enabled()) {
if (p != null && p.get_id() != 0 && !p.is_invisible() && p.is_enabled()) {
Log.d(LOG_TAG, "Clic en picto: " + p.toString());
if (PictogramActivity.this.feedback_read && !p.is_category())
PictogramActivity.this.tts.play(p.get_translation());
p.set_mirror(false,false);
LinkedList<Picto> ll = sort(PCBcontext.getVocabulary().next(p));
//LinkedList<Picto> ll = vocabulary.next(p);
Log.d(LOG_TAG, "Lista de pictos recuperada: " + ll.toString());
PictogramActivity.this.tts.play(p.get_translation());
p.set_mirror(false, false);
// If the picto is a category
if (p.is_category()) {
currentCategory = p;
PCBcontext.getActionLog().log(new TalkAction(TalkAction.SELECT, p));
hidePictoMainGridView();
// If the picto is a category
if (p.is_category()) {
currentCategory = p;
PCBcontext.getActionLog().log(new TalkAction(TalkAction.SELECT, p));
hidePictoMainGridView();
} else if (tapeAdapter.getCount() < PictogramActivity.this.maxInTape) {
addPictoWord(p);
}
} else if (tapeAdapter.getCount() < PictogramActivity.this.maxInTape) {
addPictoWord(p);
}
}
}
}
private void addPictoWord(Picto p) {
currentCategory = null;
tapeAdapter.addItem(p);
tapeAdapter.notifyDataSetChanged();
showPictoMainGridView();
PCBcontext.getActionLog().log(new TalkAction(TalkAction.ADD, p));
if (PictogramActivity.this.feedback_read) PictogramActivity.this.tts.play(p.get_translation());
if (PictogramActivity.this.feedback_highlight) execHighligthFeeback(p,false);
if (PictogramActivity.this.feedback_read)
PictogramActivity.this.tts.play(p.get_translation());
if (PictogramActivity.this.feedback_highlight) execHighligthFeeback(p, false);
}
private void execHighligthFeeback(final Picto picto,boolean highlight_background) {
private void execHighligthFeeback(final Picto picto, boolean highlight_background) {
boolean same_picto = false;
picto.set_mirror(true,highlight_background); //comienza feedback
picto.set_mirror(true, highlight_background); //comienza feedback
if (exec_mirror != null) { //se cancela ejecución del feedbcack anterior, si lo hay
exec_mirror.shutdown();
exec_mirror = null;
}
if (prev_picto != null) { //se cancela marca de feedback del anterior, si lo hay
prev_picto.set_mirror(false,false);
same_picto=prev_picto == picto;
prev_picto.set_mirror(false, false);
same_picto = prev_picto == picto;
}
if (same_picto)
prev_picto = null; //por si se pulsaa el mismo boton varias veces
......@@ -782,7 +789,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
public void run() {
refresh();
if (repeating++ == 20) {
picto.set_mirror(false,false);
picto.set_mirror(false, false);
if (exec_mirror != null) {
exec_mirror.shutdown();
exec_mirror = null;
......@@ -808,14 +815,13 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
Log.d(LOG_TAG, "No tengo pictograma. Abro carrete...");
addPicto(position % maxColumns, (int) (position / maxColumns));
}
else
} else
Toast.makeText(PictogramActivity.this, PictogramActivity.this.getResources().getString(R.string.notNewCats), Toast.LENGTH_SHORT).show();
} else {
p.alter_status();
getCurrentPictoGridAdapter().notifyDataSetChanged();
}
}
} else {
ClipData.Item item = new ClipData.Item("" + position);
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
......@@ -825,15 +831,15 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
if (p != null && !p.is_invisible() && p.is_enabled()) {
// If is not the blank picto, it isn't invisible or disabled
if (p.get_id() != 0 &&
!p.get_status().equalsIgnoreCase("invisible") &&
!p.get_status().equalsIgnoreCase("disabled") &&
tapeAdapter.getCount() < PictogramActivity.this.maxInTape) {
!p.get_status().equalsIgnoreCase("invisible") &&
!p.get_status().equalsIgnoreCase("disabled") &&
tapeAdapter.getCount() < PictogramActivity.this.maxInTape) {
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, //data to be dragged
shadowBuilder, //drag shadow
view, //local data about the drag and drop operation
0 //no needed flags
shadowBuilder, //drag shadow
view, //local data about the drag and drop operation
0 //no needed flags
);
//view.setVisibility(View.INVISIBLE);
}
......@@ -884,60 +890,60 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
private class OnDeleteButtonLongClickListener implements View.OnLongClickListener {
@Override
public boolean onLongClick(View v) {
count_deletelong++;
count_deletelong++;
if (count_deletelong >= 3) {
//TODO: COMPROBAR SI LOS USUARIOS QUE BUSCO EXISTEN: SI NO PONER LOS DATOS POR DEFECTO*******************************************************************/
if (count_deletelong >= 3) {
//TODO: COMPROBAR SI LOS USUARIOS QUE BUSCO EXISTEN: SI NO PONER LOS DATOS POR DEFECTO*******************************************************************/
//Cojo los id del ultimo estudiante y el ultimo supervisor
int lastIdStu = PCBcontext.getDevice().getLastStuId();
//Cojo los id del ultimo estudiante y el ultimo supervisor
int lastIdStu = PCBcontext.getDevice().getLastStuId();
User actual = PCBcontext.getPcbdb().getCurrentUser();
User usuario_anterior;
String lastUserName = null;
String lastPassword= null;
User actual = PCBcontext.getPcbdb().getCurrentUser();
User usuario_anterior;
String lastUserName = null;
String lastPassword = null;
if (actual.is_supervisor()) //Si el que habia es supervisor busco el ultimo niño
try {
usuario_anterior = PCBcontext.getDevice().findUser(lastIdStu,User.NO_SUPERVISOR);
if(usuario_anterior!=null){
lastUserName = usuario_anterior.get_nickname_stu();
lastPassword = usuario_anterior.get_pwd_stu();
if (actual.is_supervisor()) //Si el que habia es supervisor busco el ultimo niño
try {
usuario_anterior = PCBcontext.getDevice().findUser(lastIdStu, User.NO_SUPERVISOR);
if (usuario_anterior != null) {
lastUserName = usuario_anterior.get_nickname_stu();
lastPassword = usuario_anterior.get_pwd_stu();
}
} catch (JSONException e) {
e.printStackTrace();
}
else {
int lastIdSup = PCBcontext.getDevice().getLastSupId();
try {
usuario_anterior = PCBcontext.getDevice().findUser(lastIdStu, lastIdSup);
if (usuario_anterior != null) {
lastUserName = usuario_anterior.get_email_sup();
lastPassword = usuario_anterior.get_pwd_sup();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
else {
int lastIdSup = PCBcontext.getDevice().getLastSupId();
try {
usuario_anterior = PCBcontext.getDevice().findUser(lastIdStu,lastIdSup);
if(usuario_anterior!=null){
lastUserName = usuario_anterior.get_email_sup();
lastPassword = usuario_anterior.get_pwd_sup();
Class serialClass;
try {
serialClass = Class.forName(getString(R.string.SerialClass));
} catch (ClassNotFoundException e) {
Log.e(this.getClass().getCanonicalName(), "S:" + getString(R.string.SerialClass));
serialClass = SerialActivity.class;
}
Intent serialActivity = new Intent(getBaseContext(), serialClass);
if (lastUserName != null) {
Log.i(this.getClass().getCanonicalName(), "Switch user to " + lastUserName);
serialActivity.putExtra("switch_usr", lastUserName);
serialActivity.putExtra("switch_pwd", lastPassword);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Class serialClass;
try {
serialClass=Class.forName(getString(R.string.SerialClass));
} catch (ClassNotFoundException e) {
Log.e(this.getClass().getCanonicalName(),"S:"+getString(R.string.SerialClass));
serialClass=SerialActivity.class;
}
Intent serialActivity = new Intent(getBaseContext(), serialClass);
if (lastUserName!=null) {
Log.i(this.getClass().getCanonicalName(), "Switch user to "+ lastUserName);
serialActivity.putExtra("switch_usr", lastUserName);
serialActivity.putExtra("switch_pwd", lastPassword);
}
PictogramActivity.this.finish();
PCBcontext.getNetService().restart_app(serialActivity,false);
}
return false;
PictogramActivity.this.finish();
PCBcontext.getNetService().restart_app(serialActivity, false);
}
return false;
}
}
......@@ -957,6 +963,7 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
/**
* add a local picto from pcb
*
* @param row
* @param col
*/
......@@ -965,11 +972,11 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
if (PCBcontext.getPcbdb().getCurrentUser().has_categories()) {
this.getIntent().putExtra(Picto.JSON_ATTTRS.ROW, row);
this.getIntent().putExtra(Picto.JSON_ATTTRS.COLUMN, col);
} else {
this.getIntent().putExtra(Picto.JSON_ATTTRS.FREE_ROW, row);
this.getIntent().putExtra(Picto.JSON_ATTTRS.FREE_COLUMN, col);
this.getIntent().putExtra(Picto.JSON_ATTTRS.ROW, row);
this.getIntent().putExtra(Picto.JSON_ATTTRS.COLUMN, col);
} else {
this.getIntent().putExtra(Picto.JSON_ATTTRS.FREE_ROW, row);
this.getIntent().putExtra(Picto.JSON_ATTTRS.FREE_COLUMN, col);
}
startActivityForResult(intent, SELECT_PICTURE);
......@@ -995,27 +1002,27 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
@Override
public void onClick(DialogInterface dialog, int which) {
int cat = PictogramActivity.this.currentCategory != null
? PictogramActivity.this.currentCategory.get_id()
: Picto.NO_CATEGORY;
? PictogramActivity.this.currentCategory.get_id()
: Picto.NO_CATEGORY;
PCBcontext.getVocabulary().saveLocalPicto(
selectedImagePath,
input.getText().toString(),
cat,
row,
col,
freeRow,
freeColumn,
new iLocalPicto() {
@Override
public void saved(Picto localPicto) {
PictogramActivity.this.refresh();
try {
new PictoUploader(localPicto).upload(PictogramActivity.this);
} catch (IOException e) {
Log.e(Vocabulary.class.getCanonicalName(), e.getMessage());
}
selectedImagePath,
input.getText().toString(),
cat,
row,
col,
freeRow,
freeColumn,
new iLocalPicto() {
@Override
public void saved(Picto localPicto) {
PictogramActivity.this.refresh();
try {
new PictoUploader(localPicto).upload(PictogramActivity.this);
} catch (IOException e) {
Log.e(Vocabulary.class.getCanonicalName(), e.getMessage());
}
});
}
});
}
});
......@@ -1025,19 +1032,20 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
/**
* Función para la selección de una foto del carrete
*
* @param requestCode
* @param resultCode
* @param data
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
String selectedImagePath;
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
int row=this.getIntent().getIntExtra(Picto.JSON_ATTTRS.ROW, -1);
int col=this.getIntent().getIntExtra(Picto.JSON_ATTTRS.COLUMN, -1);
int row = this.getIntent().getIntExtra(Picto.JSON_ATTTRS.ROW, -1);
int col = this.getIntent().getIntExtra(Picto.JSON_ATTTRS.COLUMN, -1);
int freeRow = this.getIntent().getIntExtra(Picto.JSON_ATTTRS.FREE_ROW, -1);
int freeColumn = this.getIntent().getIntExtra(Picto.JSON_ATTTRS.FREE_COLUMN, -1);
Log.i(this.getClass().getCanonicalName(), "0 Picto x y " + " " + row + " " + col);
......@@ -1052,21 +1060,22 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
/**
* Función para la selección de una foto del carrete
*
* @param uri
* @return
*/
static public String getPath(Uri uri) {
if( uri == null ) {
if (uri == null) {
return null;
}
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = PCBcontext.getContext().getContentResolver().query(uri, projection, null, null, null);
if( cursor != null ){
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
......@@ -1075,143 +1084,25 @@ public class PictogramActivity extends Activity implements VocabularyTalk.iVocab
}
/*
Animator mCurrentAnimator=null;
private void zoomImageFromThumb(Picto picto, final View thumbView, int imageResId) {
// If there's an animation in progress, cancel it
// immediately and proceed with this one.
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
this.pictoMainGridView.findViewById()
// Load the high-resolution "zoomed-in" image.
final ImageView expandedImageView = (ImageView) findViewById(
R.id.expanded_image);
expandedImageView.setImageResource(imageResId);
// Calculate the starting and ending bounds for the zoomed-in image.
// This step involves lots of math. Yay, math.
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
// The start bounds are the global visible rectangle of the thumbnail,
// and the final bounds are the global visible rectangle of the container
// view. Also set the container view's offset as the origin for the
// bounds, since that's the origin for the positioning animation
// properties (X, Y).
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container)
.getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the "center crop" technique. This prevents undesirable
// stretching during the animation. Also calculate the start scaling
// factor (the end scaling factor is always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height()
> (float) startBounds.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
// Hide the thumbnail and show the zoomed-in view. When the animation
// begins, it will position the zoomed-in view in the place of the
// thumbnail.
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);
// Set the pivot point for SCALE_X and SCALE_Y transformations
// to the top-left corner of the zoomed-in view (the default
// is the center of the view).
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);
// Construct and run the parallel animation of the four translation and
// scale properties (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set
.play(ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
startScale, 1f)).with(ObjectAnimator.ofFloat(expandedImageView,
View.SCALE_Y, startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
// Upon clicking the zoomed-in image, it should zoom back down
// to the original bounds and show the thumbnail instead of
// the expanded image.
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
// Animate the four positioning/sizing properties in parallel,
// back to their original values.
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator
.ofFloat(expandedImageView, View.X, startBounds.left))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.Y,startBounds.top))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.SCALE_X, startScaleFinal))
.with(ObjectAnimator
.ofFloat(expandedImageView,
View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (PCBcontext.getPcbdb().getCurrentUser().is_supervisor())
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
firstTouchX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
@Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
if (firstTouchX > event.getX()+100) {
Intent sessionActivity = new Intent(this, SessionActivity.class);
sessionActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(sessionActivity);
}
});
set.start();
mCurrentAnimator = set;
break;
case MotionEvent.ACTION_UP:
firstTouchX = -1;
}
});
}*/
return super.dispatchTouchEvent(event);
}
}
......@@ -18,7 +18,6 @@ import com.yottacode.net.iRestapiListener;
import com.yottacode.pictogram.dao.User;
import com.yottacode.pictogram.net.ImgDownloader;
import com.yottacode.pictogram.tabletlibrary.R;
import com.yottacode.pictogram.tabletlibrary.gui.session.SessionActivity;
import com.yottacode.pictogram.tools.Img;
import com.yottacode.pictogram.tools.PCBcontext;
import com.yottacode.tools.GUITools;
......@@ -117,10 +116,8 @@ public class StudentFragmentGrid extends Fragment{
@Override
public void loadComplete() {
if (progressDialog!=null && progressDialog.isShowing()) progressDialog.dismiss();
Intent sessionActivity = new Intent(getActivity(), SessionActivity.class);
startActivity(sessionActivity);
//Intent pictogramActivity = new Intent(getActivity(), PictogramActivity.class);
//startActivity(pictogramActivity);
Intent pictogramActivity = new Intent(getActivity(), PictogramActivity.class);
startActivity(pictogramActivity);
}
@Override
......
package com.yottacode.pictogram.tabletlibrary.gui.session;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.yottacode.pictogram.dao.Picto;
import com.yottacode.pictogram.tabletlibrary.R;
import com.yottacode.tools.BitmapTools;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Vector;
/**
* Created by Fernando on 18/12/2016.
*/
class PictoAdapter extends BaseAdapter {
private class Item {
Picto picto;
int secs;
public void setCurrentMsg(int currentMsg) {
this.currentMsg = currentMsg;
}
public static class Item {
Bitmap img;
String secs;
public Item(Bitmap img, String secs) {
this.img=img;
this.secs=secs;
}
Bitmap getImg() {
return img;
}
String getTime() {
return secs;
}
public void setImg(Bitmap currmsg) {
this.img=currmsg;
}
}
Context context;
Vector<Item> msg;
int currentMsg=0;
final long base_time=new Date().getTime();
private static LayoutInflater inflater = null;
public PictoAdapter(Context context) {
this.context = context;
msg=new Vector<>(3);
newMsg();
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private String getTimeDiff(long time) {
long mills = time - this.base_time;
int mins = (int) (mills / (1000*60));
int secs = (int)(mills/(1000)) - mins*60;
return "+"+mins+ "' " + secs+"''";
}
@Override
public int getCount() {
return msg.size();
}
@Override
public Object getItem(int position) {
public Item getItem(int position) {
return msg.get(position);
}
......@@ -49,11 +93,106 @@ public long getItemId(int position) {
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.session_picto_view, null);
return vi;
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.session_picto_view, null);
ImageView picto=(ImageView)vi.findViewById(R.id.session_picto);
picto.setImageBitmap(this.msg.get(position).getImg());
if (currentMsg== position)
vi.setBackgroundColor(Color.LTGRAY);
else
vi.setBackgroundColor(Color.TRANSPARENT);
return vi;
}
public void addItem(Bitmap bmp) {
Item item=this.msg.get(currentMsg);
Bitmap oldmsg=item.getImg();
// bmp=new BitmapTools(bmp).resize(85,85).get();
bmp=set_text(context,bmp,getTimeDiff(new Date().getTime()));
Bitmap currmsg=combineImages(oldmsg,bmp);
item.setImg(currmsg);
}
public void newMsg() {
Bitmap bmp=BitmapFactory.decodeResource(context.getResources(),
R.drawable.session_starttry);
bmp=new BitmapTools(bmp).resize(75,75).get();
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(new Date()); // assigns calendar to given date
String time= calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND);
bmp=set_text(context,bmp,time);
if (this.currentMsg==this.msg.size()-1 || this.msg.size()==0) {
this.currentMsg = this.msg.size();
msg.add(new Item(bmp, time));
}
else {
this.currentMsg = this.msg.size() - 1;
notifyDataSetChanged();
}
}
private Bitmap combineImages(Bitmap c, Bitmap s) { // can add a 3rd parameter 'String loc' if you want to save the new image - left some code to do that at the bottom
Bitmap cs = null;
int width, height = 0;
if(c.getWidth() > s.getWidth()) {
width = c.getWidth() + s.getWidth();
height = c.getHeight();
} else {
width = s.getWidth() + s.getWidth();
height = c.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, c.getWidth(), 0f, null);
return cs;
}
static Bitmap set_text(Context context,Bitmap bitmap,String texto) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
int width = bitmap.getWidth(); //Ancho original
int height = bitmap.getHeight(); //Alto original
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Bitmap bm = Bitmap.createScaledBitmap(bitmap, (int)Math.round(0.9*width), (int)Math.round(0.9*height), false);
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); //Poner en blanco el bitmap original para dibujar encima
canvas.drawBitmap(bm, 0, 0, paint);
TextView textView = new TextView(context);
textView.layout(0, 50, 100, 100);
textView.setPadding(0, 0, 0, 0);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 13);
textView.setTextColor(Color.BLACK);
textView.setBackgroundColor(Color.TRANSPARENT);
textView.setWidth(100);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
textView.setMaxLines(1);
textView.setText(texto);
textView.setDrawingCacheEnabled(true);
canvas.drawBitmap(textView.getDrawingCache(), 0, 60, null);
return bitmap;
}
}
package com.yottacode.pictogram.tabletlibrary.gui.session;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
......@@ -19,16 +20,22 @@ import android.widget.ToggleButton;
import com.yottacode.pictogram.dao.User;
import com.yottacode.pictogram.tabletlibrary.R;
import com.yottacode.pictogram.tabletlibrary.gui.PictogramActivity;
import com.yottacode.pictogram.tools.PCBcontext;
import java.io.IOException;
public class SessionActivity extends FragmentActivity implements ListInstructionsFragment.iListInstructionsFragment, SessionFragment.OnFragmentInteractionListener{
public class SessionActivity extends FragmentActivity implements ListInstructionsFragment.iListInstructionsFragment, SessionFragment.OnSessionListener {
private static final String FRAGMENT_SESSION="session";
private static final String FRAGMENT_METHOD="method";
@Override
public void onSessionInteraction(Uri uri) {
}
class TouchButtonListener implements View.OnTouchListener {
int press,release;
......@@ -44,30 +51,30 @@ public class SessionActivity extends FragmentActivity implements ListInstruction
: getDrawable(release);
v.setBackground(draw);
if (event.getAction()==MotionEvent.ACTION_UP) {
SessionFragment session = (SessionFragment) getSupportFragmentManager().findFragmentByTag(SessionActivity.FRAGMENT_SESSION);
//Bitmap bitmap=((BitmapDrawable)getDrawable(press)).getBitmap();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),press);
//Bitmap bm = Bitmap.createScaledBitmap(bitmap, (int)Math.round(0.9*bitmap.getWidth()), (int)Math.round(0.9*bitmap.getHeight()), false);
session.newMsg(bitmap);
}
return true;
}
}
float firstTouchX=-1;
SessionFragment sessionFragment = new SessionFragment();
ListInstructionsFragment listInstructionsFragment= new ListInstructionsFragment();
boolean previous_mirrormode=PCBcontext.getPcbdb().getCurrentUser().is_mirror_on();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_session);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.sessions_fragment_container, listInstructionsFragment)
.commit();
}
@Override
protected void onStart() {
super.onStart();
// Set Student information on topbar
User student=PCBcontext.getPcbdb().getCurrentUser();
final TextView StudentFullNameView = (TextView) findViewById(R.id.sessionTopbarStudentFullName);
final TextView StudentUserNameView = (TextView) findViewById(R.id.sessionTopbarStudentUserName);
......@@ -81,78 +88,38 @@ public class SessionActivity extends FragmentActivity implements ListInstruction
StudentFullNameView.setText(student.get_name_stu() + " " + student.get_surname_stu());
StudentUserNameView.setText(student.get_nickname_stu());
try {
StudentPhotoView.setImageBitmap(student.get_bitmap_stu(this.getBaseContext()));
} catch (IOException e) {
Log.e(this.getClass().getCanonicalName(),e.getMessage());
}
okBtn.setOnTouchListener(new TouchButtonListener(R.drawable.session_ok,R.drawable.session_ok2));
disBtn.setOnTouchListener(new TouchButtonListener(R.drawable.session_fail,R.drawable.session_fail2));
spoBtn.setOnTouchListener(new TouchButtonListener(R.drawable.session_spontaneous,R.drawable.session_spontaneous2));
failBtn.setOnTouchListener(new TouchButtonListener(R.drawable.session_fail,R.drawable.session_fail2));
supBtn.setOnTouchListener(new TouchButtonListener(R.drawable.session_supervised,R.drawable.session_supervised2));
onoffBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Fragment fragment;
String fragment_label;
int stop;
if (isChecked) {
fragment= sessionFragment;
fragment_label=SessionActivity.FRAGMENT_SESSION;
stop=View.VISIBLE;
if (!PCBcontext.getPcbdb().getCurrentUser().is_mirror_on())
PCBcontext.getPcbdb().getCurrentUser().alter_mirror_mode();
}
else {
fragment=listInstructionsFragment;
fragment_label=SessionActivity.FRAGMENT_METHOD;
stop=View.INVISIBLE;
if (previous_mirrormode!=PCBcontext.getPcbdb().getCurrentUser().is_mirror_on())
PCBcontext.getPcbdb().getCurrentUser().alter_mirror_mode();
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.sessions_fragment_container, fragment,fragment_label);
fragmentTransaction.commit();
findViewById(R.id.sessionPauseBtn).setVisibility(stop);
okBtn.setVisibility(stop);
disBtn.setVisibility(stop);
spoBtn.setVisibility(stop);
failBtn.setVisibility(stop);
supBtn.setVisibility(stop);
findViewById(R.id.sessionTopbarMethodName).setVisibility(stop);
findViewById(R.id.sessionTopbarInstructionName).setVisibility(stop);
if (!isChecked)
onoffBtn.setEnabled(false);
set_fragment(isChecked);
}
});
try {
StudentPhotoView.setImageBitmap(student.get_bitmap_stu(this.getBaseContext()));
} catch (IOException e) {
Log.e(this.getClass().getCanonicalName(),"Error setting student image");
}
Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(SessionActivity.FRAGMENT_METHOD);
if (currentFragment == null || !currentFragment.isVisible()) {
findViewById(R.id.sessionTopbarMethodName).setVisibility(View.INVISIBLE);
findViewById(R.id.sessionTopbarInstructionName).setVisibility(View.INVISIBLE);
findViewById(R.id.sessionPauseBtn).setVisibility(View.INVISIBLE);
okBtn.setVisibility(View.INVISIBLE);
disBtn.setVisibility(View.INVISIBLE);
spoBtn.setVisibility(View.INVISIBLE);
failBtn.setVisibility(View.INVISIBLE);
supBtn.setVisibility(View.INVISIBLE);
onoffBtn.setEnabled(false);
});
onoffBtn.setEnabled(false);
}
}
@Override
protected void onStart() {
super.onStart();
set_fragment(((ToggleButton)findViewById(R.id.sessionOnOffBtn)).isChecked());
}
@Override
public void instruction_selected(int instruction, String instruction_name) {
((ToggleButton)findViewById(R.id.sessionOnOffBtn)).setEnabled(true);
((TextView)findViewById(R.id.sessionTopbarInstructionName)).setText(instruction_name);
findViewById(R.id.sessionOnOffBtn).setEnabled(true);
}
@Override
public void method_selected(int method, String method_name) {
......@@ -160,8 +127,67 @@ public class SessionActivity extends FragmentActivity implements ListInstruction
((TextView)findViewById(R.id.sessionTopbarMethodName)).setText(method_name);
}
@Override
public void onFragmentInteraction(Uri uri) {
public boolean dispatchTouchEvent(MotionEvent event) {
if (PCBcontext.getPcbdb().getCurrentUser().is_supervisor())
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
firstTouchX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
if (event.getX()> firstTouchX +100) {
Intent pictogramActivity = new Intent(this, PictogramActivity.class);
startActivity(pictogramActivity);
}
break;
case MotionEvent.ACTION_UP:
firstTouchX = 100000;
}
return super.dispatchTouchEvent(event);
}
private void set_fragment(boolean isChecked) {
Fragment fragment;
String fragment_label;
final Button okBtn =((Button)findViewById(R.id.btn_correct));
final Button disBtn =((Button)findViewById(R.id.btn_discarded));
final Button spoBtn =((Button)findViewById(R.id.btn_spontaneous));
final Button failBtn =((Button)findViewById(R.id.btn_fail));
final Button supBtn =((Button)findViewById(R.id.btn_supervised));
int stop;
if (isChecked) {
fragment= sessionFragment;
fragment_label=SessionActivity.FRAGMENT_SESSION;
stop=View.VISIBLE;
if (!PCBcontext.getPcbdb().getCurrentUser().is_mirror_on())
PCBcontext.getPcbdb().getCurrentUser().alter_mirror_mode();
}
else {
fragment=listInstructionsFragment;
fragment_label=SessionActivity.FRAGMENT_METHOD;
stop=View.INVISIBLE;
if (previous_mirrormode!=PCBcontext.getPcbdb().getCurrentUser().is_mirror_on())
PCBcontext.getPcbdb().getCurrentUser().alter_mirror_mode();
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.sessions_fragment_container, fragment,fragment_label)
.commit()
;
findViewById(R.id.sessionPauseBtn).setVisibility(stop);
okBtn.setVisibility(stop);
disBtn.setVisibility(stop);
spoBtn.setVisibility(stop);
failBtn.setVisibility(stop);
supBtn.setVisibility(stop);
findViewById(R.id.sessionTopbarMethodName).setVisibility(stop);
findViewById(R.id.sessionTopbarInstructionName).setVisibility(stop);
}
}
......@@ -2,6 +2,7 @@ package com.yottacode.pictogram.tabletlibrary.gui.session;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
......@@ -9,16 +10,19 @@ import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.yottacode.pictogram.net.websockets.ActionTalk;
import com.yottacode.pictogram.tabletlibrary.R;
import com.yottacode.pictogram.tools.PCBcontext;
import java.io.IOException;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link SessionFragment.OnFragmentInteractionListener} interface
* {@link SessionFragment.OnSessionListener } interface
* to handle interaction events.
* Use the {@link SessionFragment#newInstance} factory method to
* create an instance of this fragment.
......@@ -33,9 +37,10 @@ public class SessionFragment extends Fragment implements ActionTalk.iActionListe
private String mParam1;
private String mParam2;
ListView list_pictomsgs;
ListView list_pictomsg;
PictoAdapter adapter_pictomsg;
private OnFragmentInteractionListener mListener;
private OnSessionListener mListener=null;
public SessionFragment() {
// Required empty public constructor
......@@ -73,24 +78,28 @@ public class SessionFragment extends Fragment implements ActionTalk.iActionListe
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_session, container, false);
list_pictomsgs = (ListView) this.getActivity().findViewById(R.id.session_pictomsg_list);
// list_pictomsgs.setAdapter(new PictoAdapter(this.getContext()));
list_pictomsg = (ListView) view.findViewById(R.id.session_pictomsg_list);
adapter_pictomsg=new PictoAdapter(this.getContext());
list_pictomsg.setAdapter(adapter_pictomsg);
list_pictomsg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
((PictoAdapter)list_pictomsg.getAdapter()).setCurrentMsg(position);
((PictoAdapter)list_pictomsg.getAdapter()).notifyDataSetChanged();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
if ( mListener==null)
if (context instanceof OnSessionListener) {
mListener = (OnSessionListener ) context;
PCBcontext.getVocabulary().addActionTalkListener(this);
} else {
throw new RuntimeException(context.toString()
......@@ -101,8 +110,9 @@ public class SessionFragment extends Fragment implements ActionTalk.iActionListe
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
if ( mListener==null)
if (context instanceof OnSessionListener ) {
mListener = (OnSessionListener ) context;
PCBcontext.getVocabulary().addActionTalkListener(this);
} else {
throw new RuntimeException(context.toString()
......@@ -120,6 +130,27 @@ public class SessionFragment extends Fragment implements ActionTalk.iActionListe
@Override
public void action(action action, int picto_cat, int picto_id) {
Log.e(this.getClass().getCanonicalName(),"ACTION VOC");
try {
Bitmap bmp=PCBcontext.getVocabulary().get_picto(picto_cat,picto_id).get_bitmap(getContext());
this.adapter_pictomsg.addItem(bmp);
getActivity().runOnUiThread(new Runnable() {
public void run() {
adapter_pictomsg.notifyDataSetChanged();
}});
} catch (IOException e) {
e.printStackTrace();
}
}
public void newMsg(Bitmap bmp) {
Log.e(this.getClass().getCanonicalName(),"ACTION VOC");
this.adapter_pictomsg.addItem(bmp);
this.adapter_pictomsg.newMsg();
getActivity().runOnUiThread(new Runnable() {
public void run() {
adapter_pictomsg.notifyDataSetChanged();
}});
}
/**
......@@ -132,8 +163,8 @@ public class SessionFragment extends Fragment implements ActionTalk.iActionListe
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
public interface OnSessionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
void onSessionInteraction(Uri uri);
}
}
......@@ -6,6 +6,8 @@
android:background="#BDBDBD"
android:keepScreenOn="true"
android:id="@+id/pictogramLayout"
android:activityOpenEnterAnimation="@anim/slide_in"
android:activityOpenExitAnimation="@anim/slide_out"
tools:context="com.yottacode.pictogram.tabletlibrary.gui.PictogramActivity"
android:padding="@dimen/small_padding">
<!-- android:keepScreenOn - To keep the screen bright as long as the app is visible (also forever) -->
......
......@@ -118,7 +118,7 @@
android:id="@+id/sessionFragmentLayout"
android:layout_below="@+id/view"
android:layout_alignParentEnd="true"
android:layout_height="328dp">
android:layout_height="300dp">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
......
......@@ -3,20 +3,14 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.yottacode.pictogram.tabletlibrary.gui.session.SessionFragment"
android:orientation="vertical">
android:orientation="vertical" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<ListView
android:id="@+id/session_pictomsg_list"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="220dp"
android:orientation="horizontal" >
<ListView
android:id="@+id/session_pictomsg_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
android:layout_height="wrap_content"
android:layout_gravity="left|start">
</ListView>
</LinearLayout>
......@@ -2,23 +2,15 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="90dp"
android:layout_height="match_parent"
android:id="@+id/session_picto_layout"
android:background="@color/picto_default_background"
android:padding="@dimen/picto_padding">
<ImageView
android:id="@+id/session_picto"
android:layout_height="@dimen/picto_normal_height"
android:layout_width="match_parent"
android:contentDescription="" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/session_picto_time"/>
android:layout_width="wrap_content"
android:contentDescription="" />
</LinearLayout>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment