示例#1
0
 private String getPathToBackPackSoundDirectory() {
   Log.d("TAG", "getPathToBackPackSoundDirectory() called!");
   return Utils.buildPath(
       Utils.buildProjectPath(
           Constants.DEFAULT_ROOT
               + "/"
               + Constants.BACKPACK_DIRECTORY
               + "/"
               + Constants.BACKPACK_SOUND_DIRECTORY));
 }
示例#2
0
  private void copyImageToCatroid(String originalImagePath) {
    int[] imageDimensions = ImageEditing.getImageDimensions(originalImagePath);

    if (imageDimensions[0] < 0 || imageDimensions[1] < 0) {
      Utils.showErrorDialog(getActivity(), getString(R.string.error_load_image));
      return;
    }

    File oldFile = new File(originalImagePath);

    try {
      if (originalImagePath.equals("")) {
        throw new IOException();
      }

      String projectName = ProjectManager.getInstance().getCurrentProject().getName();
      File imageFile = StorageHandler.getInstance().copyImage(projectName, originalImagePath, null);

      String imageName;
      int extensionDotIndex = oldFile.getName().lastIndexOf('.');
      if (extensionDotIndex > 0) {
        imageName = oldFile.getName().substring(0, extensionDotIndex);
      } else {
        imageName = oldFile.getName();
      }

      String imageFileName = imageFile.getName();
      // if pixmap cannot be created, image would throw an Exception in stage
      // so has to be loaded again with other Config
      Pixmap pixmap = null;
      pixmap = Utils.getPixmapFromFile(imageFile);

      if (pixmap == null) {
        ImageEditing.overwriteImageFileWithNewBitmap(imageFile);
        pixmap = Utils.getPixmapFromFile(imageFile);

        if (pixmap == null) {
          Utils.showErrorDialog(getActivity(), getString(R.string.error_load_image));
          StorageHandler.getInstance().deleteFile(imageFile.getAbsolutePath());
          return;
        }
      }
      pixmap = null;
      updateLookAdapter(imageName, imageFileName);
    } catch (IOException e) {
      Utils.showErrorDialog(getActivity(), getString(R.string.error_load_image));
    }
    getLoaderManager().destroyLoader(ID_LOADER_MEDIA_IMAGE);
    getActivity().sendBroadcast(new Intent(ScriptActivity.ACTION_BRICK_LIST_CHANGED));
  }
示例#3
0
  public Project(Context context, String name, boolean landscape) {
    xmlHeader.setProgramName(name);
    xmlHeader.setDescription("");

    if (landscape) {
      ifPortraitSwitchWidthAndHeight();
    } else {
      ifLandscapeSwitchWidthAndHeight();
    }
    if (ScreenValues.SCREEN_HEIGHT == 0 || ScreenValues.SCREEN_WIDTH == 0) {
      Utils.updateScreenWidthAndHeight(context);
    }
    xmlHeader.virtualScreenWidth = ScreenValues.SCREEN_WIDTH;
    xmlHeader.virtualScreenHeight = ScreenValues.SCREEN_HEIGHT;
    setDeviceData(context);

    MessageContainer.clear();

    dataContainer = new DataContainer();

    if (context == null) {
      return;
    }

    Sprite background = new Sprite(context.getString(R.string.background));
    background.look.setZIndex(0);
    addSprite(background);
  }
示例#4
0
  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    String originalImagePath = "";
    CursorLoader cursorLoader = (CursorLoader) loader;

    boolean catchedExpetion = false;

    if (data == null) {
      originalImagePath = cursorLoader.getUri().getPath();
    } else {
      int columnIndex = data.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
      data.moveToFirst();

      try {
        originalImagePath = data.getString(columnIndex);
      } catch (CursorIndexOutOfBoundsException e) {
        catchedExpetion = true;
      }
    }

    if (catchedExpetion || (data == null && originalImagePath.equals(""))) {
      Utils.showErrorDialog(getActivity(), getString(R.string.error_load_image));
      return;
    }
    copyImageToCatroid(originalImagePath);
  }
示例#5
0
 public String getAbsolutePathBackPackSound() {
   if (fileName != null) {
     return Utils.buildPath(getPathToBackPackSoundDirectory(), fileName);
   } else {
     return null;
   }
 }
