/**
  * Método que trata las acciones a ejecutar al producirse un evento
  *
  * @param c Es el evento que se ha producido (o botón que se ha pulsado)
  * @param d Es la pantalla en la que se ha producido el evento
  */
 public void commandAction(Command c, Displayable d) {
   if (c.equals(this.SELECT_COMMAND)) {
     cliente.conecta(getSelectedIndex());
   } else if (c.equals(volver)) {
     padre.commandAction(volver, this);
   } else if (c.equals(buscar)) {
     cliente.buscaDisp();
   }
 }
Beispiel #2
0
  public void commandAction(Command cmd, de.enough.polish.ui.Item item) {
    item = this.mShortcutList.getFocusedItem();

    // #debug
    System.out.println(
        "cmd: " + cmd.getLabel() + ", type: " + cmd.getCommandType() + ", item: " + item);
    if (item instanceof ShortcutItem) {
      ShortcutItem shortcut = (ShortcutItem) item;
      createShortcutEditTab(shortcut);
    }
  }
Beispiel #3
0
  public void commandAction(Command command, Displayable screen) {
    try {
      if (screen.equals(mainMenuList)) {

        int position = mainMenuList.getSelectedIndex();
        String selected = mainMenuList.getString(position);

        if (selected.equals(tr.t(Translator.CATEGORIES))) {
          level = ROOT_FILE;
          showCategory(0);
        } else if (selected.equals(tr.t(Translator.OPTIONS))) {
          optionForm.fillOptions();
          display.setCurrent(optionForm);
        } else if (selected.equals(tr.t(Translator.HELP))) {
          createHelpForm();
          display.setCurrent(form);
        } else if (selected.equals(tr.t(Translator.ABOUT))) {
          createAboutForm();
          display.setCurrent(form);
        } else if (selected.equals(tr.t(Translator.EXIT))) {
          exitMIDlet();
        }

      } else if (screen.equals(list) && command.equals(List.SELECT_COMMAND)) {
        int position = list.getSelectedIndex();
        displayedCategory.lastSelectedPosition = position;

        if (position < subCategories.size()) {
          showCategory(
              ((Integer) displayedCategory.subcategories.elementAt(position)).intValue()); // level
        } else {
          int itemPosition = position - subCategories.size();
          int itemIndex = ((Integer) displayedCategory.items.elementAt(itemPosition)).intValue();
          showItem((Item) itemsIndex.elementAt(itemIndex));
        }
      } else if (command.equals(backCommand) && screen.equals(list)) {
        if (displayedCategory.parentId != PARENT_CATEGORY_MAIN_SCREEN) {
          showCategory(displayedCategory.parentId);
        } else {
          displayMain();
        }
      } else if (command.equals(backCommand) && screen.equals(form)) {
        displayMain();
      } else if (command.equals(backCommandCanvas) && screen.equals(canvas)) {
        showCategory(lastSelectedCategoryIndex);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public Object visit(Object object) {
    Command command = (Command) object;

    BooleanFactory booleanFactory = BooleanFactory.getInstance();

    if (isNotSmallDisplay
        || command.getPriority() == 1
        || command == GameCommandsFactory.getInstance().EXIT_COMMAND
        || command == GameCommandsFactory.getInstance().EXIT_WITHOUT_PROGRESS_COMMAND) {
      return booleanFactory.TRUE;
    } else {
      return booleanFactory.FALSE;
    }
  }
Beispiel #5
0
 /**
  * Add help for a command using the command's Label and text from resource info.
  *
  * @param cmd
  * @param aKey
  * @return final
  * @author Irv Bunton
  */
 public final int appendCmdHelpRsc(Command cmd, String aKey) {
   StringItem si = new StringItem(cmd.getLabel() + ":", ResourceProviderME.get(aKey));
   // #ifdef DMIDP20
   si.setLayout(Item.LAYOUT_BOTTOM);
   // #endif
   return super.append(si);
 }
  /** @see CommandListener#commandAction(Command, Displayable) */
  public void commandAction(Command cmd, Displayable disp) {
    if (cmd.getCommandType() == Command.EXIT) {
      sim.destroyApp(false);
      sim.notifyDestroyed();
    } else {
      Display d = Sim.getDisplay();

      switch (getSelectedIndex()) {
        case 0: // Neues Spiel
          gamemode = new GameModeForm();
          d.setCurrent(gamemode);
          break;

        case 1: // Einstellungen
          d.setCurrent(new PrefForm());
          break;

        case 2: // Info
          Info.showInfo(d);
          break;

        case 3: // About
          Alert alert2 =
              new Alert(
                  "About",
                  "SimME\n by SPIESSEIN\n based on HEXI\n by Prof. Slany\n",
                  null,
                  AlertType.INFO);
          alert2.setTimeout(Alert.FOREVER);
          d.setCurrent(alert2, this);
          break;
      }
    }
  }
Beispiel #7
0
 public void commandAction(Command c, Displayable d) {
   String label = c.getLabel();
   if (label.equals("Cancel")) {
     destroyApp(true);
   } else if (label.equals("Login")) {
     validateUser(userName.getString(), password.getString());
   }
 }
Beispiel #8
0
 public void commandAction(Command c, Displayable s) {
   if (c.getCommandType() == Command.EXIT) {
     destroyApp(true);
     notifyDestroyed();
   } else if (c == mCameraCommand) showCamera();
   else if (c == mBackCommand) mDisplay.setCurrent(mMainForm);
   else if (c == mCaptureCommand) {
     capture();
   }
 }
  public void commandAction(Command cmd, Displayable d) {
    // System.out.println("WinManager.commandAction "+cmd.getLabel());

    if (cmd
        == controller.cScreen.nokiaPush) { // emulate joystick push by menu item on Nokia Series 40
      jPressed();
    } else {
      controller.protocol.queueCommand(cmd.getLabel());
    }
  }
Beispiel #10
0
  public static String commandLabel(Command c, boolean shortonly) {
    String l = shortonly ? null : c.getLongLabel();

    if (l == null || l.length() == 0) {
      l = c.getLabel();
    }
    if (l == null && l.length() == 0) {
      // #ifdef notdef
      // unfortunately there is no way to detect the command type :-(
      int t = c.getType();
      for (int i = 0; i < cmdlabels.length; ++i) {
        if (t == cmdtypes[i]) {
          l = cmdlabels[i];
          break;
        }
      }
      // #endif
      l = "???";
    }
    return l;
  }
Beispiel #11
0
  public void commandAction(Command command, Displayable display) {
    if (command == javax.microedition.lcdui.List.SELECT_COMMAND) {
      // View this verse

      // Grab the reference
      int selectedIndex = getSelectedIndex();

      if (selectedIndex != -1) {
        // Convert to cyclic history list
        selectedIndex += goBible.historyStartIndex;

        if (selectedIndex >= GoBible.HISTORY_SIZE) {
          selectedIndex -= GoBible.HISTORY_SIZE;
        }

        goBible.currentBookIndex = goBible.historyVerseIndices[selectedIndex * 3] & 0xff;
        goBible.currentChapterIndex = goBible.historyVerseIndices[selectedIndex * 3 + 1] & 0xff;
        goBible.currentVerseIndex = goBible.historyVerseIndices[selectedIndex * 3 + 2] & 0xff;

        goBible.bibleCanvas.enterLoadingMode();
        goBible.display.setCurrent(goBible.bibleCanvas);
        goBible.loadCurrentChapter();
        goBible.bibleCanvas.update();
      }
    } else {
      switch (command.getCommandType()) {
        case Command.OK:
        case Command.CANCEL:
          {
            // Revert to the previously displayed verse
            goBible.bibleCanvas.enterLoadingMode();
            goBible.display.setCurrent(goBible.bibleCanvas);
            goBible.bibleCanvas.repaint();
            goBible.loadCurrentChapter();
            goBible.showMainScreen();
            break;
          }
      }
    }
  }
 public void commandAction(final Command c, Displayable d) {
   Runnable r =
       new Runnable() {
         public void run() {
           if (c == exitCommand) {
             BlueCoveObexMIDlet.exit();
           } else if (c == clearCommand) {
             clearLog();
           } else if (c == startRunCommand) {
             TestSelector.runTest();
           } else if (c == selectTestCommand) {
             TestSelector.selectTest();
           } else if (c == continueCommand) {
             runContinue();
           } else {
             if (c != null) {
               Logger.info("Command " + c.getLabel() + " not found");
             }
           }
         }
       };
   ThreadUtils.invokeLater(r, c.getLabel());
 }
  public synchronized void commandAction(Command command, Displayable displayable) {
    try {
      String displayableAsString = NO_DISPLAYABLE;
      if (displayable != null) {
        displayableAsString = displayable.toString();
      }

      String label = NO_COMMAND;
      if (command != null) {
        label = command.getLabel();
      }

      PreLogUtil.put(
          new StringMaker()
              .append(COMMAND_NAME)
              .append(label)
              .append(DISPLAYABLE)
              .append(displayableAsString)
              .toString(),
          this,
          this.COMMAND_ACTION);

      GameCommandsFactory gameCommandsFactory = GameCommandsFactory.getInstance();

      if (command == gameCommandsFactory.SHOW_GAME_CANVAS) {
        // TWB - If progress concurrency is a problem then this is probably the cause
        if (this.getDisplay().getCurrent() != this.allbinaryGameCanvasRunnableInterface) {
          this.setDisplay((Displayable) this.allbinaryGameCanvasRunnableInterface);
        }

        this.unPauseAppBackground(false);
      } else if (command == gameCommandsFactory.CLOSE_AND_SHOW_GAME_CANVAS) {
        // this.closeMenuListener();
        MenuListener menuListener = (MenuListener) displayable;
        menuListener.close();

        this.setDisplay((Displayable) this.allbinaryGameCanvasRunnableInterface);
        this.unPauseAppBackground(false);
      } else if (command == gameCommandsFactory.EXIT_COMMAND) {
        // TWB - Handle exit for android differently
        if (GameMidletEventHandler.getInstance().getEventListenerInterfaceList().size() == 0) {
          this.exit(true);
        }

        GameMidletEventHandler.getInstance().fireEvent(null);
      } else if (command == gameCommandsFactory.EXIT_WITHOUT_PROGRESS_COMMAND) {
        this.exit(false);
      } else if (command == gameCommandsFactory.START_COMMAND
          || command == gameCommandsFactory.RESTART_COMMAND
          || command == gameCommandsFactory.CONTINUE_COMMAND) {
        // GameState gameState = GameStateFactory.getInstance(command);
        if (gameMidletStateFactory.getCurrentGameState() != GameState.PLAYING_GAME_STATE
            || command == gameCommandsFactory.RESTART_COMMAND) {
          if (this.gameStartTimeHelper.isTime()) {
            this.createGame();
            gameMidletStateFactory.setCurrentGameState(GameState.PLAYING_GAME_STATE);
          } else {
            LogUtil.put(
                LogFactory.getInstance(
                    "Starting Game Too Often", this, MidletStrings.getInstance().COMMAND_ACTION));
          }

        } else {
          LogUtil.put(LogFactory.getInstance("Already in playing state", this, COMMAND_ACTION));
        }

      } else if (command == gameCommandsFactory.BUY_COMMAND) {
        InApplicationPurchaseFactory inApplicationPurchaseFactory =
            InApplicationPurchaseFactory.getInstance();

        final BasicArrayList list = LockableFeatureFactory.getInstance().getList();
        LockableFeature lockableFeature = (LockableFeature) list.get(0);

        if (list.size() > 0 && !inApplicationPurchaseFactory.isPurchased(lockableFeature)) {
          inApplicationPurchaseFactory.purchase(lockableFeature);
          // TextNotificationUtil.getInstance().fireSuccess("In Application Purchase Request");
        } else {
          TextNotificationUtil.getInstance().fireSuccess("Already Purchased");
        }
      } else if (command == gameCommandsFactory.QUIT_COMMAND) {
        if (this.gameStartTimeHelper.isTime()) {
          this.stopGameCanvasRunnableInterface();
          gameMidletStateFactory.setCurrentGameState(GameState.NO_GAME_STATE);
          this.setDemo();
        }
      } else if (command == MyCommandsFactory.getInstance().RESUME_COMMAND) {
        this.unPauseAppBackground(false);
      } else if (command == MyCommandsFactory.getInstance().PAUSE_COMMAND) {
        this.pauseAppBackground(false);
      } else if (command == MyCommandsFactory.getInstance().SET_DISPLAYABLE) {
        this.pauseAppBackground(false);

        this.setDisplay(displayable);
      } else if (command == gameCommandsFactory.SET_MENU_DISPLAYABLE) {
        this.pauseAppBackground(false);

        MenuListener menuListener = (MenuListener) displayable;
        menuListener.open();

        this.setDisplay(displayable);
      } else if (command == gameCommandsFactory.START_TRACE) {
        this.debugInterface.start();
        ((AllBinaryGameCanvas) this.allbinaryGameCanvasRunnableInterface)
            .addCommand(gameCommandsFactory.STOP_TRACE);
        ((AllBinaryGameCanvas) this.allbinaryGameCanvasRunnableInterface)
            .removeCommand(gameCommandsFactory.START_TRACE);
      } else if (command == gameCommandsFactory.STOP_TRACE) {
        this.pauseAppBackground(false);
        this.debugInterface.stop();
        this.unPauseAppBackground(false);
        ((AllBinaryGameCanvas) this.allbinaryGameCanvasRunnableInterface)
            .addCommand(gameCommandsFactory.START_TRACE);
        ((AllBinaryGameCanvas) this.allbinaryGameCanvasRunnableInterface)
            .removeCommand(gameCommandsFactory.STOP_TRACE);
      } else if (command == gameCommandsFactory.DEFAULT_OPTIONS) {
        Displayable tempDisplayable = displayable;
        if (tempDisplayable instanceof GameOptionsForm) {
          GameFeatureFormUtil.getInstance().setDefault((CommandForm) tempDisplayable);
        }
      } else if (command == GameInputMappingInstructionsCanvas.DISPLAY) {
        Displayable tempDisplayable = displayable;
        if (tempDisplayable instanceof GameInputMappingCanvas) {
          GameInputMappingCanvas gameInputMappingCanvas = (GameInputMappingCanvas) tempDisplayable;
          gameInputMappingCanvas.update();
        }

        this.commandAction(
            gameCommandsFactory.SET_MENU_DISPLAYABLE, this.getInputMappingInstructionsCanvas());

        // this.setDisplay((Displayable) this.getInputMappingInstructionsCanvas());
      } else if (HighScoreCommandsFactory.getInstance().isHighScoreCommand(command)) {
        Displayable tempDisplayable = displayable;
        if (tempDisplayable instanceof HighScoresCanvas) {
          HighScoresCanvas highScoresCanvas = (HighScoresCanvas) tempDisplayable;

          highScoresCanvas.updateCommand(command);
        }
      } else if (command == HighScoreCommands.getInstance().DISPLAY) {
        this.commandAction(gameCommandsFactory.SET_MENU_DISPLAYABLE, this.createHighScoresCanvas());
      } else if (command == GameInputMappingInstructionsCanvas.CLOSE) {
        MenuListener menuListener = (MenuListener) displayable;
        menuListener.close();

        this.commandAction(GameInputMappingCanvas.DISPLAY, null);
      } else if (command == GameInputMappingCanvas.DISPLAY) {
        // TWB - Called for HTML5 but not others?
        Features features = Features.getInstance();

        if (features.isDefault(HTMLFeatureFactory.getInstance().HTML)) {
          this.pauseAppBackground(false);
        }

        this.commandAction(gameCommandsFactory.SET_MENU_DISPLAYABLE, this.getInputMappingCanvas());

        // this.setDisplay((Displayable) this.getInputMappingCanvas());
      } else if (command == GameInputMappingCanvas.DEFAULT) {
        Displayable tempDisplayable = displayable;
        if (tempDisplayable instanceof GameInputMappingCanvas) {
          GameInputMappingCanvas gameInputMappingCanvas = (GameInputMappingCanvas) tempDisplayable;
          gameInputMappingCanvas.setDefault();
        }
      } else if (command == InGameOptionsForm.DISPLAY) {
        this.pauseAppBackground(false);

        ProgressCanvas progressCanvas = ProgressCanvasFactory.getInstance();

        progressCanvas.addPortion(50, "In Game Options");

        AllBinaryGameLayerManager layerManager = this.createGameLayerManager();

        InGameOptionsFormFactory.init(
            this,
            new InGameFeatures(),
            "Options In Game",
            layerManager.getBackgroundBasicColor(),
            layerManager.getForegroundBasicColor());

        InGameOptionsForm inGameOptionsForm = InGameOptionsFormFactory.getInstance();

        inGameOptionsForm.setItemStateListener(this.allbinaryGameCanvasRunnableInterface);

        this.commandAction(gameCommandsFactory.SET_MENU_DISPLAYABLE, inGameOptionsForm);
      } else if (command == InGameOptionsForm.DEFAULT) {
        GameFeatureFormUtil.getInstance().setDefault(InGameOptionsFormFactory.getInstance());
      } else if (command == gameCommandsFactory.DISPLAY_OPTIONS) {
        AllBinaryMediaManager.setMuted(true);
        this.stopAll();

        MainFeatureFactory mainFeatureFactory = MainFeatureFactory.getInstance();
        Features features = Features.getInstance();

        isFullScreen = features.isFeature(mainFeatureFactory.FULL_SCREEN);

        // PreLogUtil.put("Open isFullScreen: " + isFullScreen, this,
        // MidletStrings.getInstance().COMMAND_ACTION);

        ResizableListenerHandler.getInstance().fireEvent(true);

        this.setResized(false);

        this.commandAction(gameCommandsFactory.SET_MENU_DISPLAYABLE, this.getGameOptionsForm());
      } else if (command == gameCommandsFactory.CLOSE_OPTIONS) {
        // PreLogUtil.put("Close", this, MidletStrings.getInstance().COMMAND_ACTION);
        ResizableListenerHandler.getInstance().fireEvent(false);

        this.commandAction(gameCommandsFactory.CLOSE_AND_SHOW_GAME_CANVAS, displayable);

        StringMaker stringBuffer = new StringMaker();
        stringBuffer.append("Close isFullScreen/change: ");
        stringBuffer.append(isFullScreen);
        stringBuffer.append(FullScreenUtil.isScreenChange(isFullScreen));
        stringBuffer.append(" isResized: ");
        stringBuffer.append(this.isResized());

        PreLogUtil.put(stringBuffer.toString(), this, COMMAND_ACTION);

        // Restart canvas if screen change
        if (this.isResized() || FullScreenUtil.isScreenChange(isFullScreen)) {
          // PreLogUtil.put("Resized/Changed", this, MidletStrings.getInstance().COMMAND_ACTION);

          this.updateFullScreen();
        }

        AllBinaryMediaManager.setMuted(false);
      } else if (command == gameCommandsFactory.DISPLAY_LOAD_FORM) {
        this.pauseAppBackground(false);

        KeyValuePersistance keyValuePersistance = GamePersistanceSingleton.getInstance();

        keyValuePersistance.clear();
        keyValuePersistance.loadAll();

        if (this.getLoadGameForm() == null) {
          AllBinaryGameLayerManager layerManager = this.createGameLayerManager();

          this.setLoadGameForm(
              new LoadGameForm(
                  this,
                  "Load Game",
                  layerManager.getBackgroundBasicColor(),
                  layerManager.getForegroundBasicColor()));
        } else {
          this.getLoadGameForm().update();
        }

        this.commandAction(gameCommandsFactory.SET_MENU_DISPLAYABLE, this.getLoadGameForm());

        // this.setDisplay((Displayable) this.getLoadGameForm());
      } else if (command == gameCommandsFactory.LOAD_FILE) {
        int index = this.getLoadGameForm().getSelectedId();

        if (index != -1) {
          KeyValuePersistance keyValuePersistance = GamePersistanceSingleton.getInstance();

          this.setStartStateHashtable(keyValuePersistance.get(index));

          MenuListener menuListener = this.getLoadGameForm();
          menuListener.close();

          PreLogUtil.put(BasicMotionGesturesHandler.getInstance().toString(), this, COMMAND_ACTION);

          this.commandAction(gameCommandsFactory.START_COMMAND, null);

          PreLogUtil.put(BasicMotionGesturesHandler.getInstance().toString(), this, COMMAND_ACTION);
        }
      } else if (command == gameCommandsFactory.DELETE_FILE) {
        int index = this.getLoadGameForm().getSelectedText();

        if (index != -1) {
          KeyValuePersistance keyValuePersistance = GamePersistanceSingleton.getInstance();

          keyValuePersistance.delete(index);
          keyValuePersistance.clear();
          keyValuePersistance.loadAll(1);
          this.getLoadGameForm().update();
        }
      }
      /*
      else if (command == GameCommands.DISPLAY_SAVE_FORM)
      {
      this.pauseApp();
      this.setDisplay((Displayable) this.getSaveGameForm());
      }*/
      else if (command == gameCommandsFactory.SAVE) {
        KeyValuePersistance keyValuePersistance = GamePersistanceSingleton.getInstance();

        this.pauseAppBackground(false);
        // String name = ((SaveGameForm) this.getSaveGameForm()).getText();
        keyValuePersistance.save(this.getCurrentStateHashtable());

        // this.setDisplay((Displayable) allbinaryGameCanvasRunnableInterface);

        this.unPauseAppBackground(false);
      } else if (command == HighScoreTextBox.SUBMIT_TEXTBOX_COMMAND) {
        LogUtil.put(LogFactory.getInstance("Submitted Score", this, COMMAND_ACTION));

        this.allbinaryGameCanvasRunnableInterface.setHighScoreSubmitted(true);

        this.commandAction(gameCommandsFactory.CLOSE_AND_SHOW_GAME_CANVAS, displayable);
      } else if (command == gameCommandsFactory.DISPLAY_ABOUT) {
        this.commandAction(gameCommandsFactory.SET_MENU_DISPLAYABLE, this.getAboutCanvas());
      } else if (command == gameCommandsFactory.TOGGLE_KEYBOARD) {
        VirtualKeyboardEventHandler virtualKeyboardEventHandler =
            VirtualKeyboardEventHandler.getInstance();

        virtualKeyboardEventHandler.fireEvent(virtualKeyboardEventHandler.SHOW_EVENT);
      } else if (command.getLabel().compareTo(gameCommandsFactory.TOGGLE_FULLSCREEN.getLabel())
          == 0) {
        MainFeatureFactory mainFeatureFactory = MainFeatureFactory.getInstance();

        Features features = Features.getInstance();

        boolean isFullScreen = features.isFeature(mainFeatureFactory.FULL_SCREEN);

        if (isFullScreen) {
          features.removeDefault(mainFeatureFactory.FULL_SCREEN);
        } else {
          features.addDefault(mainFeatureFactory.FULL_SCREEN);
        }

        this.updateFullScreen();
      }

      // no else
      // if (command != gameCommandsFactory.START_COMMAND && command !=
      // gameCommandsFactory.RESTART_COMMAND)
      // {
      // gameMidletStateFactory.setCurrentGameState(GameState.NO_GAME_STATE);
      // }

    } catch (Exception e) {
      LogUtil.put(
          LogFactory.getInstance(
              CommonStrings.getInstance().EXCEPTION,
              this,
              MidletStrings.getInstance().COMMAND_ACTION,
              e));
      if (command != GameCommandsFactory.getInstance().EXIT_COMMAND) {
        this.exit(false);
      }
    }
  }
 public void commandAction(Command command, Displayable display) {
   getController().control(command.getCommandType());
 }
  public boolean handleCommand(Command command) {
    String label = command.getLabel();
    System.out.println("<* MediaController.handleCommand() *> " + label);

    /** Case: Save Add photo * */
    if (label.equals("Add")) {
      ScreenSingleton.getInstance().setCurrentScreenName(Constants.ADDPHOTOTOALBUM_SCREEN);
      AddMediaToAlbum form = new AddMediaToAlbum("Add new item to Album");
      form.setCommandListener(this);
      setCurrentScreen(form);
      return true;

    }
    // #ifdef includePhoto
    // [NC] Added in the scenario 07
    else if (label.equals("View")) {
      String selectedImageName = getSelectedMediaName();
      showImage(selectedImageName);
      // #ifdef includeSorting
      // [EF] Added in the scenario 02
      incrementCountViews(selectedImageName);
      // #endif
      ScreenSingleton.getInstance().setCurrentScreenName(Constants.IMAGE_SCREEN);
      return true;
    }
    // #endif

    // #ifdef includeMusic
    // [NC] Added in the scenario 07
    else if (label.equals("Play")) {
      String selectedMediaName = getSelectedMediaName();
      return playMusicMedia(selectedMediaName);
    }
    // #endif

    // #ifdef includeVideo
    // [NC] Added in the scenario 08
    else if (label.equals("Play Video")) {
      String selectedMediaName = getSelectedMediaName();
      return playVideoMedia(selectedMediaName);
    }
    // #endif

    // #ifdef captureVideo
    // [NC] Added in the scenario 08
    else if (label.equals("Capture Video")) {

      CaptureVideoScreen playscree =
          new CaptureVideoScreen(midlet, CaptureVideoScreen.CAPTUREVIDEO);
      playscree.setVisibleVideo();
      VideoCaptureController controller =
          new VideoCaptureController(
              midlet, getAlbumData(), (AlbumListScreen) getAlbumListScreen(), playscree);
      this.setNextController(controller);
      playscree.setCommandListener(this);
      return true;
    }
    // #endif

    // #ifdef capturePhoto
    // [NC] Added in the scenario 08
    else if (label.equals("Capture Photo")) {
      CaptureVideoScreen playscree =
          new CaptureVideoScreen(midlet, CaptureVideoScreen.CAPTUREPHOTO);
      playscree.setVisibleVideo();
      PhotoViewController controller =
          new PhotoViewController(
              midlet, getAlbumData(), (AlbumListScreen) getAlbumListScreen(), "New photo");
      controller.setCpVideoScreen(playscree);
      this.setNextController(controller);
      playscree.setCommandListener(this);
      return true;
    }
    // #endif

    else if (label.equals("Save Item")) {
      try {
        getAlbumData()
            .addNewMediaToAlbum(
                ((AddMediaToAlbum) getCurrentScreen()).getItemName(),
                ((AddMediaToAlbum) getCurrentScreen()).getPath(),
                getCurrentStoreName());
        // #ifdef includeMusic
        // [NC] Added in the scenario 07
        if (getAlbumData() instanceof MusicAlbumData) {
          getAlbumData().loadMediaDataFromRMS(getCurrentStoreName());
          MediaData mymedia =
              getAlbumData().getMediaInfo(((AddMediaToAlbum) getCurrentScreen()).getItemName());
          mymedia.setTypeMedia(((AddMediaToAlbum) getCurrentScreen()).getItemType());
          getAlbumData().updateMediaInfo(mymedia, mymedia);
          //					MultiMediaData mmedi = new MultiMediaData(mymedia, ((AddMediaToAlbum)
          // getCurrentScreen()).getItemType());
          //					getAlbumData().updateMediaInfo(mymedia, mmedi);
        }
        // #endif

      } catch (InvalidImageDataException e) {
        Alert alert = null;
        if (e instanceof ImagePathNotValidException)
          alert = new Alert("Error", "The path is not valid", null, AlertType.ERROR);
        else alert = new Alert("Error", "The file format is not valid", null, AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
        return true;
        // alert.setTimeout(5000);
      } catch (PersistenceMechanismException e) {
        Alert alert = null;
        if (e.getCause() instanceof RecordStoreFullException)
          alert = new Alert("Error", "The mobile database is full", null, AlertType.ERROR);
        else
          alert =
              new Alert(
                  "Error", "The mobile database can not add a new photo", null, AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
      }
      // #ifdef includeMusic
      // [NC] Added in the scenario 07
      catch (ImageNotFoundException e) {
        Alert alert =
            new Alert(
                "Error",
                "The selected item was not found in the mobile device",
                null,
                AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
        return true;
      }
      // #endif
      return goToPreviousScreen();
      /** Case: Delete selected Photo from recordstore * */
    } else if (label.equals("Delete")) {
      String selectedMediaName = getSelectedMediaName();
      try {
        getAlbumData().deleteMedia(getCurrentStoreName(), selectedMediaName);
      } catch (PersistenceMechanismException e) {
        Alert alert =
            new Alert(
                "Error", "The mobile database can not delete this item", null, AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
        return true;
      } catch (ImageNotFoundException e) {
        Alert alert =
            new Alert(
                "Error",
                "The selected item was not found in the mobile device",
                null,
                AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
        return true;
      }
      showMediaList(getCurrentStoreName(), false, false);
      ScreenSingleton.getInstance().setCurrentScreenName(Constants.IMAGELIST_SCREEN);
      return true;

      /** Case: Edit photo label [EF] Added in the scenario 02 */
    } else if (label.equals("Edit Label")) {
      String selectedImageName = getSelectedMediaName();
      try {
        media = getAlbumData().getMediaInfo(selectedImageName);
        // PhotoController photoController = new PhotoController(image,
        // this);
        NewLabelScreen formScreen =
            new NewLabelScreen("Edit Label Item", NewLabelScreen.LABEL_PHOTO);
        formScreen.setCommandListener(this);
        this.setScreen(formScreen);
        setCurrentScreen(formScreen);
        formScreen = null;
      } catch (ImageNotFoundException e) {
        Alert alert =
            new Alert(
                "Error",
                "The selected item was not found in the mobile device",
                null,
                AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
      }
      return true;

      // #ifdef includeSorting
      /** Case: Sort photos by number of views [EF] Added in the scenario 02 */
    } else if (label.equals("Sort by Views")) {
      showMediaList(getCurrentStoreName(), true, false);
      ScreenSingleton.getInstance().setCurrentScreenName(Constants.IMAGELIST_SCREEN);

      return true;
      // #endif

      // #ifdef includeFavourites
      /** Case: Set photo as favorite [EF] Added in the scenario 03 */
    } else if (label.equals("Set Favorite")) {
      String selectedMediaName = getSelectedMediaName();
      try {
        MediaData media = getAlbumData().getMediaInfo(selectedMediaName);
        media.toggleFavorite();
        updateMedia(media);
        System.out.println(
            "<* BaseController.handleCommand() *> Image = "
                + selectedMediaName
                + "; Favorite = "
                + media.isFavorite());
      } catch (ImageNotFoundException e) {
        Alert alert =
            new Alert(
                "Error",
                "The selected item was not found in the mobile device",
                null,
                AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
      } catch (InvalidImageDataException e) {
        Alert alert = null;
        if (e instanceof ImagePathNotValidException)
          alert = new Alert("Error", "The path is not valid", null, AlertType.ERROR);
        else
          alert = new Alert("Error", "The image file format is not valid", null, AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
      } catch (PersistenceMechanismException e) {
        Alert alert = null;
        if (e.getCause() instanceof RecordStoreFullException)
          alert = new Alert("Error", "The mobile database is full", null, AlertType.ERROR);
        else
          alert =
              new Alert(
                  "Error",
                  "The mobile database can not update new informations",
                  null,
                  AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
      }
      return true;

      /** Case: View favorite photos [EF] Added in the scenario 03 */
    } else if (label.equals("View Favorites")) {
      showMediaList(getCurrentStoreName(), false, true);
      ScreenSingleton.getInstance().setCurrentScreenName(Constants.IMAGELIST_SCREEN);

      return true;
      // #endif

      /** Case: Save new Photo Label */
    } else if (label.equals("Save")) {
      System.out.println(
          "<* PhotoController.handleCommand() *> Save Photo Label = " + this.screen.getLabelName());
      this.getMedia().setMediaLabel(this.screen.getLabelName());
      try {
        updateMedia(media);
      } catch (InvalidImageDataException e) {
        Alert alert = null;
        if (e instanceof ImagePathNotValidException)
          alert = new Alert("Error", "The path is not valid", null, AlertType.ERROR);
        else
          alert = new Alert("Error", "The image file format is not valid", null, AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
      } catch (PersistenceMechanismException e) {
        Alert alert =
            new Alert(
                "Error", "The mobile database can not update this photo", null, AlertType.ERROR);
        Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
      }
      return goToPreviousScreen();

      /** Case: Go to the Previous or Fallback screen * */
    } else if (label.equals("Back")) {
      return goToPreviousScreen();

      /** Case: Cancel the current screen and go back one* */
    } else if (label.equals("Cancel")) {
      return goToPreviousScreen();
    }
    return false;
  }
Beispiel #16
0
 /**
  * WARNING: Can only be used in JavaSE environments! Serializes the specified object.
  *
  * @param object the object
  * @param out the stream into which the object should be serialized
  * @param useObfuscation true when classnames are obfuscated
  * @throws IOException when serialization data could not be written or when encountering an object
  *     that cannot be serialized
  */
 public static void serialize(Object object, DataOutputStream out, boolean useObfuscation)
     throws IOException {
   // #endif
   out.writeByte(VERSION);
   boolean isNull = (object == null);
   out.writeBoolean(isNull);
   if (!isNull) {
     if (object instanceof Externalizable) {
       out.writeByte(TYPE_EXTERNALIZABLE);
       String className = object.getClass().getName();
       // #if polish.JavaSE
       if (useObfuscation && obfuscationSerializeMap != null) {
         String obfuscatedClassName = (String) obfuscationSerializeMap.get(className);
         if (obfuscatedClassName != null) {
           // System.out.println("Serializer.serialize: translating classname from " + className +
           // " to " +  obfuscatedClassName +  " useObfuscationIndicator=" +
           // useObfuscationIndicator.get() );
           className = obfuscatedClassName;
         }
       }
       // #endif
       // #debug debug
       // #= System.out.println("serializing " + className + "=" + object);
       out.writeUTF(className);
       ((Externalizable) object).write(out);
     } else if (object instanceof Externalizable[]) {
       out.writeByte(TYPE_EXTERNALIZABLE_ARRAY);
       String cn = object.getClass().getName();
       cn = cn.substring(cn.lastIndexOf('[') + 2, cn.length() - 1);
       // #if polish.JavaSE
       if (useObfuscation && obfuscationSerializeMap != null) {
         String obfuscatedClassName = (String) obfuscationSerializeMap.get(cn);
         if (obfuscatedClassName != null) {
           // System.out.println("Serializer.serialize: translating classname from " + className +
           // " to " +  obfuscatedClassName );
           cn = obfuscatedClassName;
         }
       }
       // #endif
       out.writeUTF(cn);
       Externalizable[] externalizables = (Externalizable[]) object;
       out.writeInt(externalizables.length);
       Hashtable classNames = new Hashtable();
       Class lastClass = null;
       byte lastId = 0;
       byte idCounter = 0;
       for (int i = 0; i < externalizables.length; i++) {
         Externalizable externalizable = externalizables[i];
         Class currentClass = externalizable.getClass();
         if (currentClass == lastClass) {
           out.writeByte(lastId);
         } else {
           Byte knownId = (Byte) classNames.get(currentClass);
           if (knownId != null) {
             out.writeByte(knownId.byteValue());
           } else {
             // this is a class that has not yet been encountered:
             out.writeByte(0);
             idCounter++;
             String className = currentClass.getName();
             // #if polish.JavaSE
             if (useObfuscation && obfuscationSerializeMap != null) {
               String obfuscatedClassName = (String) obfuscationSerializeMap.get(className);
               if (obfuscatedClassName != null) {
                 // System.out.println("Serializer.serialize: translating classname from " +
                 // className + " to " +  obfuscatedClassName );
                 className = obfuscatedClassName;
               }
             }
             // #endif
             // #debug debug
             // #= System.out.println("serializing " + className + "=" + object);
             out.writeUTF(className);
             lastClass = currentClass;
             lastId = idCounter;
             classNames.put(currentClass, new Byte(lastId));
           }
         }
         externalizable.write(out);
       }
     } else if (object instanceof Object[]) {
       out.writeByte(TYPE_OBJECT_ARRAY);
       Object[] objects = (Object[]) object;
       out.writeInt(objects.length);
       for (int i = 0; i < objects.length; i++) {
         Object obj = objects[i];
         serialize(obj, out);
       }
     } else if (object instanceof Byte) {
       out.writeByte(TYPE_BYTE);
       out.writeByte(((Byte) object).byteValue());
     } else if (object instanceof Short) {
       out.writeByte(TYPE_SHORT);
       out.writeShort(((Short) object).shortValue());
     } else if (object instanceof Integer) {
       out.writeByte(TYPE_INTEGER);
       out.writeInt(((Integer) object).intValue());
     } else if (object instanceof Long) {
       out.writeByte(TYPE_LONG);
       out.writeLong(((Long) object).longValue());
       // #if polish.hasFloatingPoint
     } else if (object instanceof Float) {
       out.writeByte(TYPE_FLOAT);
       out.writeFloat(((Float) object).floatValue());
     } else if (object instanceof Double) {
       out.writeByte(TYPE_DOUBLE);
       out.writeDouble(((Double) object).doubleValue());
       // #endif
     } else if (object instanceof String) {
       out.writeByte(TYPE_STRING);
       out.writeUTF((String) object);
     } else if (object instanceof StringBuffer) {
       out.writeByte(TYPE_STRING_BUFFER);
       out.writeUTF(((StringBuffer) object).toString());
     } else if (object instanceof Character) {
       out.writeByte(TYPE_CHARACTER);
       out.writeChar(((Character) object).charValue());
     } else if (object instanceof Boolean) {
       out.writeByte(TYPE_BOOLEAN);
       out.writeBoolean(((Boolean) object).booleanValue());
     } else if (object instanceof Date) {
       out.writeByte(TYPE_DATE);
       out.writeLong(((Date) object).getTime());
     } else if (object instanceof Calendar) {
       out.writeByte(TYPE_CALENDAR);
       out.writeLong(((Calendar) object).getTime().getTime());
     } else if (object instanceof Random) {
       out.writeByte(TYPE_RANDOM);
     } else if (object instanceof Hashtable) {
       out.writeByte(TYPE_HASHTABLE);
       Hashtable table = (Hashtable) object;
       out.writeInt(table.size());
       Enumeration enumeration = table.keys();
       while (enumeration.hasMoreElements()) {
         Object key = enumeration.nextElement();
         serialize(key, out);
         Object value = table.get(key);
         serialize(value, out);
       }
     } else if (object instanceof Vector) { // also serializes stacks
       if (object instanceof Stack) {
         out.writeByte(TYPE_STACK);
       } else {
         out.writeByte(TYPE_VECTOR);
       }
       Vector vector = (Vector) object;
       int size = vector.size();
       out.writeInt(size);
       for (int i = 0; i < size; i++) {
         serialize(vector.elementAt(i), out);
       }
       // #if polish.midp2
     } else if (object instanceof Image) {
       out.writeByte(TYPE_IMAGE);
       // #if polish.JavaSE
       boolean handled = false;
       // we are within a Java SE environment. When the J2ME Polish runtime librarby is used, we
       // can
       // store the image in PNG format instead of in the much more verbose RGB format:
       try {
         // #if false
         Field bufferedImageField = null;
         // #else
         // # Field bufferedImageField = object.getClass().getDeclaredField("bufferedImage");
         // #endif
         bufferedImageField.setAccessible(true);
         BufferedImage bufferedImage = (BufferedImage) bufferedImageField.get(object);
         ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
         ImageIO.write(bufferedImage, "png", byteOut);
         out.writeByte(TYPE_IMAGE_BYTES);
         byte[] data = byteOut.toByteArray();
         out.writeInt(data.length);
         for (int i = 0; i < data.length; i++) {
           out.writeByte(data[i]);
         }
         handled = true;
       } catch (Exception e) {
         e.printStackTrace();
         // #debug warn
         System.out.println(
             "Warning: Unable to retrieve bufferedImage field of javax.microedition.lcdui.Image - probably the enough-polish-runtime library is not used.");
       }
       if (!handled) {
         // #endif
         Image image = (Image) object;
         out.writeByte(TYPE_IMAGE_RGB);
         int width = image.getWidth();
         int height = image.getHeight();
         out.writeInt(width);
         out.writeInt(height);
         int[] rgb = new int[width * height];
         image.getRGB(rgb, 0, width, 0, 0, width, height);
         for (int i = 0; i < rgb.length; i++) {
           out.writeInt(rgb[i]);
         }
         // #if polish.JavaSE
       }
       // #endif
       // #endif
       // #if polish.midp
     } else if (object instanceof Font) {
       out.writeByte(TYPE_FONT);
       Font font = (Font) object;
       out.writeInt(font.getFace());
       out.writeInt(font.getStyle());
       out.writeInt(font.getSize());
     } else if (object instanceof Command) {
       out.writeByte(TYPE_COMMAND);
       Command command = (Command) object;
       out.writeInt(command.getCommandType());
       out.writeInt(command.getPriority());
       out.writeUTF(command.getLabel());
       // #endif
     } else if (object instanceof byte[]) {
       out.writeByte(TYPE_BYTE_ARRAY);
       byte[] numbers = (byte[]) object;
       out.writeInt(numbers.length);
       out.write(numbers, 0, numbers.length);
     } else if (object instanceof short[]) {
       out.writeByte(TYPE_SHORT_ARRAY);
       short[] numbers = (short[]) object;
       out.writeInt(numbers.length);
       for (int i = 0; i < numbers.length; i++) {
         short number = numbers[i];
         out.writeShort(number);
       }
     } else if (object instanceof int[]) {
       out.writeByte(TYPE_INT_ARRAY);
       int[] numbers = (int[]) object;
       out.writeInt(numbers.length);
       for (int i = 0; i < numbers.length; i++) {
         int number = numbers[i];
         out.writeInt(number);
       }
     } else if (object instanceof long[]) {
       out.writeByte(TYPE_LONG_ARRAY);
       long[] numbers = (long[]) object;
       out.writeInt(numbers.length);
       for (int i = 0; i < numbers.length; i++) {
         long number = numbers[i];
         out.writeLong(number);
       }
       // #if polish.hasFloatingPoint
     } else if (object instanceof float[]) {
       out.writeByte(TYPE_FLOAT_ARRAY);
       float[] numbers = (float[]) object;
       out.writeInt(numbers.length);
       for (int i = 0; i < numbers.length; i++) {
         float number = numbers[i];
         out.writeFloat(number);
       }
     } else if (object instanceof double[]) {
       out.writeByte(TYPE_DOUBLE_ARRAY);
       double[] numbers = (double[]) object;
       out.writeInt(numbers.length);
       for (int i = 0; i < numbers.length; i++) {
         double number = numbers[i];
         out.writeDouble(number);
       }
       // #endif
     } else if (object instanceof char[]) {
       out.writeByte(TYPE_CHAR_ARRAY);
       char[] characters = (char[]) object;
       out.writeInt(characters.length);
       for (int i = 0; i < characters.length; i++) {
         char c = characters[i];
         out.writeChar(c);
       }
     } else if (object instanceof boolean[]) {
       out.writeByte(TYPE_BOOLEAN_ARRAY);
       boolean[] bools = (boolean[]) object;
       out.writeInt(bools.length);
       for (int i = 0; i < bools.length; i++) {
         boolean b = bools[i];
         out.writeBoolean(b);
       }
     } else if (object instanceof String[]) {
       out.writeByte(TYPE_STRING_ARRAY);
       String[] strings = (String[]) object;
       out.writeInt(strings.length);
       for (int i = 0; i < strings.length; i++) {
         String s = strings[i];
         out.writeUTF(s);
       }
     } else {
       throw new IOException("Cannot serialize " + object.getClass().getName());
     }
   }
 }