示例#6
0
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    listView = getListView();
    registerForContextMenu(listView);

    if (savedInstanceState != null) {
      selectedLookData =
          (LookData) savedInstanceState.getSerializable(BUNDLE_ARGUMENTS_SELECTED_LOOK);

      boolean uriIsSet = savedInstanceState.getBoolean(BUNDLE_ARGUMENTS_URI_IS_SET);
      if (uriIsSet) {
        String defLookName = getString(R.string.default_look_name);
        lookFromCameraUri = UtilCamera.getDefaultLookFromCameraUri(defLookName);
      }
    }
    lookDataList = ProjectManager.INSTANCE.getCurrentSprite().getLookDataList();

    adapter =
        new LookAdapter(getActivity(), R.layout.fragment_look_looklist_item, lookDataList, false);
    adapter.setOnLookEditListener(this);
    setListAdapter(adapter);

    Utils.loadProjectIfNeeded(getActivity());
  }
  public void testContainer() throws IOException, InterruptedException {

    storageHandler.copyImage(currentProjectName, testImage.getAbsolutePath(), null);

    String checksumImage = Utils.md5Checksum(testImage);

    FileChecksumContainer fileChecksumContainer = projectManager.getFileChecksumContainer();
    assertTrue(
        "Checksum isn't in container", fileChecksumContainer.containsChecksum(checksumImage));

    // wait to get a different timestamp on next file
    Thread.sleep(2000);

    File newTestImage =
        storageHandler.copyImage(currentProjectName, testImage.getAbsolutePath(), null);
    File imageDirectory =
        new File(
            Constants.DEFAULT_ROOT
                + "/"
                + currentProjectName
                + "/"
                + Constants.IMAGE_DIRECTORY
                + "/");
    File[] filesImage = imageDirectory.listFiles();

    // nomedia file is also in images folder
    assertEquals("Wrong amount of files in folder", 2, filesImage.length);

    File newTestSound = storageHandler.copySoundFile(testSound.getAbsolutePath());
    String checksumSound = Utils.md5Checksum(testSound);
    assertTrue(
        "Checksum isn't in container", fileChecksumContainer.containsChecksum(checksumSound));
    File soundDirectory =
        new File(
            Constants.DEFAULT_ROOT + "/" + currentProjectName + "/" + Constants.SOUND_DIRECTORY);
    File[] filesSound = soundDirectory.listFiles();

    // nomedia file is also in sounds folder
    assertEquals("Wrong amount of files in folder", 2, filesSound.length);

    fileChecksumContainer.decrementUsage(newTestImage.getAbsolutePath());
    assertTrue("Checksum was deleted", fileChecksumContainer.containsChecksum(checksumImage));
    fileChecksumContainer.decrementUsage(newTestImage.getAbsolutePath());
    assertFalse("Checksum wasn't deleted", fileChecksumContainer.containsChecksum(checksumImage));
    fileChecksumContainer.decrementUsage(newTestSound.getAbsolutePath());
    assertFalse("Checksum wasn't deleted", fileChecksumContainer.containsChecksum(checksumSound));
  }
示例#8
0
  public boolean manualScreenshotExists(String manualScreenshotName) {

    String path = Utils.buildProjectPath(getName()) + "/" + manualScreenshotName;
    File manualScreenShot = new File(path);
    if (manualScreenShot.exists()) {
      return false;
    }
    return true;
  }
示例#9
0
  @Override
  public void create() {
    font = new BitmapFont();
    font.setColor(1f, 0f, 0.05f, 1f);
    font.setScale(1.2f);

    project = ProjectManager.getInstance().getCurrentProject();
    pathForScreenshot = Utils.buildProjectPath(project.getName()) + "/";

    virtualWidth = project.getXmlHeader().virtualScreenWidth;
    virtualHeight = project.getXmlHeader().virtualScreenHeight;

    virtualWidthHalf = virtualWidth / 2;
    virtualHeightHalf = virtualHeight / 2;

    stage = new Stage(virtualWidth, virtualHeight, true);
    batch = stage.getSpriteBatch();

    Gdx.gl.glViewport(0, 0, ScreenValues.SCREEN_WIDTH, ScreenValues.SCREEN_HEIGHT);
    initScreenMode();

    sprites = project.getSpriteList();
    for (Sprite sprite : sprites) {
      sprite.resetSprite();
      sprite.look.createBrightnessContrastShader();
      stage.addActor(sprite.look);
      sprite.resume();
    }

    passepartout =
        new Passepartout(
            ScreenValues.SCREEN_WIDTH,
            ScreenValues.SCREEN_HEIGHT,
            maximizeViewPortWidth,
            maximizeViewPortHeight,
            virtualWidth,
            virtualHeight);
    stage.addActor(passepartout);

    if (DEBUG) {
      OrthoCamController camController = new OrthoCamController(camera);
      InputMultiplexer multiplexer = new InputMultiplexer();
      multiplexer.addProcessor(camController);
      multiplexer.addProcessor(stage);
      Gdx.input.setInputProcessor(multiplexer);
      fpsLogger = new FPSLogger();
    } else {
      Gdx.input.setInputProcessor(stage);
    }

    axes = new Texture(Gdx.files.internal("stage/red_pixel.bmp"));
    skipFirstFrameForAutomaticScreenshot = true;
    if (checkIfAutomaticScreenshotShouldBeTaken) {
      makeAutomaticScreenshot = project.manualScreenshotExists(SCREENSHOT_MANUAL_FILE_NAME);
    }
  }
示例#10
0
  private void loadPocketPaintImageIntoCatroid(Intent intent) {
    Bundle bundle = intent.getExtras();
    String pathOfPocketPaintImage = bundle.getString(Constants.EXTRA_PICTURE_PATH_POCKET_PAINT);

    int[] imageDimensions = ImageEditing.getImageDimensions(pathOfPocketPaintImage);
    if (imageDimensions[0] < 0 || imageDimensions[1] < 0) {
      Utils.showErrorDialog(getActivity(), this.getString(R.string.error_load_image));
      return;
    }

    String actualChecksum = Utils.md5Checksum(new File(pathOfPocketPaintImage));

    // If look changed --> saving new image with new checksum and changing lookData
    if (!selectedLookData.getChecksum().equalsIgnoreCase(actualChecksum)) {
      String oldFileName = selectedLookData.getLookFileName();
      String newFileName = oldFileName.substring(oldFileName.indexOf('_') + 1);

      // HACK for https://github.com/Catrobat/Catroid/issues/81
      if (!newFileName.endsWith(".png")) {
        newFileName = newFileName + ".png";
      }

      String projectName = ProjectManager.getInstance().getCurrentProject().getName();

      try {
        File newLookFile =
            StorageHandler.getInstance()
                .copyImage(projectName, pathOfPocketPaintImage, newFileName);
        File temporaryPictureFileInPocketPaint = new File(pathOfPocketPaintImage);
        temporaryPictureFileInPocketPaint.delete(); // delete temp file in paintroid

        StorageHandler.getInstance()
            .deleteFile(
                selectedLookData.getAbsolutePath()); // reduce usage in container or delete it

        selectedLookData.setLookFilename(newLookFile.getName());
        selectedLookData.resetThumbnailBitmap();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
示例#11
0
  public SoundInfo copySoundInfoForSprite(Sprite sprite) {
    SoundInfo cloneSoundInfo = new SoundInfo();

    cloneSoundInfo.name = this.name;

    try {
      cloneSoundInfo.fileName =
          StorageHandler.getInstance()
              .copySoundFile(
                  Utils.buildPath(
                      Utils.buildProjectPath(
                          ProjectManager.getInstance().getCurrentProject().getName()),
                      Constants.SOUND_DIRECTORY,
                      fileName))
              .getName();
    } catch (IOException ioException) {
      Log.e(TAG, Log.getStackTraceString(ioException));
    }

    return cloneSoundInfo;
  }
示例#12
0
  public void setText(String text) {
    if (text == null) {
      text = "";
    }
    this.text = text;

    hashText = Utils.md5Checksum(text);
    String fileName = hashText;
    File pathToSpeechFile = new File(Constants.TEXT_TO_SPEECH_TMP_PATH);
    pathToSpeechFile.mkdirs();
    speechFile = new File(pathToSpeechFile, fileName + Constants.TEXT_TO_SPEECH_EXTENSION);
  }
示例#13
0
  public void testFileSize() throws IOException {
    for (int i = 0; i < 2; i++) {
      UtilFile.saveFileToProject(
          "testDirectory",
          i + "testsound.mp3",
          org.catrobat.catroid.test.R.raw.longtestsound,
          getInstrumentation().getContext(),
          UtilFile.FileType.TYPE_SOUND_FILE);
    }

    double expectedSizeInKilobytes = 84.2;
    assertEquals(
        "Unexpected file size String",
        String.format("%.1f KB", expectedSizeInKilobytes),
        UtilFile.getSizeAsString(testDirectory));

    for (int i = 2; i < 48; i++) {
      UtilFile.saveFileToProject(
          "testDirectory",
          i + "testsound.mp3",
          org.catrobat.catroid.test.R.raw.longtestsound,
          getInstrumentation().getContext(),
          UtilFile.FileType.TYPE_SOUND_FILE);
    }
    DecimalFormat decimalFormat = new DecimalFormat("#.0");
    String expected = decimalFormat.format(2.0) + " MB";
    assertEquals("Unexpected file size String", expected, UtilFile.getSizeAsString(testDirectory));

    PrintWriter printWriter = null;

    File testFile = new File(Utils.buildPath(testDirectory.getAbsolutePath(), "catroid.txt"));

    try {
      testFile.createNewFile();

      printWriter = new PrintWriter(testFile);
      printWriter.print("catroid");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (printWriter != null) {
        printWriter.close();
      }
    }

    assertEquals("Unexpected Filesize!", "7 Byte", UtilFile.getSizeAsString(testFile));

    UtilFile.deleteDirectory(testDirectory);
  }
示例#14
0
  private void loadPictureFromCameraIntoCatroid() {
    if (lookFromCameraUri != null) {
      String originalImagePath = lookFromCameraUri.getPath();

      int[] imageDimensions = ImageEditing.getImageDimensions(originalImagePath);
      if (imageDimensions[0] < 0 || imageDimensions[1] < 0) {
        Utils.showErrorDialog(getActivity(), getString(R.string.error_load_image));
        return;
      }
      copyImageToCatroid(originalImagePath);

      File pictureOnSdCard = new File(lookFromCameraUri.getPath());
      pictureOnSdCard.delete();
    }
  }
  @Override
  public boolean onLongClick(View view) {
    if (((BrickAdapter) getAdapter()).getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) {
      return true;
    }

    ((BrickAdapter) getAdapter()).isDragging = true;
    ((BrickAdapter) getAdapter()).setSpinnersEnabled(false);

    int itemPosition = calculateItemPositionAndTouchPointY(view);
    boolean drawingCacheEnabled = view.isDrawingCacheEnabled();

    view.setDrawingCacheEnabled(true);
    view.measure(
        MeasureSpec.makeMeasureSpec(ScreenValues.SCREEN_WIDTH, MeasureSpec.EXACTLY),
        MeasureSpec.makeMeasureSpec(
            Utils.getPhysicalPixels(WIDTH_OF_BRICK_PREVIEW_IMAGE, getContext()),
            MeasureSpec.AT_MOST));
    view.layout(0, 0, ScreenValues.SCREEN_WIDTH, view.getMeasuredHeight());
    view.setDrawingCacheBackgroundColor(Color.TRANSPARENT);

    view.buildDrawingCache(true);

    Bitmap bitmap;
    if (view.getDrawingCache() == null) {
      view.setDrawingCacheEnabled(drawingCacheEnabled);
      bitmap = getBitmapFromView(view, getMeasuredWidth(), view.getHeight());
    } else {
      bitmap = Bitmap.createBitmap(view.getDrawingCache());
    }

    view.setDrawingCacheEnabled(drawingCacheEnabled);

    startDragging(bitmap, touchPointY);

    if (!dragNewBrick) {
      setDragViewAnimation(0);
      dragNewBrick = false;
    }

    dragAndDropListener.drag(itemPosition, itemPosition);
    dimBackground = true;

    previousItemPosition = itemPosition;

    return true;
  }
 private synchronized void startRecording() {
   if (soundRecorder != null && soundRecorder.isRecording()) {
     return;
   }
   try {
     String recordPath =
         Utils.buildPath(
             Constants.TMP_PATH,
             getString(R.string.soundrecorder_recorded_filename) + Constants.RECORDING_EXTENTION);
     soundRecorder = new SoundRecorder(recordPath);
     soundRecorder.start();
     setViewsToRecordingState();
   } catch (IOException e) {
     Log.e("CATROID", "Error recording sound.", e);
     Toast.makeText(this, R.string.soundrecorder_error, Toast.LENGTH_SHORT).show();
   }
 }
示例#17
0
  public void setDeviceData(Context context) {
    // TODO add other header values
    xmlHeader.setPlatform(Constants.PLATFORM_NAME);
    xmlHeader.setPlatformVersion((double) Build.VERSION.SDK_INT);
    xmlHeader.setDeviceName(Build.MODEL);

    xmlHeader.setCatrobatLanguageVersion(Constants.CURRENT_CATROBAT_LANGUAGE_VERSION);
    xmlHeader.setApplicationBuildName(Constants.APPLICATION_BUILD_NAME);
    xmlHeader.setApplicationBuildNumber(Constants.APPLICATION_BUILD_NUMBER);

    if (context == null) {
      xmlHeader.setApplicationVersion("unknown");
      xmlHeader.setApplicationName("unknown");
    } else {
      xmlHeader.setApplicationVersion(Utils.getVersionName(context));
      xmlHeader.setApplicationName(context.getString(R.string.app_name));
    }
  }
示例#18
0
  private void copyLook(int position) {
    LookData lookData = lookDataList.get(position);

    try {
      String projectName = ProjectManager.getInstance().getCurrentProject().getName();

      StorageHandler.getInstance().copyImage(projectName, lookData.getAbsolutePath(), null);

      String imageName = lookData.getLookName() + "_" + getString(R.string.copy_look_addition);
      String imageFileName = lookData.getLookFileName();

      updateLookAdapter(imageName, imageFileName);
    } catch (IOException e) {
      Utils.showErrorDialog(getActivity(), getString(R.string.error_load_image));
      e.printStackTrace();
    }
    getActivity().sendBroadcast(new Intent(ScriptActivity.ACTION_BRICK_LIST_CHANGED));
  }
示例#19
0
 @Override
 public View getPrototypeView(Context context) {
   prototypeView = View.inflate(context, R.layout.brick_glide_to, null);
   TextView textX =
       (TextView) prototypeView.findViewById(R.id.brick_glide_to_prototype_text_view_x);
   TextView textY =
       (TextView) prototypeView.findViewById(R.id.brick_glide_to_prototype_text_view_y);
   TextView textDuration =
       (TextView) prototypeView.findViewById(R.id.brick_glide_to_prototype_text_view_duration);
   TextView times = (TextView) prototypeView.findViewById(R.id.brick_glide_to_seconds_text_view);
   textX.setText(String.valueOf(BrickValues.X_POSITION));
   textY.setText(String.valueOf(BrickValues.Y_POSITION));
   textDuration.setText(String.valueOf(BrickValues.DURATION));
   times.setText(
       context
           .getResources()
           .getQuantityString(
               R.plurals.second_plural, Utils.convertDoubleToPluralInteger(BrickValues.DURATION)));
   return prototypeView;
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_soundrecorder);

    recordLayout = (LinearLayout) findViewById(R.id.recordLayout);
    recordButton = (ImageView) findViewById(R.id.recordButton);
    recordText = (TextView) findViewById(R.id.recordText);
    recordingIndicationText = (TextView) findViewById(R.id.recording);

    recordLayout.setOnClickListener(this);

    soundRecorder = (SoundRecorder) getLastCustomNonConfigurationInstance();
    if (soundRecorder != null && soundRecorder.isRecording()) {
      setViewsToRecordingState();
    }

    Utils.checkForSdCard(this);
  }
示例#21
0
  private AlertDialog createDialogStepTwo(AlertDialog.Builder dialogBuilder) {
    AlertDialog dialog =
        dialogBuilder
            .setPositiveButton(R.string.ok, null)
            .setNegativeButton(R.string.cancel_button, null)
            .create();

    dialogView.findViewById(R.id.dialog_new_object_step_1_layout).setVisibility(View.GONE);

    ImageView imageView = (ImageView) dialogView.findViewById(R.id.dialog_new_object_look_preview);
    if (newObjectName == null) {
      newObjectName = getString(R.string.new_sprite_dialog_default_sprite_name);
    }
    newObjectName = Utils.getUniqueObjectName(newObjectName);

    imageView.setImageURI(lookUri);
    EditText editTextNewObject =
        (EditText) dialogView.findViewById(R.id.dialog_new_object_name_edit_text);
    editTextNewObject.setHint(newObjectName);
    return dialog;
  }
示例#22
0
  @Override
  public void onResume() {
    super.onResume();

    if (!Utils.checkForExternalStorageAvailableAndDisplayErrorIfNot(getActivity())) {
      return;
    }

    if (lookRenamedReceiver == null) {
      lookRenamedReceiver = new LookRenamedReceiver();
    }

    if (lookDeletedReceiver == null) {
      lookDeletedReceiver = new LookDeletedReceiver();
    }

    IntentFilter intentFilterRenameLook = new IntentFilter(ScriptActivity.ACTION_LOOK_RENAMED);
    getActivity().registerReceiver(lookRenamedReceiver, intentFilterRenameLook);

    IntentFilter intentFilterDeleteLook = new IntentFilter(ScriptActivity.ACTION_LOOK_DELETED);
    getActivity().registerReceiver(lookDeletedReceiver, intentFilterDeleteLook);

    SharedPreferences settings =
        PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());

    setShowDetails(settings.getBoolean(SHARED_PREFERENCE_NAME, false));

    handleAddButtonFromNew();

    if (isResultHandled) {
      isResultHandled = false;

      ScriptActivity scriptActivity = (ScriptActivity) getActivity();
      if (scriptActivity.getIsLookFragmentFromSetLookBrickNew()
          && scriptActivity.getIsLookFragmentHandleAddButtonHandled()) {
        switchToScriptFragment();
      }
    }
  }
示例#23
0
  private void updateLookAdapter(String name, String fileName) {
    name = Utils.getUniqueLookName(name);

    LookData lookData = new LookData();
    lookData.setLookFilename(fileName);
    lookData.setLookName(name);
    lookDataList.add(lookData);

    adapter.notifyDataSetChanged();

    if (lookDataListChangedAfterNewListener != null) {
      lookDataListChangedAfterNewListener.onLookDataListChangedAfterNew(lookData);
    }

    // scroll down the list to the new item:
    final ListView listView = getListView();
    listView.post(
        new Runnable() {
          @Override
          public void run() {
            listView.setSelection(listView.getCount() - 1);
          }
        });
  }
示例#24
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);

    ActionBar actionBar = getActionBar();
    actionBar.hide();

    Intent intent = getIntent();
    url = intent.getStringExtra(INTENT_PARAMETER_URL);
    if (url == null) {
      url = Constants.BASE_URL_HTTPS;
    }
    callingActivity = intent.getStringExtra(CALLING_ACTIVITY);

    webView = (WebView) findViewById(R.id.webView);

    webView.setWebChromeClient(
        new WebChromeClient() {
          private ProgressDialog progressCircle;

          @Override
          public void onProgressChanged(WebView view, int progress) {
            if (progressCircle == null) {
              progressCircle = new ProgressDialog(view.getContext(), R.style.WebViewLoadingCircle);
              progressCircle.setCancelable(true);
              progressCircle.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
              progressCircle.show();
            }

            if (progress == 100) {
              progressCircle.dismiss();
              progressCircle = null;
            }
          }
        });
    webView.setWebViewClient(new MyWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    String language = String.valueOf(Constants.CURRENT_CATROBAT_LANGUAGE_VERSION);
    String flavor = Constants.FLAVOR_DEFAULT;
    String version = Utils.getVersionName(getApplicationContext());
    String platform = Constants.PLATFORM_DEFAULT;
    webView
        .getSettings()
        .setUserAgentString(
            "Catrobat/" + language + " " + flavor + "/" + version + " Platform/" + platform);

    webView.loadUrl(url);

    webView.setDownloadListener(
        new DownloadListener() {
          @Override
          public void onDownloadStart(
              String url,
              String userAgent,
              String contentDisposition,
              String mimetype,
              long contentLength) {
            Log.d(
                WebViewActivity.class.getSimpleName(),
                "contentDisposition: " + contentDisposition + "   " + mimetype);

            if (getExtentionFromContentDisposition(contentDisposition)
                .contains(Constants.CATROBAT_EXTENSION)) {
              DownloadUtil.getInstance()
                  .prepareDownloadAndStartIfPossible(WebViewActivity.this, url);
            } else if (url.contains(Constants.LIBRARY_BASE_URL)) {
              String name = getMediaNameFromUrl(url);
              String mediaType = getMediaTypeFromContentDisposition(contentDisposition);
              String fileName = name + getExtentionFromContentDisposition(contentDisposition);
              String tempPath = null;
              switch (mediaType) {
                case Constants.MEDIA_TYPE_LOOK:
                  tempPath = Constants.TMP_LOOKS_PATH;
                  break;
                case Constants.MEDIA_TYPE_SOUND:
                  tempPath = Constants.TMP_SOUNDS_PATH;
              }
              String filePath = Utils.buildPath(tempPath, fileName);
              resultIntent.putExtra(MEDIA_FILE_PATH, filePath);
              DownloadUtil.getInstance()
                  .prepareMediaDownloadAndStartIfPossible(
                      WebViewActivity.this, url, mediaType, name, filePath, callingActivity);
            } else {
              DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

              request.setTitle(
                  getString(R.string.notification_download_title_pending)
                      + " "
                      + DownloadUtil.getInstance().getProjectNameFromUrl(url));
              request.setDescription(getString(R.string.notification_download_pending));
              request.setNotificationVisibility(
                  DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
              request.setDestinationInExternalPublicDir(
                  Environment.DIRECTORY_DOWNLOADS,
                  DownloadUtil.getInstance().getProjectNameFromUrl(url)
                      + ANDROID_APPLICATION_EXTENSION);
              request.setMimeType(mimetype);

              registerReceiver(
                  onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

              DownloadManager downloadManager =
                  (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
              downloadManager.enqueue(request);
            }
          }
        });
  }
示例#25
0
 private String getPathToBackPackDirectory() {
   Log.d("TAG", "getPathToBackPackDirectory() called!");
   return Utils.buildPath(
       Utils.buildProjectPath(ProjectManager.getInstance().getCurrentProject().getName()),
       Constants.BACKPACK_DIRECTORY);
 }
示例#26
0
  private boolean handleOkButton() {
    EditText editText = (EditText) dialogView.findViewById(R.id.dialog_new_object_name_edit_text);
    String newSpriteName;
    if (editText.length() == 0) {
      newSpriteName = editText.getHint().toString();
    } else {
      newSpriteName = editText.getText().toString().trim();
    }
    if (newSpriteName.contains(".")) {
      int fileExtensionPosition = newSpriteName.indexOf(".");
      newSpriteName = newSpriteName.substring(0, fileExtensionPosition);
    }

    ProjectManager projectManager = ProjectManager.getInstance();

    if (newSpriteName.equalsIgnoreCase("")) {
      Utils.showErrorDialog(getActivity(), R.string.spritename_invalid);
      return false;
    }

    if (projectManager.spriteExists(newSpriteName)) {
      Utils.showErrorDialog(getActivity(), R.string.spritename_already_exists);
      return false;
    }

    Sprite sprite = new Sprite(newSpriteName);
    projectManager.addSprite(sprite);

    LookData lookData;
    try {
      File newLookFile =
          StorageHandler.getInstance()
              .copyImage(projectManager.getCurrentProject().getName(), lookUri.getPath(), null);

      String imageFileName = newLookFile.getName();
      Utils.rewriteImageFileForStage(getActivity(), newLookFile);

      lookData = new LookData();
      lookData.setLookFilename(imageFileName);
      lookData.setLookName(newSpriteName);
    } catch (IOException exception) {
      Utils.showErrorDialog(getActivity(), R.string.error_load_image);
      exception.printStackTrace();

      return false;
    }

    sprite.getLookDataList().add(lookData);

    if (requestedAction == ActionAfterFinished.ACTION_UPDATE_SPINNER && spinnerAdapter != null) {
      Intent broadcastIntent;
      broadcastIntent = new Intent(ScriptActivity.ACTION_BRICK_LIST_CHANGED);
      getActivity().sendBroadcast(broadcastIntent);
      spinnerAdapter.refreshSpinnerAfterNewSprite(getActivity(), newSpriteName);
    } else {
      Intent broadcastIntent;
      broadcastIntent = new Intent(ScriptActivity.ACTION_SPRITES_LIST_CHANGED);
      getActivity().sendBroadcast(broadcastIntent);
    }

    if (requestedAction == ActionAfterFinished.ACTION_FORWARD_TO_NEW_OBJECT) {
      projectManager.setCurrentSprite(sprite);

      Intent intent = new Intent(getActivity(), ProgramMenuActivity.class);
      intent.putExtra(
          ProgramMenuActivity.FORWARD_TO_SCRIPT_ACTIVITY, ScriptActivity.FRAGMENT_SCRIPTS);
      startActivity(intent);
    }
    dismiss();
    return true;
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    StorageHandler.getInstance().saveProject(ProjectManager.getInstance().getCurrentProject());

    receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
    try {
      if (projectPath == null) {
        result = false;
        Log.e(TAG, "project path is null");
        return;
      }

      File directoryPath = new File(projectPath);
      String[] paths = directoryPath.list();

      if (paths == null) {
        result = false;
        Log.e(TAG, "project path is not valid");
        return;
      }

      for (int i = 0; i < paths.length; i++) {
        paths[i] = Utils.buildPath(directoryPath.getAbsolutePath(), paths[i]);
      }

      String zipFileString = Utils.buildPath(Constants.TMP_PATH, UPLOAD_FILE_NAME);
      File zipFile = new File(zipFileString);
      if (!zipFile.exists()) {
        zipFile.getParentFile().mkdirs();
        zipFile.createNewFile();
      }
      if (!UtilZip.writeToZipFile(paths, zipFileString)) {
        zipFile.delete();
        result = false;
        return;
      }

      // String deviceIMEI = UtilDeviceInfo.getDeviceIMEI(context);
      String userEmail = UtilDeviceInfo.getUserEmail(this);
      String language = UtilDeviceInfo.getUserLanguageCode(this);

      Context context = getApplicationContext();
      ServerCalls.getInstance()
          .uploadProject(
              projectName,
              projectDescription,
              zipFileString,
              userEmail,
              language,
              token,
              username,
              receiver,
              notificationId,
              context);

      zipFile.delete();
    } catch (IOException e) {
      e.printStackTrace();
      result = false;
    } catch (WebconnectionException webException) {
      serverAnswer = webException.getMessage();
      Log.e(TAG, serverAnswer);
      result = false;
    }
  }
示例#28
0
  public void testGoNStepsBackBrick() {
    ScriptActivity activity = (ScriptActivity) solo.getCurrentActivity();
    ScriptFragment fragment =
        (ScriptFragment) activity.getFragment(ScriptActivity.FRAGMENT_SCRIPTS);
    BrickAdapter adapter = fragment.getAdapter();

    int childrenCount = adapter.getChildCountFromLastGroup();
    int groupCount = adapter.getScriptCount();

    assertEquals(
        "Incorrect number of bricks.",
        2,
        solo.getCurrentViews(ListView.class).get(0).getChildCount());
    assertEquals("Incorrect number of bricks.", 1, childrenCount);

    ArrayList<Brick> projectBrickList = project.getSpriteList().get(0).getScript(0).getBrickList();
    assertEquals("Incorrect number of bricks.", 1, projectBrickList.size());

    assertEquals(
        "Wrong Brick instance.", projectBrickList.get(0), adapter.getChild(groupCount - 1, 0));
    assertNotNull("TextView does not exist.", solo.getText(solo.getString(R.string.brick_move)));

    UiTestUtils.testBrickWithFormulaEditor(
        solo,
        ProjectManager.getInstance().getCurrentSprite(),
        R.id.brick_move_n_steps_edit_text,
        STEPS_TO_MOVE,
        Brick.BrickField.STEPS,
        moveNStepsBrick);

    UiTestUtils.insertValueViaFormulaEditor(solo, R.id.brick_move_n_steps_edit_text, STEPS_TO_MOVE);

    try {
      assertEquals(
          "Wrong text in field.",
          STEPS_TO_MOVE,
          (moveNStepsBrick.getFormulaWithBrickField(Brick.BrickField.STEPS)).interpretDouble(null));
    } catch (InterpretationException interpretationException) {
      fail("Wrong text in field.");
    }

    assertEquals(
        "Value in Brick is not updated.",
        STEPS_TO_MOVE,
        Double.valueOf(
            ((TextView) solo.getView(R.id.brick_move_n_steps_edit_text))
                .getText()
                .toString()
                .replace(',', '.')));

    UiTestUtils.insertValueViaFormulaEditor(solo, R.id.brick_move_n_steps_edit_text, 1);
    TextView stepTextView = (TextView) solo.getView(R.id.brick_move_n_steps_step_text_view);
    assertTrue(
        "Specifier hasn't changed from plural to singular",
        stepTextView
            .getText()
            .equals(
                stepTextView
                    .getResources()
                    .getQuantityString(R.plurals.brick_move_n_step_plural, 1)));

    UiTestUtils.insertValueViaFormulaEditor(solo, R.id.brick_move_n_steps_edit_text, 1.4);
    stepTextView = (TextView) solo.getView(R.id.brick_move_n_steps_step_text_view);
    assertTrue(
        "Specifier hasn't changed from singular to plural",
        stepTextView
            .getText()
            .equals(
                stepTextView
                    .getResources()
                    .getQuantityString(
                        R.plurals.brick_move_n_step_plural,
                        Utils.convertDoubleToPluralInteger(1.4))));
  }
示例#29
0
  @Override
  public View getView(Context context, int brickId, BaseAdapter baseAdapter) {
    if (animationState) {
      return view;
    }
    view = View.inflate(context, R.layout.brick_glide_to, null);
    view = getViewWithAlpha(alphaValue);

    setCheckboxView(R.id.brick_glide_to_checkbox);
    final Brick brickInstance = this;

    checkbox.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            checked = isChecked;
            adapter.handleCheck(brickInstance, isChecked);
          }
        });

    TextView textX = (TextView) view.findViewById(R.id.brick_glide_to_prototype_text_view_x);
    TextView editX = (TextView) view.findViewById(R.id.brick_glide_to_edit_text_x);
    getFormulaWithBrickField(BrickField.X_DESTINATION)
        .setTextFieldId(R.id.brick_glide_to_edit_text_x);
    getFormulaWithBrickField(BrickField.X_DESTINATION).refreshTextField(view);
    editX.setOnClickListener(this);

    TextView textY = (TextView) view.findViewById(R.id.brick_glide_to_prototype_text_view_y);
    TextView editY = (TextView) view.findViewById(R.id.brick_glide_to_edit_text_y);
    getFormulaWithBrickField(BrickField.Y_DESTINATION)
        .setTextFieldId(R.id.brick_glide_to_edit_text_y);
    getFormulaWithBrickField(BrickField.Y_DESTINATION).refreshTextField(view);
    editY.setOnClickListener(this);

    TextView textDuration =
        (TextView) view.findViewById(R.id.brick_glide_to_prototype_text_view_duration);
    TextView editDuration = (TextView) view.findViewById(R.id.brick_glide_to_edit_text_duration);
    getFormulaWithBrickField(BrickField.DURATION_IN_SECONDS)
        .setTextFieldId(R.id.brick_glide_to_edit_text_duration);
    getFormulaWithBrickField(BrickField.DURATION_IN_SECONDS).refreshTextField(view);

    TextView times = (TextView) view.findViewById(R.id.brick_glide_to_seconds_text_view);

    if (getFormulaWithBrickField(BrickField.DURATION_IN_SECONDS).isSingleNumberFormula()) {
      try {
        times.setText(
            view.getResources()
                .getQuantityString(
                    R.plurals.second_plural,
                    Utils.convertDoubleToPluralInteger(
                        getFormulaWithBrickField(BrickField.DURATION_IN_SECONDS)
                            .interpretDouble(ProjectManager.getInstance().getCurrentSprite()))));
      } catch (InterpretationException interpretationException) {
        Log.d(getClass().getSimpleName(), "Couldn't interpret Formula.", interpretationException);
      }
    } else {

      // Random Number to get into the "other" keyword for values like 0.99 or 2.001 seconds or
      // degrees
      // in hopefully all possible languages
      times.setText(
          view.getResources()
              .getQuantityString(R.plurals.second_plural, Utils.TRANSLATION_PLURAL_OTHER_INTEGER));
    }

    textDuration.setVisibility(View.GONE);
    editDuration.setVisibility(View.VISIBLE);
    textX.setVisibility(View.GONE);
    editX.setVisibility(View.VISIBLE);
    textY.setVisibility(View.GONE);
    editY.setVisibility(View.VISIBLE);

    editDuration.setOnClickListener(this);
    return view;
  }
示例#30
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();

    Intent intent = getIntent();
    url = intent.getStringExtra(INTENT_PARAMETER_URL);
    if (url == null) {
      url = Constants.BASE_URL_HTTPS;
    }

    webView = (WebView) findViewById(R.id.webView);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new MyWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);

    String language = String.valueOf(Constants.CURRENT_CATROBAT_LANGUAGE_VERSION);
    String flavor = Constants.FLAVOR_DEFAULT;
    String version = Utils.getVersionName(getApplicationContext());
    String platform = Constants.PLATFORM_DEFAULT;
    webView
        .getSettings()
        .setUserAgentString(
            "Catrobat/" + language + " " + flavor + "/" + version + " Platform/" + platform);

    webView.loadUrl(url);

    webView.setDownloadListener(
        new DownloadListener() {
          @Override
          public void onDownloadStart(
              String url,
              String userAgent,
              String contentDisposition,
              String mimetype,
              long contentLength) {
            Log.e("TAG", "contentDisposition: " + contentDisposition + "   " + mimetype);
            if (contentDisposition.contains(Constants.CATROBAT_EXTENSION)) {
              DownloadUtil.getInstance()
                  .prepareDownloadAndStartIfPossible(WebViewActivity.this, url);
            } else {
              DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

              request.setTitle(
                  getString(R.string.notification_download_title_pending)
                      + " "
                      + DownloadUtil.getInstance().getProjectNameFromUrl(url));
              request.setDescription(getString(R.string.notification_download_pending));
              request.setNotificationVisibility(
                  DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
              request.setDestinationInExternalPublicDir(
                  Environment.DIRECTORY_DOWNLOADS,
                  DownloadUtil.getInstance().getProjectNameFromUrl(url)
                      + ANDROID_APPLICATION_EXTENSION);
              request.setMimeType(mimetype);

              registerReceiver(
                  onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

              DownloadManager downloadManager =
                  (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
              downloadManager.enqueue(request);
            }
          }
        });
  }