Exemplo n.º 1
0
  public SettingsView(ZimbraME midlet, Settings settings) {
    super(midlet);

    mSettings = settings;

    // #style SettingsView
    TabbedForm f =
        new TabbedForm(
            Locale.get("main.Settings"),
            new String[] {
              Locale.get("settings.General"),
              Locale.get("settings.Display"),
              // Locale.get("settings.Mail"),
              Locale.get("settings.Shortcuts")
            },
            null);

    // #if true
    // # mView = f;
    // #endif

    f.setItemStateListener(this);
    f.setTabbedFormListener(this);

    createGeneralTab();
    createDisplayTab();
    createShortcutsTab();

    f.addCommand(SAVE);
    f.setCommandListener(this);
    f.setItemStateListener(this);
  }
Exemplo n.º 2
0
 /** Creates a new html tag handler */
 public HtmlTagHandler() {
   // #ifdef polish.i18n.useDynamicTranslations
   if (Locale.get("polish.command.followlink") != CMD_LINK.getLabel()) {
     CMD_LINK = new Command(Locale.get("polish.command.followlink"), Command.OK, 2);
     CMD_SUBMIT = new Command(Locale.get("polish.command.submit"), Command.ITEM, 2);
     CMD_BACK = new Command(Locale.get("polish.command.back"), Command.BACK, 10);
   }
   // #endif
   STYLE_LINE_BREAK.layout = Item.LAYOUT_NEWLINE_AFTER;
 }
 protected Item[] createStaticItems() {
   if (null == iden)
     return new Item[] {
       this.titleitem =
           new TitleBarItem(Locale.get("nowplus.client.java.webaccounts.add.title"), getModel())
     };
   else
     return new Item[] {
       this.titleitem =
           new TitleBarItem(Locale.get("nowplus.client.java.webaccounts.edit.title"), getModel())
     };
 }
Exemplo n.º 4
0
 public void commandAction(Command c, Displayable d) {
   if (processorThread.isAlive()) {
     logger.error(Locale.get("fsdiscover.StillBusyTryAgain") /*Still busy, try again later*/);
     return;
   }
   if (c == BACK_CMD) {
     /**
      * Need to call sl.selectedFile() before calling parent.show(), as we need to keep track of
      * state for e.g. GuiDiscover
      */
     sl.selectionCanceled();
     parent.show();
     return;
   }
   if (c == ROOT_CMD) {
     url = "file:///";
     processorThread = new Thread(this);
     processorThread.start();
     return;
   }
   if (list.getSelectedIndex() < 0) {
     logger.error(Locale.get("fsdiscover.NoElementSelected") /*No element selected*/);
     return;
   }
   if (c == OK_CMD) {
     selectEntry();
     return;
   }
   if (c == DOWN_CMD) {
     if (list.getString(list.getSelectedIndex()).equalsIgnoreCase("..")) {
       c = UP_CMD;
     } else {
       url = (String) urlList.elementAt(list.getSelectedIndex());
       processorThread = new Thread(this);
       processorThread.start();
       return;
     }
   }
   if (c == UP_CMD) {
     url = url.substring(0, url.substring(0, url.length() - 1).lastIndexOf('/') + 1);
     // #debug debug
     logger.debug("Moving up directory to :" + url);
     if (url.length() < 9) { // file:///
       url = "file:///";
     }
     processorThread = new Thread(this);
     processorThread.start();
     return;
   }
 }
Exemplo n.º 5
0
  public OutputStream openSession(String url, String name) {
    OutputStream oS = null;
    // #if polish.api.fileconnection
    try {
      url += name + ".gpx";
      // #debug info
      logger.info("Opening file " + url);
      session = Connector.open(url);
      FileConnection fileCon = (FileConnection) session;
      if (fileCon == null) throw new IOException("Couldn't open url " + url);
      if (!fileCon.exists()) {
        fileCon.create();
      } else {
        fileCon.truncate(0);
      }

      oS = fileCon.openOutputStream();
    } catch (IOException e) {
      logger.error(
          Locale.get(
                  "fileexportsession.CouldNotObtainConnection") /*Could not obtain connection with */
              + url
              + " ("
              + e.getMessage()
              + ")");
      e.printStackTrace();
    }
    // #endif
    return oS;
  }
Exemplo n.º 6
0
  public void commandAction(Command cmd, Displayable d) {
    if (d == Dialogs.mErrorD) {
      mMidlet.setTopViewCurrent();
    } else if (cmd == DELETE) {
      ShortcutItem item = (ShortcutItem) mShortcutList.getFocusedItem();
      item.shortcut.action = 0;
      createShortcutsTab();
    } else if (cmd == OK || cmd == CANCEL) {
      if (cmd == OK) {
        // save the current shortcut
        int button = mSelectedShortcut.shortcut.button;
        // #debug
        System.out.println("saving shortcut " + button);
        Shortcut s = mSettings.getShortcut(button);
        s.copy(mSelectedShortcut.shortcut);
      }

      createShortcutsTab();
    } else {
      try {
        mSettings.flush();
        mMidlet.setTopViewCurrent();
      } catch (IOException e) {
        Dialogs.popupErrorDialog(mMidlet, this, Locale.get("error.FailedToSaveSettings"));
      }
    }
  }
Exemplo n.º 7
0
 private void updateSolution(int state) {
   logger.info("Update Solution");
   currentState = state;
   if ((System.currentTimeMillis() - lastFixTimestamp) > 3000) {
     hasFix = false;
   }
   // locationUpdated(locationManager, locationManager.getLastKnownLocation(provider), true);
   if (state == LocationProvider.OUT_OF_SERVICE) {
     if (receiverList != null) {
       receiverList.receiveStatus(LocationMsgReceiver.STATUS_OFF, 0);
       receiverList.receiveMessage(
           Locale.get("androidlocationinput.ProviderStopped") /*provider stopped*/);
     }
     // some devices, e.g. Samsung Galaxy Note will claim LocationProvider.AVAILABLE
     // even when there's no fix, so use a timestamp to detect
   } else if (state == LocationProvider.TEMPORARILY_UNAVAILABLE || !hasFix) {
     if (receiverList != null) {
       receiverList.receiveStatus(LocationMsgReceiver.STATUS_NOFIX, numSatellites);
     }
   } else if (state == LocationProvider.AVAILABLE || hasFix) {
     if (receiverList != null) {
       receiverList.receiveStatus(LocationMsgReceiver.STATUS_ON, numSatellites);
     }
   }
 }
Exemplo n.º 8
0
 public void onNmeaReceived(long timestamp, String nmeaString) {
   // #debug info
   logger.info("Using extra NMEA info in Android location provider: " + nmeaString);
   // FIXME combine to one, duplicated in Jsr179Input and AndroidLocationInput
   if (nmeaString != null) {
     if (rawDataLogger != null) {
       try {
         rawDataLogger.write(nmeaString.getBytes());
         rawDataLogger.flush();
       } catch (IOException ioe) {
         logger.exception(
             Locale.get("jsr179input.CouldNotWriteGPSLog") /*Could not write raw GPS log*/, ioe);
       }
     }
     Vector messages = StringTokenizer.getVector(nmeaString, "$");
     if (messages != null) {
       for (int i = 0; i < messages.size(); i++) {
         String nmeaMessage = (String) messages.elementAt(i);
         if (nmeaMessage == null) {
           continue;
         }
         if (nmeaMessage.startsWith("$")) {
           // Cut off $GP from the start
           nmeaMessage = nmeaMessage.substring(3);
         } else if (nmeaMessage.startsWith("GP")) {
           // Cut off GP from the start
           nmeaMessage = nmeaMessage.substring(2);
         }
         int delimiterIdx = nmeaMessage.indexOf("*");
         if (delimiterIdx > 0) {
           // remove the checksum
           nmeaMessage = nmeaMessage.substring(0, delimiterIdx);
         }
         delimiterIdx = nmeaMessage.indexOf(" ");
         if (delimiterIdx > 0) {
           // remove trailing whitespace because some mobiles like HTC Touch Diamond 2 with JavaFX
           // receive NMEA sentences terminated by a space instead of a star followed by the
           // checksum
           nmeaMessage = nmeaMessage.substring(0, delimiterIdx);
         }
         // #debug info
         logger.info("Decoding: " + nmeaMessage);
         if ((nmeaMessage != null) && (nmeaMessage.length() > 5)) {
           smsg.decodeMessage(nmeaMessage, false, false);
           // get *DOP from the message
           pos.pdop = smsg.getPosition().pdop;
           pos.hdop = smsg.getPosition().hdop;
           pos.vdop = smsg.getPosition().vdop;
           // disable for now if we have a fix; could be this is incorrect for devices with GPS &
           // GLONASS, and we get this from getGpsStatus()
           if (!hasFix) {
             numSatellites = smsg.getMAllSatellites();
             updateSolution(LocationProvider.TEMPORARILY_UNAVAILABLE);
           }
         }
       }
     }
   }
 }
Exemplo n.º 9
0
  public GuiGpxOsmUpload() {
    super(Locale.get("guigpxosmupload.GPXToOSM") /*GPX upload to OSM*/);

    descriptionTF =
        new TextField(
            Locale.get("guigpxosmupload.Description") /*Description:*/, "", 255, TextField.ANY);
    tagsTF = new TextField(Locale.get("guigpxosmupload.Tags") /*Tags:*/, "", 255, TextField.ANY);
    String[] items = new String[1];
    items[0] = Locale.get("guigpxosmupload.Public") /*Public*/;
    publicCG = new ChoiceGroup("", Choice.MULTIPLE, items, null);

    this.append(descriptionTF);
    this.append(tagsTF);
    this.append(publicCG);
    this.addCommand(OK_CMD);
    this.addCommand(BACK_CMD);
    this.setCommandListener(this);
  }
Exemplo n.º 10
0
 public void closeSession() {
   // #if polish.api.fileconnection
   try {
     session.close();
   } catch (IOException e) {
     logger.error(
         Locale.get(
             "fileexportsession.FailedToCloseConnection") /*Failed to close connection after storing to file*/);
     e.printStackTrace();
   }
   // #endif
 }
Exemplo n.º 11
0
 public void disableRawLogging() {
   if (rawDataLogger != null) {
     try {
       rawDataLogger.close();
     } catch (IOException e) {
       logger.exception(
           Locale.get(
               "androidlocationinput.CouldntCloseRawGpsLogger") /*Couldnt close raw gps logger*/,
           e);
     }
     rawDataLogger = null;
   }
 }
Exemplo n.º 12
0
  public void commandAction(Command c, Displayable d) {
    if (c == BACK_CMD) {
      if (d == this) {
        parent.show();
      } else {
        show();
      }
    }
    if (c == ADD_CMD) {
      this.addTag = true;
      TextField tf =
          new TextField(Locale.get("guiosmentitydisplay.key") /*key*/, "", 100, TextField.ANY);
      tf.addCommand(OK_CMD);
      tf.setItemCommandListener(this);
      this.append(tf);
      Display.getDisplay(GpsMid.getInstance()).setCurrentItem(tf);
      tf = new TextField(Locale.get("guiosmentitydisplay.value") /*value*/, "", 100, TextField.ANY);
      tf.addCommand(OK_CMD);
      tf.setItemCommandListener(this);
      this.append(tf);
    }

    if (c == CREATE_CHANGE_CMD) {
      changesetGui = new GuiOsmChangeset(this, this);
      changesetGui.show();
    }

    if (c == CLOSE_CHANGE_CMD) {
      if (changesetGui == null) {
        logger.error(
            Locale.get(
                "guiosmentitydisplay.NoChangesetIsCurrentlyOpen") /*No changeset is currently open*/);
      } else {
        changesetGui.closeChangeset();
        changesetGui = null;
      }
    }
  }
Exemplo n.º 13
0
  private void createDisplayTab() {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    // #style SpanningLabel
    StringItem s = new StringItem(null, Locale.get("settings.ShowTickersFor"));
    f.append(DISPLAY_TAB, s);

    // #style ChoiceGroupIndented
    mTickerCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mTickerCG.append(Locale.get("settings.Conversations"), null);
    // #style ChoiceItem
    mTickerCG.append(Locale.get("settings.Messages"), null);
    // #style ChoiceItem
    mTickerCG.append(Locale.get("settings.Appointments"), null);
    f.append(DISPLAY_TAB, mTickerCG);

    // ========== Ticker Speed

    // #style SpanningLabel
    s = new StringItem(null, Locale.get("settings.TickerSpeed"));
    f.append(DISPLAY_TAB, s);

    // #style ChoiceGroupIndented
    mTickerSpeedCG = new ChoiceGroup(null, ChoiceGroup.EXCLUSIVE);
    // #style ChoiceItem
    mTickerSpeedCG.append(Locale.get("settings.Slow"), null);
    // #style ChoiceItem
    mTickerSpeedCG.append(Locale.get("settings.Medium"), null);
    // #style ChoiceItem
    mTickerSpeedCG.append(Locale.get("settings.Fast"), null);
    f.append(DISPLAY_TAB, mTickerSpeedCG);

    // TODO remove when Polish fixes bug that causes layout/highlighting weirdness if the below is
    // removed
    // #style Spacer
    s = new StringItem(null, "");
    f.append(DISPLAY_TAB, s);
  }
Exemplo n.º 14
0
  private void createGeneralTab() {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    // #style ChoiceGroup
    mKeepSignedInCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mKeepSignedInCG.append(Locale.get("login.KeepSignedIn"), null);
    f.append(GENERAL_TAB, mKeepSignedInCG);

    // #style ChoiceGroup
    mCacheContactsCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mCacheContactsCG.append(Locale.get("settings.CacheContacts"), null);
    /* TODO Add this in later
    	f.append(GENERAL_TAB, mCacheContactsCG);
    */

    // ========== Preload Contacts

    // #style ChoiceGroup
    mPreloadContactsCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mPreloadContactsCG.append(Locale.get("settings.PreloadContacts"), null);
    f.append(GENERAL_TAB, mPreloadContactsCG);

    // ========== Delete w/o confirmation

    boolean delWOC = mSettings.getDelWOConf();
    // #style ChoiceGroupOffset
    mDelWOConfCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mDelWOConfCG.append(Locale.get("settings.DelWOConf"), null);
    mDelWOConfCG.setSelectedIndex(0, delWOC);
    f.append(GENERAL_TAB, mDelWOConfCG);

    // #style ChoiceGroupIndented
    mDelWOConfSubCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mDWOCConvCI = new ChoiceItem(Locale.get("settings.Conversations"), null, Choice.MULTIPLE);
    // #style ChoiceItem
    mDWOCMsgCI = new ChoiceItem(Locale.get("settings.Messages"), null, Choice.MULTIPLE);
    f.append(GENERAL_TAB, mDelWOConfSubCG);

    // TODO remove when Polish fixes bug that causes layout/highlighting weirdness if the below is
    // removed
    // #style Spacer
    StringItem s = new StringItem(null, "");
    f.append(GENERAL_TAB, s);
  }
Exemplo n.º 15
0
  private void createShortcutsTab() {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    // #style ChoiceGroup
    mShortcutList = new de.enough.polish.ui.ListItem(null);
    Shortcut[] shortcuts = mSettings.getShortcuts();
    Shortcut firstUnused = null;
    for (int i = 0; i < shortcuts.length; i++) {
      if (!shortcuts[i].isConfigured()) {
        firstUnused = shortcuts[i];
        break;
      }
    }

    ChoiceItem ci = null;
    if (firstUnused != null) {
      // #style ChoiceItem
      ci = new ShortcutItem(Locale.get("settings.NewShortcut"), null, List.IMPLICIT, firstUnused);
      mShortcutList.append(ci);
    }
    for (int i = 0; i < shortcuts.length; i++) {
      if (!shortcuts[i].isConfigured()) continue;
      // #style ChoiceItem
      ci = new ShortcutItem(shortcuts[i].toString(), null, List.IMPLICIT, shortcuts[i]);
      mShortcutList.append(ci);
    }

    f.deleteAll(SHORTCUTS_TAB);
    f.removeCommand(OK);
    f.removeCommand(CANCEL);
    f.addCommand(SAVE);
    f.addCommand(DELETE);
    f.append(SHORTCUTS_TAB, mShortcutList);
    mShortcutList.setItemCommandListener(this);
    mShortcutList.setDefaultCommand(List.SELECT_COMMAND);
  }
Exemplo n.º 16
0
 private void getRoots() {
   // Work around the problem that list.deleteAll might cause problems on a
   // SE K750
   list = createEmptyList();
   urlList.removeAllElements();
   // #if polish.api.pdaapi
   // logger.debug("getRoot");
   Enumeration drives = FileSystemRegistry.listRoots();
   // logger.debug("The valid roots found are: ");
   while (drives.hasMoreElements()) {
     String root = (String) drives.nextElement();
     list.append(root, null);
     urlList.addElement(url + root);
   }
   // #else
   list.append(Locale.get("fsdiscover.APINotSupByDevice") /*API not supported by device*/, null);
   // #endif
   // Display the new list. We just assume, that the old list was still
   // displaying
   // As an attempt to check if that was the case didn't seem to work
   // reliably on
   // some mobiles
   show();
 }
Exemplo n.º 17
0
  private void createShortcutEditTab(ShortcutItem si) {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    mSelectedShortcut = new ShortcutItem(si);
    int selectedIndex;
    switch (mSelectedShortcut.shortcut.action) {
      case Shortcut.ACTION_MOVE_TO_FOLDER:
      default:
        selectedIndex = SHORTCUT_FOLDER;
        break;
      case Shortcut.ACTION_TAG:
        selectedIndex = SHORTCUT_TAG;
        break;
      case Shortcut.ACTION_RUN_SAVED_SEARCH:
        selectedIndex = SHORTCUT_SEARCH;
        break;
    }

    mShortcutEditScreen = new de.enough.polish.ui.ListItem(Locale.get("settings.EditShortcut"));

    // #style SpanningLabel
    Item item = new StringItem(null, Locale.get("settings.Button"));
    mShortcutEditScreen.append(item);

    // #style ChoiceGroupPopup
    mShortcutButtonCG = new ChoiceGroup(null, Choice.POPUP);
    for (int i = 0; i < 10; i++) {
      // #style ChoiceItemPopup
      mShortcutButtonCG.append("# " + i, null);
    }

    mShortcutButtonCG.setSelectedIndex(mSelectedShortcut.shortcut.button, true);
    mShortcutEditScreen.append(mShortcutButtonCG);

    // #style SpanningLabel
    item = new StringItem(null, Locale.get("settings.Action"));
    mShortcutEditScreen.append(item);

    // #style ChoiceGroupIndented
    mShortcutActionCG = new ChoiceGroup(null, ChoiceGroup.EXCLUSIVE);
    // #style ChoiceItem
    mShortcutActionCG.append(
        mSelectedShortcut.shortcut.toString(false, Shortcut.ACTION_MOVE_TO_FOLDER), null);
    // #style ChoiceItem
    mShortcutActionCG.append(mSelectedShortcut.shortcut.toString(false, Shortcut.ACTION_TAG), null);
    // #style ChoiceItem
    mShortcutActionCG.append(
        mSelectedShortcut.shortcut.toString(false, Shortcut.ACTION_RUN_SAVED_SEARCH), null);
    mShortcutEditScreen.append(mShortcutActionCG);

    mShortcutActionCG.setSelectedIndex(selectedIndex, true);
    f.removeCommand(SAVE);
    f.removeCommand(DELETE);
    f.addCommand(OK);
    f.addCommand(CANCEL);
    f.deleteAll(SHORTCUTS_TAB);
    f.append(SHORTCUTS_TAB, mShortcutEditScreen);
  }
Exemplo n.º 18
0
  public GuiSetupGui(ShareNavDisplayable parent, boolean initialSetup) {
    super(Locale.get("guisetupgui.GUIOptions") /*GUI Options*/);
    this.parent = parent;
    this.initialSetup = initialSetup;
    try {
      long mem = Configuration.getPhoneAllTimeMaxMemory();
      if (mem == 0) {
        mem = Runtime.getRuntime().totalMemory();
      }
      mem = mem / 1024;
      memField =
          new TextField(
              Locale.get("guisetupgui.DefineMaxMem") /*Define maxMem (kbyte)*/,
              Long.toString(mem),
              8,
              TextField.DECIMAL);
      append(memField);
      String[] imenu = new String[7];
      imenu[0] = Locale.get("guisetupgui.UseIconMenu") /*Use icon menu*/;
      imenu[1] = Locale.get("guisetupgui.UseSetupIconMenu") /*Use icon menu for settings*/;
      imenu[2] = Locale.get("guisetupgui.FullscreenIconMenu") /*Fullscreen icon menu*/;
      imenu[3] = Locale.get("guisetupgui.SplitscreenIconMenu") /*Split screen icon menu*/;
      imenu[4] = Locale.get("guisetupgui.LargeTabButtons") /*Large tab buttons*/;
      imenu[5] = Locale.get("guisetupgui.IconsMappedOnKeys") /*Icons mapped on keys*/;
      // imenu[5] = Locale.get("guisetupgui.OptimiseForRouting")/*Optimise for routing*/;
      imenu[6] =
          Locale.get("guisetupgui.FavoritesInRouteIconMenu") /*Favorites in route icon menu*/;
      imenuOpts =
          new ChoiceGroup(
              Locale.get("guisetupgui.IconMenu") /*Icon Menu:*/, Choice.MULTIPLE, imenu, null);
      imenuOpts.setSelectedIndex(
          0, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS));
      imenuOpts.setSelectedIndex(
          1, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_SETUP));
      imenuOpts.setSelectedIndex(
          2, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_FULLSCREEN));
      imenuOpts.setSelectedIndex(
          3, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_SPLITSCREEN));
      imenuOpts.setSelectedIndex(
          4, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_BIG_TAB_BUTTONS));
      imenuOpts.setSelectedIndex(
          5, Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_MAPPED_ICONS));
      // imenuOpts.setSelectedIndex(5,
      //		Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED));
      imenuOpts.setSelectedIndex(
          6, Configuration.getCfgBitSavedState(Configuration.CFGBIT_FAVORITES_IN_ROUTE_ICON_MENU));
      append(imenuOpts);

      if (Configuration.getHasPointerEvents()) {
        String[] touch = new String[4];
        int i = 0;
        touch[i++] = Locale.get("guisetupgui.longMapTap");
        touch[i++] = Locale.get("guisetupgui.doubleMapTap");
        touch[i++] = Locale.get("guisetupgui.singleMapTap");
        touch[i++] = Locale.get("guisetupgui.clickableMarkers");
        mapTapFeatures =
            new ChoiceGroup(
                Locale.get("guisetupgui.MapTapFeatures") /*Map Touch Features*/,
                Choice.MULTIPLE,
                touch,
                null);
        i = 0;
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG));
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE));
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE));
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_CLICKABLE_MAPOBJECTS));
        append(mapTapFeatures);
      }

      // search options
      int iMax = 3;
      if (Configuration.getHasPointerEvents()) {
        iMax++;
      }
      // #if polish.android
      iMax++;
      // #endif
      String[] search = null;
      search = new String[iMax];
      int searchnum = 0;
      search[searchnum++] = Locale.get("guisetupgui.scroll") /*Scroll result under cursor*/;
      search[searchnum++] = Locale.get("guisetupgui.scrollall") /*Scroll all results*/;
      if (Configuration.getHasPointerEvents()) {
        search[searchnum++] = Locale.get("guisetupgui.numberkeypad") /*Enable virtual keypad*/;
      }
      search[searchnum++] =
          Locale.get(
              "guisetupgui.SuppressSearchWarning") /*Suppress warning about exceeding max results*/;
      // #if polish.android
      search[searchnum++] =
          Locale.get("guisetupgui.ShowNativeKeyboard") /*Show native keyboard in search*/;
      // #endif
      searchSettings =
          new ChoiceGroup(
              Locale.get("guisetupgui.searchopts") /*Search options:*/,
              Choice.MULTIPLE,
              search,
              null);
      /* only display search settings available on the device */
      // maximum search option entries
      searchnum = 0;
      searchSettings.setSelectedIndex(
          searchnum++, Configuration.getCfgBitSavedState(Configuration.CFGBIT_TICKER_ISEARCH));
      searchSettings.setSelectedIndex(
          searchnum++, Configuration.getCfgBitSavedState(Configuration.CFGBIT_TICKER_ISEARCH_ALL));
      if (Configuration.getHasPointerEvents()) {
        searchSettings.setSelectedIndex(
            searchnum++,
            Configuration.getCfgBitSavedState(Configuration.CFGBIT_SEARCH_TOUCH_NUMBERKEYPAD));
      }
      searchSettings.setSelectedIndex(
          searchnum++,
          Configuration.getCfgBitSavedState(Configuration.CFGBIT_SUPPRESS_SEARCH_WARNING));
      // #if polish.android
      searchSettings.setSelectedIndex(
          searchnum++,
          Configuration.getCfgBitSavedState(Configuration.CFGBIT_SEARCH_SHOW_NATIVE_KEYBOARD));
      // #endif
      append(searchSettings);
      String[] searchLayout = new String[2];
      searchLayout[0] = Locale.get("guidiscover.SearchWholeNames") /*Search for whole names*/;
      searchLayout[1] = Locale.get("guidiscover.SearchWords") /*Search for words*/;
      searchLayoutGroup =
          new ChoiceGroup(
              Locale.get("guidiscover.SearchStyle") /*Search style*/,
              Choice.EXCLUSIVE,
              searchLayout,
              null);
      searchLayoutGroup.setSelectedIndex(
          Configuration.getCfgBitSavedState(Configuration.CFGBIT_WORD_ISEARCH) ? 1 : 0, true);
      append(searchLayoutGroup);

      int searchMax = Configuration.getSearchMax();
      searchField =
          new TextField(
              Locale.get("guisetupgui.DefineMaxSearch") /*Max # of search results*/,
              Integer.toString(searchMax),
              8,
              TextField.DECIMAL);
      append(searchField);

      float dist = Configuration.getPoiSearchDistance();
      poiSearchDistance =
          new TextField(
              Locale.get("guisetupgui.PoiDistance") /*POI Distance: */,
              Float.toString(dist),
              8,
              TextField.ANY);
      append(poiSearchDistance);

      String[] otherSettings = new String[1];
      otherSettings[0] =
          Locale.get("guisetupgui.ExitWithBackButton") /* Back button exits application*/;
      otherGroup =
          new ChoiceGroup(
              Locale.get("guisetupgui.otherOptions") /* Other options */,
              Choice.MULTIPLE,
              otherSettings,
              null);
      otherGroup.setSelectedIndex(
          0,
          Configuration.getCfgBitSavedState(
              Configuration.CFGBIT_EXIT_APPLICATION_WITH_BACK_BUTTON));
      append(otherGroup);

      addCommand(CMD_SAVE);
      addCommand(CMD_CANCEL);

      // Set up this Displayable to listen to command events
      setCommandListener(this);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 19
0
public class GuiSetupGui extends Form implements CommandListener {
  private ChoiceGroup imenuOpts;
  private ChoiceGroup mapTapFeatures;
  private ChoiceGroup searchSettings;
  private ChoiceGroup searchLayoutGroup;
  private ChoiceGroup otherGroup;

  // commands
  private static final Command CMD_SAVE =
      new Command(Locale.get("generic.Save") /*Save*/, ShareNavMenu.OK, 2);
  private static final Command CMD_CANCEL =
      new Command(Locale.get("generic.Cancel") /*Cancel*/, ShareNavMenu.BACK, 3);

  // other
  private final ShareNavDisplayable parent;
  private final boolean initialSetup;

  private TextField memField;
  private TextField searchField;
  private TextField poiSearchDistance;

  public GuiSetupGui(ShareNavDisplayable parent, boolean initialSetup) {
    super(Locale.get("guisetupgui.GUIOptions") /*GUI Options*/);
    this.parent = parent;
    this.initialSetup = initialSetup;
    try {
      long mem = Configuration.getPhoneAllTimeMaxMemory();
      if (mem == 0) {
        mem = Runtime.getRuntime().totalMemory();
      }
      mem = mem / 1024;
      memField =
          new TextField(
              Locale.get("guisetupgui.DefineMaxMem") /*Define maxMem (kbyte)*/,
              Long.toString(mem),
              8,
              TextField.DECIMAL);
      append(memField);
      String[] imenu = new String[7];
      imenu[0] = Locale.get("guisetupgui.UseIconMenu") /*Use icon menu*/;
      imenu[1] = Locale.get("guisetupgui.UseSetupIconMenu") /*Use icon menu for settings*/;
      imenu[2] = Locale.get("guisetupgui.FullscreenIconMenu") /*Fullscreen icon menu*/;
      imenu[3] = Locale.get("guisetupgui.SplitscreenIconMenu") /*Split screen icon menu*/;
      imenu[4] = Locale.get("guisetupgui.LargeTabButtons") /*Large tab buttons*/;
      imenu[5] = Locale.get("guisetupgui.IconsMappedOnKeys") /*Icons mapped on keys*/;
      // imenu[5] = Locale.get("guisetupgui.OptimiseForRouting")/*Optimise for routing*/;
      imenu[6] =
          Locale.get("guisetupgui.FavoritesInRouteIconMenu") /*Favorites in route icon menu*/;
      imenuOpts =
          new ChoiceGroup(
              Locale.get("guisetupgui.IconMenu") /*Icon Menu:*/, Choice.MULTIPLE, imenu, null);
      imenuOpts.setSelectedIndex(
          0, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS));
      imenuOpts.setSelectedIndex(
          1, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_SETUP));
      imenuOpts.setSelectedIndex(
          2, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_FULLSCREEN));
      imenuOpts.setSelectedIndex(
          3, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_SPLITSCREEN));
      imenuOpts.setSelectedIndex(
          4, Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_BIG_TAB_BUTTONS));
      imenuOpts.setSelectedIndex(
          5, Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_MAPPED_ICONS));
      // imenuOpts.setSelectedIndex(5,
      //		Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED));
      imenuOpts.setSelectedIndex(
          6, Configuration.getCfgBitSavedState(Configuration.CFGBIT_FAVORITES_IN_ROUTE_ICON_MENU));
      append(imenuOpts);

      if (Configuration.getHasPointerEvents()) {
        String[] touch = new String[4];
        int i = 0;
        touch[i++] = Locale.get("guisetupgui.longMapTap");
        touch[i++] = Locale.get("guisetupgui.doubleMapTap");
        touch[i++] = Locale.get("guisetupgui.singleMapTap");
        touch[i++] = Locale.get("guisetupgui.clickableMarkers");
        mapTapFeatures =
            new ChoiceGroup(
                Locale.get("guisetupgui.MapTapFeatures") /*Map Touch Features*/,
                Choice.MULTIPLE,
                touch,
                null);
        i = 0;
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG));
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE));
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE));
        mapTapFeatures.setSelectedIndex(
            i++, Configuration.getCfgBitState(Configuration.CFGBIT_CLICKABLE_MAPOBJECTS));
        append(mapTapFeatures);
      }

      // search options
      int iMax = 3;
      if (Configuration.getHasPointerEvents()) {
        iMax++;
      }
      // #if polish.android
      iMax++;
      // #endif
      String[] search = null;
      search = new String[iMax];
      int searchnum = 0;
      search[searchnum++] = Locale.get("guisetupgui.scroll") /*Scroll result under cursor*/;
      search[searchnum++] = Locale.get("guisetupgui.scrollall") /*Scroll all results*/;
      if (Configuration.getHasPointerEvents()) {
        search[searchnum++] = Locale.get("guisetupgui.numberkeypad") /*Enable virtual keypad*/;
      }
      search[searchnum++] =
          Locale.get(
              "guisetupgui.SuppressSearchWarning") /*Suppress warning about exceeding max results*/;
      // #if polish.android
      search[searchnum++] =
          Locale.get("guisetupgui.ShowNativeKeyboard") /*Show native keyboard in search*/;
      // #endif
      searchSettings =
          new ChoiceGroup(
              Locale.get("guisetupgui.searchopts") /*Search options:*/,
              Choice.MULTIPLE,
              search,
              null);
      /* only display search settings available on the device */
      // maximum search option entries
      searchnum = 0;
      searchSettings.setSelectedIndex(
          searchnum++, Configuration.getCfgBitSavedState(Configuration.CFGBIT_TICKER_ISEARCH));
      searchSettings.setSelectedIndex(
          searchnum++, Configuration.getCfgBitSavedState(Configuration.CFGBIT_TICKER_ISEARCH_ALL));
      if (Configuration.getHasPointerEvents()) {
        searchSettings.setSelectedIndex(
            searchnum++,
            Configuration.getCfgBitSavedState(Configuration.CFGBIT_SEARCH_TOUCH_NUMBERKEYPAD));
      }
      searchSettings.setSelectedIndex(
          searchnum++,
          Configuration.getCfgBitSavedState(Configuration.CFGBIT_SUPPRESS_SEARCH_WARNING));
      // #if polish.android
      searchSettings.setSelectedIndex(
          searchnum++,
          Configuration.getCfgBitSavedState(Configuration.CFGBIT_SEARCH_SHOW_NATIVE_KEYBOARD));
      // #endif
      append(searchSettings);
      String[] searchLayout = new String[2];
      searchLayout[0] = Locale.get("guidiscover.SearchWholeNames") /*Search for whole names*/;
      searchLayout[1] = Locale.get("guidiscover.SearchWords") /*Search for words*/;
      searchLayoutGroup =
          new ChoiceGroup(
              Locale.get("guidiscover.SearchStyle") /*Search style*/,
              Choice.EXCLUSIVE,
              searchLayout,
              null);
      searchLayoutGroup.setSelectedIndex(
          Configuration.getCfgBitSavedState(Configuration.CFGBIT_WORD_ISEARCH) ? 1 : 0, true);
      append(searchLayoutGroup);

      int searchMax = Configuration.getSearchMax();
      searchField =
          new TextField(
              Locale.get("guisetupgui.DefineMaxSearch") /*Max # of search results*/,
              Integer.toString(searchMax),
              8,
              TextField.DECIMAL);
      append(searchField);

      float dist = Configuration.getPoiSearchDistance();
      poiSearchDistance =
          new TextField(
              Locale.get("guisetupgui.PoiDistance") /*POI Distance: */,
              Float.toString(dist),
              8,
              TextField.ANY);
      append(poiSearchDistance);

      String[] otherSettings = new String[1];
      otherSettings[0] =
          Locale.get("guisetupgui.ExitWithBackButton") /* Back button exits application*/;
      otherGroup =
          new ChoiceGroup(
              Locale.get("guisetupgui.otherOptions") /* Other options */,
              Choice.MULTIPLE,
              otherSettings,
              null);
      otherGroup.setSelectedIndex(
          0,
          Configuration.getCfgBitSavedState(
              Configuration.CFGBIT_EXIT_APPLICATION_WITH_BACK_BUTTON));
      append(otherGroup);

      addCommand(CMD_SAVE);
      addCommand(CMD_CANCEL);

      // Set up this Displayable to listen to command events
      setCommandListener(this);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void commandAction(Command c, Displayable d) {

    if (c == CMD_CANCEL) {
      parent.show();
      return;
    }

    if (c == CMD_SAVE) {
      try {
        long mem = Long.parseLong(memField.getString());
        Configuration.setPhoneAllTimeMaxMemory(mem * 1024);
      } catch (NumberFormatException e) {
        // nothing to do (ignore content)
      }
      try {
        int searchMax = Integer.parseInt(searchField.getString());
        Configuration.setSearchMax(searchMax);
      } catch (NumberFormatException e) {
        // nothing to do (ignore content)
      }
      try {
        float dist = Float.parseFloat(poiSearchDistance.getString());
        Configuration.setPoiSearchDistance(dist);
      } catch (NumberFormatException e) {
        // nothing to do (ignore content)
      }

      Trace trace = Trace.getInstance();
      if (imenuOpts.isSelected(0)
          != Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS)) {
        trace.removeAllCommands();
        Configuration.setCfgBitSavedState(Configuration.CFGBIT_ICONMENUS, imenuOpts.isSelected(0));
        trace.addAllCommands();
      }
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_ICONMENUS_SETUP, imenuOpts.isSelected(1));
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_ICONMENUS_FULLSCREEN, imenuOpts.isSelected(2));
      if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_SPLITSCREEN)
          && !imenuOpts.isSelected(3)) {
        trace.stopShowingSplitScreen();
      }
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_ICONMENUS_SPLITSCREEN, imenuOpts.isSelected(3));
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_ICONMENUS_BIG_TAB_BUTTONS, imenuOpts.isSelected(4));
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_ICONMENUS_MAPPED_ICONS, imenuOpts.isSelected(5));
      // Configuration.setCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED,
      //		imenuOpts.isSelected(5));
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_FAVORITES_IN_ROUTE_ICON_MENU, imenuOpts.isSelected(6));
      // When the GUI is to be optimized for routing and we have a default
      // backlight method, turn the backlight on.
      // boolean optimizedForRouting = imenuOpts.isSelected(5);
      boolean optimizedForRouting = imenuOpts.isSelected(5);
      if (initialSetup && optimizedForRouting) {
        if (Configuration.getDefaultDeviceBacklightMethodCfgBit() != 0) {
          Configuration.setCfgBitSavedState(Configuration.CFGBIT_BACKLIGHT_ON, true);
          ShareNav.getInstance().restartBackLightTimer();
        }
      }

      Trace.uncacheIconMenu();
      GuiDiscover.uncacheIconMenu();

      boolean searchLayout = (searchLayoutGroup.getSelectedIndex() == 1);

      if (searchLayout != Configuration.getCfgBitState(Configuration.CFGBIT_WORD_ISEARCH)) {
        Configuration.setCfgBitSavedState(Configuration.CFGBIT_WORD_ISEARCH, searchLayout);
      }
      int i = 0;
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_TICKER_ISEARCH, searchSettings.isSelected(i++));
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_TICKER_ISEARCH_ALL, searchSettings.isSelected(i++));
      if (Configuration.getHasPointerEvents()) {
        Configuration.setCfgBitSavedState(
            Configuration.CFGBIT_SEARCH_TOUCH_NUMBERKEYPAD, searchSettings.isSelected(i++));
      }

      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_SUPPRESS_SEARCH_WARNING, searchSettings.isSelected(i++));
      // #if polish.android
      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_SEARCH_SHOW_NATIVE_KEYBOARD, searchSettings.isSelected(i++));
      // #endif

      i = 0;
      if (Configuration.getHasPointerEvents()) {
        Configuration.setCfgBitSavedState(
            Configuration.CFGBIT_MAPTAP_LONG, mapTapFeatures.isSelected(i++));
        Configuration.setCfgBitSavedState(
            Configuration.CFGBIT_MAPTAP_DOUBLE, mapTapFeatures.isSelected(i++));
        Configuration.setCfgBitSavedState(
            Configuration.CFGBIT_MAPTAP_SINGLE, mapTapFeatures.isSelected(i++));
        Configuration.setCfgBitSavedState(
            Configuration.CFGBIT_CLICKABLE_MAPOBJECTS, mapTapFeatures.isSelected(i++));
      }

      Configuration.setCfgBitSavedState(
          Configuration.CFGBIT_EXIT_APPLICATION_WITH_BACK_BUTTON, otherGroup.isSelected(0));

      parent.show();
      return;
    }
  }

  public void show() {
    ShareNav.getInstance().show(this);
  }
}
/**
 * This class implements the layout of the 'sign up' form of the WebAccounts pages
 *
 * <p>Used for editing of all SN types.
 *
 * @author Anders Bo Pedersen, [email protected]
 */
public class EditWebAccountForm extends BaseFramedForm {
  public static final Command cmdLogin =
      new Command(Locale.get("nowplus.client.java.webaccounts.command.login"), Command.SCREEN, 0);

  protected TitleBarItem titleitem;

  protected ExternalNetwork network;

  protected Identity iden;

  protected TextField usernameTextField, passwordTextField;

  public EditWebAccountForm(Model model, Controller controller, ExternalNetwork nw, Identity iden) {
    this(model, controller, nw, iden, null);
  }

  public EditWebAccountForm(
      Model model, Controller controller, ExternalNetwork nw, Identity iden, Style style) {
    super(model, controller, null, style);

    this.network = nw;
    this.iden = iden;

    // #style webaccount_edit_headline
    Container info = new Container(false);
    info.setAppearanceMode(Item.PLAIN);

    // constructs network icon and sets default style to focused/'white'
    IconItem networkIcon =
        UiFactory.createNetworkIcon(
            (null != this.network ? this.network.getNetworkId() : ""), false);
    networkIcon.setStyle(networkIcon.getFocusedStyle());
    networkIcon.setAppearanceMode(Item.PLAIN);

    info.add(networkIcon);
    info.add(
        // #style webaccount_edit_headline_text
        new StringItem(
            null,
            (null != this.network ? this.network.getName() : "")
                + " "
                + Locale.get("nowplus.client.java.webaccounts.edit.info.suffix")));
    this.append(info);

    String credentialsLabel = null;
    if (nw.getCredentialsType() == ExternalNetwork.CREDENTIALS_USERNAME) {
      credentialsLabel = Locale.get("nowplus.client.java.webaccounts.edit.username");
    } else if (nw.getCredentialsType() == ExternalNetwork.CREDENTIALS_USERNAME_OR_EMAIL) {
      credentialsLabel = Locale.get("nowplus.client.java.webaccounts.edit.username_email");
    }

    // add username textfield
    this.usernameTextField =
        UiFactory.createTextField(
            null, null, 128, TextField.ANY | TextField.INITIAL_CAPS_NEVER, this);
    // fix for PBLA-816 Touch device: predictive text while disabling the surepress
    // #if polish.blackberry
    this.usernameTextField.setNoComplexInput(true);
    // #endif

    // #if using.native.textfield:defined
    this.usernameTextField.setTitle(credentialsLabel);
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(this.usernameTextField);
    // #endif
    // #endif

    // check for existing username
    if (null == this.iden) {
      this.usernameTextField.setHelpText(credentialsLabel);

      // #if polish.blackberry
      // #style ui_factory_textfield_helpfont
      usernameTextField.setHelpStyle();
      // #endif
    } else {
      this.usernameTextField.setString(this.iden.getName());

      // username uneditable in 'edit mode'
      //			this.usernameTextField.setAppearanceMode(Item.PLAIN);
    }

    // add password textfield
    this.passwordTextField =
        UiFactory.createTextField(
            null,
            null,
            128,
            TextField.NON_PREDICTIVE | TextField.INITIAL_CAPS_NEVER | TextField.PASSWORD,
            this);
    // #if using.native.textfield:defined
    this.passwordTextField.setTitle(Locale.get("nowplus.client.java.webaccounts.edit.password"));
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(this.passwordTextField);
    // #elif polish.device.textField.requires.initialCapsNeverFix
    UiFactory.fixS40NativeTextField(this.passwordTextField);
    // #endif
    // #endif

    // check for existing password
    this.passwordTextField.setHelpText(Locale.get("nowplus.client.java.webaccounts.edit.password"));

    // #if polish.blackberry
    // #style ui_factory_textfield_helpfont
    this.passwordTextField.setHelpStyle();
    // #endif

    // #if polish.blackberry
    removeCommand(cmdBack);

    // #style ui_factory_button_item
    StringItem loginButton =
        UiFactory.createButtonItem(
            null, cmdLogin.getLabel(), (de.enough.polish.ui.Command) cmdLogin, null, null);

    append(loginButton);

    // #endif

    // adding disclaimer for given network
    if (null != this.network) {
      String[] disclaimer = this.network.getDisclaimer();

      if (disclaimer[0] != null) {
        // #style .webaccount_edit_disclaimer_header
        this.append(disclaimer[0]);
      }

      for (int i = 1; i < disclaimer.length; i++) {
        // #style .webaccount_edit_disclaimer_text
        this.append(disclaimer[i]);
      }
    }

    // #if !polish.blackberry
    this.addCommand(cmdLogin);
    this.addCommand(cmdBack);
    // #endif
  }

  protected Item createBottomItem() {
    return null;
  }

  protected String createCssSelector() {
    return null;
  }

  protected Item[] createStaticItems() {
    if (null == iden)
      return new Item[] {
        this.titleitem =
            new TitleBarItem(Locale.get("nowplus.client.java.webaccounts.add.title"), getModel())
      };
    else
      return new Item[] {
        this.titleitem =
            new TitleBarItem(Locale.get("nowplus.client.java.webaccounts.edit.title"), getModel())
      };
  }

  protected Item createTopItem() {
    return null;
  }

  public byte getContext() {
    return -1;
  }

  public void commandAction(Command c, Displayable d) {
    if (c == cmdLogin) {
      getController().notifyEvent(Event.Context.WEB_ACCOUNTS, Event.WebAccounts.SAVE, null);
    } else super.commandAction(c, d);
  }

  /** @return */
  public ExternalNetwork getNetwork() {
    return this.network;
  }

  /** @return */
  public String getUsername() {
    return this.usernameTextField.getText();
  }

  /** @return */
  public String getPassword() {
    return this.passwordTextField.getString();
  }

  public void showNotify() {
    super.showNotify();

    // #if !polish.blackberry
    // #if not using.native.textfield:defined
    TextUtilities.loadTextFieldCharacterset(
        "la"); // Defaulting to latin characters as we only allow latin characters in input fields
    // #endif
    // #endif
  }

  // #if polish.blackberry
  // overrides
  /**
   * Handles key events.
   *
   * <p>WARNING: When this method should be overwritten, one need to ensure that super.keyPressed(
   * int ) is called!
   *
   * @param keyCode The code of the pressed key
   * @see de.enough.polish.ui.Screen#keyPressed(int)
   */
  public void keyPressed(int keyCode) {
    if (Keypad.key(keyCode) == Keypad.KEY_ESCAPE) commandAction(cmdBack, this);
    else super.keyPressed(keyCode);
  }
  // #endif

}
Exemplo n.º 21
0
 protected void setupScreen() {
   try {
     this.deleteAll();
     addTag = false;
     if (osmentity == null) {
       this.append(
           new StringItem(
               Locale.get("guiosmentitydisplay.NoDataAvailable") /*No Data available*/, "..."));
       return;
     }
     Hashtable tags = osmentity.getTags();
     if (tags == null) return;
     Enumeration keysEn = tags.keys();
     while (keysEn.hasMoreElements()) {
       String key = (String) keysEn.nextElement();
       Item i = new StringItem(key, (String) tags.get(key));
       i.addCommand(EDIT_CMD);
       i.addCommand(REMOVE_CMD);
       i.setItemCommandListener(this);
       // #style formItem
       this.append(i);
     }
     if (osmentity.getVersion() > 0) {
       // #style formItem
       this.append(new StringItem(Locale.get("guiosmentitydisplay.Edited") /*Edited */, null));
       // #style formItem
       this.append(
           new StringItem(
               Locale.get("guiosmentitydisplay.at") /*    at:*/, osmentity.getEditTime()));
       // #style formItem
       this.append(
           new StringItem(
               Locale.get("guiosmentitydisplay.by") /*    by:*/, osmentity.getEditor()));
       // #style formItem
       this.append(
           new StringItem(
               Locale.get("guiosmentitydisplay.ver") /*    ver:*/,
               Integer.toString(osmentity.getVersion())));
     }
     // #if polish.android
     ViewItem createButton =
         new SaveButton(
             Locale.get("guiosmentitydisplay.CreateChangeset") /*Create changeset*/,
             this,
             (Displayable) this,
             CREATE_CHANGE_CMD);
     ViewItem closeButton =
         new SaveButton(
             Locale.get("guiosmentitydisplay.CloseChangeset") /*Close changeset*/,
             this,
             (Displayable) this,
             CLOSE_CHANGE_CMD);
     this.append(createButton);
     this.append(closeButton);
     AndroidDisplay ad = AndroidDisplay.getDisplay(GpsMid.getInstance());
     ad.setOnKeyListener(
         new OnKeyListener() {
           public boolean onKey(View v, int keyCode, KeyEvent event) {
             if (event.getAction() == KeyEvent.ACTION_DOWN) {
               // check if the right key was pressed
               if (keyCode == KeyEvent.KEYCODE_BACK) {
                 backPressed();
                 return true;
               }
             }
             return false;
           }
         });
     // #endif
   } catch (Exception e) {
     logger.exception(
         Locale.get(
             "guiosmentitydisplay.InitialisingEntityTagScreenFailed") /*Initialising entity tag screen failed: */,
         e);
   }
 }
Exemplo n.º 22
0
/** @author Jens Vesti */
public class LoginForm extends BaseForm // implements ItemCommandListener
{
  public static Command cmdSave =
      new Command(Locale.get("nowplus.client.java.loginform.command.save"), Command.SCREEN, 10);
  public static Command cmdCancel =
      new Command(Locale.get("nowplus.client.java.loginform.command.cancel"), Command.CANCEL, 10);
  public static Command cmdExit =
      new Command(Locale.get("nowplus.client.java.command.exit"), Command.EXIT, 10);

  boolean usernameReadonly = false;
  private TextField userName, passWord;
  private ChoiceItem rememberMeItem;
  private Model model;

  /** Title item displaying both screen name and current time */
  protected TitleBarItem titleitem;

  // #if polish.blackberry
  private Command cmdQuit;
  // #endif

  public LoginForm(
      Model model,
      Controller controller,
      final String title,
      boolean firstLogin,
      final Style style) {
    super(model, controller, null, style);
    this.model = model;
    this.titleitem = new TitleBarItem(title, model);

    // #if polish.blackberry.isTouchBuild == true
    this.title = this.titleitem;
    // #else
    // add title item
    this.append(titleitem);
    // #endif

    // #if polish.blackberry
    titleitem.setAppearanceMode(Item.PLAIN);
    // #endif

    initForm(firstLogin);

    // focus on TextField of UserName input
    if (!usernameReadonly) {
      UiAccess.focus(this, userName);
    }
  }

  public LoginForm(Model model, Controller controller, final String title, boolean firstLogin) {
    this(model, controller, title, firstLogin, null);
  }

  // #if polish.blackberry
  public TextField getUserNameTextField() {
    return userName;
  }
  // #endif

  public String getUsername() {
    return userName.getString();
  }

  public String getPassword() {
    return passWord.getString();
  }

  public boolean isRememberMeSet() {
    return rememberMeItem.isSelected;
  }

  private void initForm(boolean firstLogin) {
    // #if !polish.blackberry
    this.addCommand(cmdSave);

    if (firstLogin) this.addCommand(cmdCancel);
    else this.addCommand(cmdExit);
    // #endif

    StringItem headLine;
    // #if polish.blackberry
    // #if polish.blackberry.isTouchBuild == false
    // #style .login_headline
    headLine = new StringItem(null, Locale.get("nowplus.client.java.loginform.headline"));
    this.append(headLine);
    // #endif
    // #else
    // #style .login_headline
    headLine = new StringItem(null, Locale.get("nowplus.client.java.loginform.headline"));
    this.append(headLine);

    // #endif

    // #if polish.blackberry && polish.blackberry.isTouchBuild == false
    headLine.setAppearanceMode(Item.PLAIN);
    // #endif

    String usernameString = model.getUserName();
    String passwordString = "";

    // #if username:defined
    // #message Username is set
    // #= usernameString = "${username}";
    // #endif

    // #if password:defined
    // #message Password is set
    // #= passwordString = "${password}";
    // #endif

    if (usernameString == null) usernameString = "";
    if (passwordString == null) passwordString = "";

    // username textfield

    // #if polish.blackberry
    userName =
        UiFactory.createTextField(
            Locale.get("nowplus.client.java.loginform.username.hint"),
            usernameString,
            255,
            TextField.NON_PREDICTIVE,
            this);
    // fix for PBLA-816 Touch device: predictive text while disabling the surepress
    userName.setNoComplexInput(true);
    // #else
    userName = UiFactory.createTextField(null, usernameString, 255, TextField.NON_PREDICTIVE, this);
    // #endif

    UiAccess.setTextfieldHelp(userName, Locale.get("nowplus.client.java.loginform.username.hint"));
    // #if using.native.textfield:defined
    userName.setTitle(Locale.get("nowplus.client.java.loginform.username.hint"));
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(userName);
    // #endif
    // #endif

    if (userName.getText().length() > 0) {
      // Change username textfield into uneditable field once authenticated once to keep users from
      // switching username
      userName.setConstraints(TextField.NON_PREDICTIVE | TextField.UNEDITABLE);

      usernameReadonly = true;

      // #if not polish.blackberry
      // #style .login_textfield_readonly
      // #= userName.setStyle();
      // #endif
    }

    // password textfield

    // #if polish.blackberry
    passWord =
        UiFactory.createTextField(
            Locale.get("nowplus.client.java.loginform.password.hint"),
            passwordString,
            255,
            TextField.NON_PREDICTIVE | TextField.INITIAL_CAPS_NEVER | TextField.PASSWORD,
            this);
    // #else
    passWord =
        UiFactory.createTextField(
            null, passwordString, 255, TextField.INITIAL_CAPS_NEVER | TextField.PASSWORD, this);
    // #endif

    UiAccess.setTextfieldHelp(passWord, Locale.get("nowplus.client.java.loginform.password.hint"));
    // #if using.native.textfield:defined
    passWord.setTitle(Locale.get("nowplus.client.java.loginform.password.hint"));
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(passWord);
    // #elif polish.device.textField.requires.initialCapsNeverFix:defined
    UiFactory.fixS40NativeTextField(passWord);
    // #endif
    // #endif

    rememberMeItem =
        UiFactory.createChoiceCheckBoxItem(
            Locale.get("nowplus.client.java.loginform.rememberme.label"), Choice.MULTIPLE);
    rememberMeItem.select(model.stayLoggedIn());
    UiFactory.createChoiceGroup(
        null,
        ChoiceGroup.MULTIPLE,
        new ChoiceItem[] {rememberMeItem},
        0,
        rememberMeItem.isSelected,
        null,
        this);

    // #if !polish.blackberry
    if (usernameReadonly) {
      this.focus(passWord);
    }
    // #endif

    // #if polish.blackberry
    // #style ui_factory_button_item
    StringItem loginButton =
        UiFactory.createButtonItem(
            null, cmdSave.getLabel(), (de.enough.polish.ui.Command) cmdSave, null, null);
    append(loginButton);

    if (firstLogin) {
      cmdQuit = cmdCancel;
    } else {
      cmdQuit = cmdExit;
    }
    // #endif
  }

  // #if polish.blackberry
  // overrides
  /**
   * Handles key events.
   *
   * <p>WARNING: When this method should be overwritten, one need to ensure that super.keyPressed(
   * int ) is called!
   *
   * @param keyCode The code of the pressed key
   */
  public void keyPressed(int keyCode) {
    if (Keypad.key(keyCode) == Keypad.KEY_ESCAPE) getCommandListener().commandAction(cmdQuit, this);
    else super.keyPressed(keyCode);
  }
  // #endif

  public void showNotify() {
    super.showNotify();

    // #if polish.blackberry.isTouchBuild == true
    DeviceControl.hideSoftKeyboard();
    // #endif

    // #if !polish.blackberry
    // #if not using.native.textfield:defined
    TextUtilities.loadTextFieldCharacterset(
        "la"); // Defaulting to latin characters as we only allow latin characters in input fields
    // #endif
    // #endif

  }

  // Following snippet of code makes a screen dump of what is being displayed and saves it as a file
  // in default graphics directory
  // #if ${visualverification}==true
  // #public void paint(Graphics g)
  // #{
  // #	if(TestUtil.doPaint())
  // #	{
  // #		super.paint(TestUtil.getGraphics(g));
  // #		TestUtil.flush();
  // #	}
  // #	else
  // #		super.paint(g);
  // #}
  // #endif

  // #if ${output.keystrokes}==true
  protected boolean handleKeyReleased(int keyCode, int gameAction) {
    System.out.println(DebugUtils.addKeystrokeReleased(keyCode));
    return super.handleKeyReleased(keyCode, gameAction);
  }

  protected boolean handleKeyRepeated(int keyCode, int gameAction) {
    System.out.println(DebugUtils.addKeystrokeRepeated(keyCode));
    return super.handleKeyRepeated(keyCode, gameAction);
  }

  protected boolean handleKeyPressed(int keyCode, int gameAction) {
    System.out.println(DebugUtils.addKeystrokePressed(keyCode));
    return super.handleKeyPressed(keyCode, gameAction);
  }
  // #endif

  public void destroy() {}

  // #if polish.fix_uncaught_startup_exception
  public void create() {
    synchronized (this) {
      if (!this.isContentCreated) {
        createContent();

        this.isContentCreated = true;
      }
    }
  }
  // #endif

  protected void createContent() {}

  public byte getContext() {
    return 0;
  }
}
  public EditWebAccountForm(
      Model model, Controller controller, ExternalNetwork nw, Identity iden, Style style) {
    super(model, controller, null, style);

    this.network = nw;
    this.iden = iden;

    // #style webaccount_edit_headline
    Container info = new Container(false);
    info.setAppearanceMode(Item.PLAIN);

    // constructs network icon and sets default style to focused/'white'
    IconItem networkIcon =
        UiFactory.createNetworkIcon(
            (null != this.network ? this.network.getNetworkId() : ""), false);
    networkIcon.setStyle(networkIcon.getFocusedStyle());
    networkIcon.setAppearanceMode(Item.PLAIN);

    info.add(networkIcon);
    info.add(
        // #style webaccount_edit_headline_text
        new StringItem(
            null,
            (null != this.network ? this.network.getName() : "")
                + " "
                + Locale.get("nowplus.client.java.webaccounts.edit.info.suffix")));
    this.append(info);

    String credentialsLabel = null;
    if (nw.getCredentialsType() == ExternalNetwork.CREDENTIALS_USERNAME) {
      credentialsLabel = Locale.get("nowplus.client.java.webaccounts.edit.username");
    } else if (nw.getCredentialsType() == ExternalNetwork.CREDENTIALS_USERNAME_OR_EMAIL) {
      credentialsLabel = Locale.get("nowplus.client.java.webaccounts.edit.username_email");
    }

    // add username textfield
    this.usernameTextField =
        UiFactory.createTextField(
            null, null, 128, TextField.ANY | TextField.INITIAL_CAPS_NEVER, this);
    // fix for PBLA-816 Touch device: predictive text while disabling the surepress
    // #if polish.blackberry
    this.usernameTextField.setNoComplexInput(true);
    // #endif

    // #if using.native.textfield:defined
    this.usernameTextField.setTitle(credentialsLabel);
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(this.usernameTextField);
    // #endif
    // #endif

    // check for existing username
    if (null == this.iden) {
      this.usernameTextField.setHelpText(credentialsLabel);

      // #if polish.blackberry
      // #style ui_factory_textfield_helpfont
      usernameTextField.setHelpStyle();
      // #endif
    } else {
      this.usernameTextField.setString(this.iden.getName());

      // username uneditable in 'edit mode'
      //			this.usernameTextField.setAppearanceMode(Item.PLAIN);
    }

    // add password textfield
    this.passwordTextField =
        UiFactory.createTextField(
            null,
            null,
            128,
            TextField.NON_PREDICTIVE | TextField.INITIAL_CAPS_NEVER | TextField.PASSWORD,
            this);
    // #if using.native.textfield:defined
    this.passwordTextField.setTitle(Locale.get("nowplus.client.java.webaccounts.edit.password"));
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(this.passwordTextField);
    // #elif polish.device.textField.requires.initialCapsNeverFix
    UiFactory.fixS40NativeTextField(this.passwordTextField);
    // #endif
    // #endif

    // check for existing password
    this.passwordTextField.setHelpText(Locale.get("nowplus.client.java.webaccounts.edit.password"));

    // #if polish.blackberry
    // #style ui_factory_textfield_helpfont
    this.passwordTextField.setHelpStyle();
    // #endif

    // #if polish.blackberry
    removeCommand(cmdBack);

    // #style ui_factory_button_item
    StringItem loginButton =
        UiFactory.createButtonItem(
            null, cmdLogin.getLabel(), (de.enough.polish.ui.Command) cmdLogin, null, null);

    append(loginButton);

    // #endif

    // adding disclaimer for given network
    if (null != this.network) {
      String[] disclaimer = this.network.getDisclaimer();

      if (disclaimer[0] != null) {
        // #style .webaccount_edit_disclaimer_header
        this.append(disclaimer[0]);
      }

      for (int i = 1; i < disclaimer.length; i++) {
        // #style .webaccount_edit_disclaimer_text
        this.append(disclaimer[i]);
      }
    }

    // #if !polish.blackberry
    this.addCommand(cmdLogin);
    this.addCommand(cmdBack);
    // #endif
  }
Exemplo n.º 24
0
/**
 * TODO Add ability to cancel out of settings (warn if changes made)
 *
 * @author rossd
 */
public class SettingsView extends View
    implements ItemCommandListener, ItemStateListener, TabbedFormListener {

  private static final Command SAVE = new Command(Locale.get("main.Save"), Command.CANCEL, 1);
  private static final Command OK = new Command(Locale.get("main.Ok"), Command.OK, 1);
  private static final Command DELETE = new Command(Locale.get("main.Delete"), Command.OK, 1);

  // TabbedForm tab indexes
  private static final int DISPLAY_TAB = 1;
  private static final int GENERAL_TAB = 0;
  // private static final int MAIL_TAB = 2;
  private static final int SHORTCUTS_TAB = 2;

  // Choice item indexes for show fragment ticker
  private static final int TICKER_CONV = 0;
  private static final int TICKER_MSG = 1;
  private static final int TICKER_APPT = 2;

  // Choice item indexes for fragment ticker speed
  private static final int TICKER_SLOW = 0;
  private static final int TICKER_MED = 1;
  private static final int TICKER_FAST = 2;

  // Choice item indexes for shortcut action
  private static final int SHORTCUT_FOLDER = 0;
  private static final int SHORTCUT_TAG = 1;
  private static final int SHORTCUT_SEARCH = 2;

  private Settings mSettings;

  // General Tab Elements
  private ChoiceGroup mKeepSignedInCG;
  private ChoiceGroup mCacheContactsCG;
  private ChoiceGroup mPreloadContactsCG;
  private ChoiceGroup mDelWOConfCG;
  private ChoiceGroup mDelWOConfSubCG;
  private ChoiceItem mDWOCConvCI;
  private ChoiceItem mDWOCMsgCI;

  // Display Tab Elements
  private ChoiceGroup mTickerCG;
  private ChoiceGroup mTickerSpeedCG;

  // Shortcut Tab Elements
  private de.enough.polish.ui.ListItem mShortcutList;
  private de.enough.polish.ui.ListItem mShortcutEditScreen;
  private ChoiceGroup mShortcutActionCG;
  private ChoiceGroup mShortcutButtonCG;
  private ShortcutItem mSelectedShortcut;

  public SettingsView(ZimbraME midlet, Settings settings) {
    super(midlet);

    mSettings = settings;

    // #style SettingsView
    TabbedForm f =
        new TabbedForm(
            Locale.get("main.Settings"),
            new String[] {
              Locale.get("settings.General"),
              Locale.get("settings.Display"),
              // Locale.get("settings.Mail"),
              Locale.get("settings.Shortcuts")
            },
            null);

    // #if true
    // # mView = f;
    // #endif

    f.setItemStateListener(this);
    f.setTabbedFormListener(this);

    createGeneralTab();
    createDisplayTab();
    createShortcutsTab();

    f.addCommand(SAVE);
    f.setCommandListener(this);
    f.setItemStateListener(this);
  }

  public void setCurrent() {
    // #if true
    // # initTabContent(((TabbedForm)mView).getSelectedTab());
    // #endif
    mMidlet.mDisplay.setCurrent(mView);
  }

  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);
    }
  }

  public void commandAction(Command cmd, Displayable d) {
    if (d == Dialogs.mErrorD) {
      mMidlet.setTopViewCurrent();
    } else if (cmd == DELETE) {
      ShortcutItem item = (ShortcutItem) mShortcutList.getFocusedItem();
      item.shortcut.action = 0;
      createShortcutsTab();
    } else if (cmd == OK || cmd == CANCEL) {
      if (cmd == OK) {
        // save the current shortcut
        int button = mSelectedShortcut.shortcut.button;
        // #debug
        System.out.println("saving shortcut " + button);
        Shortcut s = mSettings.getShortcut(button);
        s.copy(mSelectedShortcut.shortcut);
      }

      createShortcutsTab();
    } else {
      try {
        mSettings.flush();
        mMidlet.setTopViewCurrent();
      } catch (IOException e) {
        Dialogs.popupErrorDialog(mMidlet, this, Locale.get("error.FailedToSaveSettings"));
      }
    }
  }

  public void notifyTabChangeCompleted(int oldTabIdx, int newTabIdx) {
    initTabContent(newTabIdx);
  }

  public boolean notifyTabChangeRequested(int oldTabIdx, int newTabIdx) {
    return true;
  }

  public void itemStateChanged(Item item) {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif
    switch (f.getActiveTab()) {
      case GENERAL_TAB:
        itemStateChangedGeneralTab(item);
        break;
      case DISPLAY_TAB:
        itemStateChangedDisplayTab(item);
        break;
      case SHORTCUTS_TAB:
        itemStateChangedShortcutsTab(item);
        break;
    }
  }

  private void itemStateChangedGeneralTab(Item item) {
    ChoiceGroup cg = (ChoiceGroup) item;
    if (cg == mKeepSignedInCG) {
      mSettings.setKeepSignedIn(cg.isSelected(0));
    } else if (cg == mCacheContactsCG) {
      mSettings.setCacheContacts(cg.isSelected(0));
    } else if (cg == mPreloadContactsCG) {
      mSettings.setPreloadContacts(cg.isSelected(0));
    } else if (cg == mDelWOConfCG) {
      setDelWOConfCG(cg.isSelected(0));
    } else if (cg == mDelWOConfSubCG) {
      mSettings.setDelWOCConv(mDWOCConvCI.isSelected);
      mSettings.setDelWOCMsg(mDWOCMsgCI.isSelected);
    }
  }

  private void itemStateChangedDisplayTab(Item item) {
    ChoiceGroup cg = (ChoiceGroup) item;
    if (cg == mTickerCG) {
      mSettings.setShowConvTicker(cg.isSelected(TICKER_CONV));
      mSettings.setShowMsgTicker(cg.isSelected(TICKER_MSG));
      mSettings.setShowApptTicker(cg.isSelected(TICKER_APPT));
    } else if (cg == mTickerSpeedCG) {
      switch (mTickerSpeedCG.getSelectedIndex()) {
        case TICKER_SLOW:
          mSettings.setTickerSpeed(Settings.SLOW_TICKER);
          break;
        case TICKER_MED:
          mSettings.setTickerSpeed(Settings.MED_TICKER);
          break;
        case TICKER_FAST:
          mSettings.setTickerSpeed(Settings.FAST_TICKER);
          break;
      }
    }
  }

  private void itemStateChangedShortcutsTab(Item item) {
    if (item == mShortcutButtonCG) {
      // #debug
      System.out.println("button: " + mShortcutButtonCG.getSelectedIndex());
      mSelectedShortcut.shortcut.button = mShortcutButtonCG.getSelectedIndex();
      return;
    }

    CollectionView v;
    switch (mShortcutActionCG.getSelectedIndex()) {
      case SHORTCUT_FOLDER:
      default:
        v = mMidlet.gotoFolderPickerView(mView);
        break;
      case SHORTCUT_TAG:
        v = mMidlet.gotoTagPickerView(mView, mSelectedShortcut.shortcut.destId);
        break;
      case SHORTCUT_SEARCH:
        v = mMidlet.gotoSavedSearchPickerView(mView);
        break;
    }
    v.setListener(new PickerListener(this, mSelectedShortcut));
  }

  private void initTabContent(int tabIdx) {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    switch (tabIdx) {
      case GENERAL_TAB:
        initGeneralTab();
        f.removeCommand(DELETE);
        break;
      case DISPLAY_TAB:
        initDisplayTab();
        f.removeCommand(DELETE);
        break;
      case SHORTCUTS_TAB:
        initShortcutsTab();
        f.addCommand(DELETE);
        break;
    }
  }

  private void initGeneralTab() {
    mKeepSignedInCG.setSelectedIndex(0, mSettings.getKeepSignedIn());
    mCacheContactsCG.setSelectedIndex(0, mSettings.getCacheContacts());
    mPreloadContactsCG.setSelectedIndex(0, mSettings.getPreloadContacts());

    setDelWOConfCG(mSettings.getDelWOConf());
    mDWOCConvCI.select(mSettings.getDelWOCConv());
    mDWOCMsgCI.select(mSettings.getDelWOCMsg());
  }

  private void initDisplayTab() {
    mTickerCG.setSelectedIndex(TICKER_CONV, mSettings.getShowConvTicker());
    mTickerCG.setSelectedIndex(TICKER_MSG, mSettings.getShowMsgTicker());
    mTickerCG.setSelectedIndex(TICKER_APPT, mSettings.getShowApptTicker());

    switch (mSettings.getTickerSpeed()) {
      case Settings.SLOW_TICKER:
        mTickerSpeedCG.setSelectedIndex(TICKER_SLOW, true);
        break;
      case Settings.MED_TICKER:
        mTickerSpeedCG.setSelectedIndex(TICKER_MED, true);
        break;
      case Settings.FAST_TICKER:
        mTickerSpeedCG.setSelectedIndex(TICKER_FAST, true);
        break;
    }
  }

  private void initShortcutsTab() {}

  private void createGeneralTab() {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    // #style ChoiceGroup
    mKeepSignedInCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mKeepSignedInCG.append(Locale.get("login.KeepSignedIn"), null);
    f.append(GENERAL_TAB, mKeepSignedInCG);

    // #style ChoiceGroup
    mCacheContactsCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mCacheContactsCG.append(Locale.get("settings.CacheContacts"), null);
    /* TODO Add this in later
    	f.append(GENERAL_TAB, mCacheContactsCG);
    */

    // ========== Preload Contacts

    // #style ChoiceGroup
    mPreloadContactsCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mPreloadContactsCG.append(Locale.get("settings.PreloadContacts"), null);
    f.append(GENERAL_TAB, mPreloadContactsCG);

    // ========== Delete w/o confirmation

    boolean delWOC = mSettings.getDelWOConf();
    // #style ChoiceGroupOffset
    mDelWOConfCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mDelWOConfCG.append(Locale.get("settings.DelWOConf"), null);
    mDelWOConfCG.setSelectedIndex(0, delWOC);
    f.append(GENERAL_TAB, mDelWOConfCG);

    // #style ChoiceGroupIndented
    mDelWOConfSubCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mDWOCConvCI = new ChoiceItem(Locale.get("settings.Conversations"), null, Choice.MULTIPLE);
    // #style ChoiceItem
    mDWOCMsgCI = new ChoiceItem(Locale.get("settings.Messages"), null, Choice.MULTIPLE);
    f.append(GENERAL_TAB, mDelWOConfSubCG);

    // TODO remove when Polish fixes bug that causes layout/highlighting weirdness if the below is
    // removed
    // #style Spacer
    StringItem s = new StringItem(null, "");
    f.append(GENERAL_TAB, s);
  }

  private void createDisplayTab() {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    // #style SpanningLabel
    StringItem s = new StringItem(null, Locale.get("settings.ShowTickersFor"));
    f.append(DISPLAY_TAB, s);

    // #style ChoiceGroupIndented
    mTickerCG = new ChoiceGroup("", ChoiceGroup.MULTIPLE);
    // #style ChoiceItem
    mTickerCG.append(Locale.get("settings.Conversations"), null);
    // #style ChoiceItem
    mTickerCG.append(Locale.get("settings.Messages"), null);
    // #style ChoiceItem
    mTickerCG.append(Locale.get("settings.Appointments"), null);
    f.append(DISPLAY_TAB, mTickerCG);

    // ========== Ticker Speed

    // #style SpanningLabel
    s = new StringItem(null, Locale.get("settings.TickerSpeed"));
    f.append(DISPLAY_TAB, s);

    // #style ChoiceGroupIndented
    mTickerSpeedCG = new ChoiceGroup(null, ChoiceGroup.EXCLUSIVE);
    // #style ChoiceItem
    mTickerSpeedCG.append(Locale.get("settings.Slow"), null);
    // #style ChoiceItem
    mTickerSpeedCG.append(Locale.get("settings.Medium"), null);
    // #style ChoiceItem
    mTickerSpeedCG.append(Locale.get("settings.Fast"), null);
    f.append(DISPLAY_TAB, mTickerSpeedCG);

    // TODO remove when Polish fixes bug that causes layout/highlighting weirdness if the below is
    // removed
    // #style Spacer
    s = new StringItem(null, "");
    f.append(DISPLAY_TAB, s);
  }

  private void createShortcutsTab() {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    // #style ChoiceGroup
    mShortcutList = new de.enough.polish.ui.ListItem(null);
    Shortcut[] shortcuts = mSettings.getShortcuts();
    Shortcut firstUnused = null;
    for (int i = 0; i < shortcuts.length; i++) {
      if (!shortcuts[i].isConfigured()) {
        firstUnused = shortcuts[i];
        break;
      }
    }

    ChoiceItem ci = null;
    if (firstUnused != null) {
      // #style ChoiceItem
      ci = new ShortcutItem(Locale.get("settings.NewShortcut"), null, List.IMPLICIT, firstUnused);
      mShortcutList.append(ci);
    }
    for (int i = 0; i < shortcuts.length; i++) {
      if (!shortcuts[i].isConfigured()) continue;
      // #style ChoiceItem
      ci = new ShortcutItem(shortcuts[i].toString(), null, List.IMPLICIT, shortcuts[i]);
      mShortcutList.append(ci);
    }

    f.deleteAll(SHORTCUTS_TAB);
    f.removeCommand(OK);
    f.removeCommand(CANCEL);
    f.addCommand(SAVE);
    f.addCommand(DELETE);
    f.append(SHORTCUTS_TAB, mShortcutList);
    mShortcutList.setItemCommandListener(this);
    mShortcutList.setDefaultCommand(List.SELECT_COMMAND);
  }

  private void createShortcutEditTab(ShortcutItem si) {
    TabbedForm f = null;
    // #if true
    // # f = (TabbedForm)mView;
    // #endif

    mSelectedShortcut = new ShortcutItem(si);
    int selectedIndex;
    switch (mSelectedShortcut.shortcut.action) {
      case Shortcut.ACTION_MOVE_TO_FOLDER:
      default:
        selectedIndex = SHORTCUT_FOLDER;
        break;
      case Shortcut.ACTION_TAG:
        selectedIndex = SHORTCUT_TAG;
        break;
      case Shortcut.ACTION_RUN_SAVED_SEARCH:
        selectedIndex = SHORTCUT_SEARCH;
        break;
    }

    mShortcutEditScreen = new de.enough.polish.ui.ListItem(Locale.get("settings.EditShortcut"));

    // #style SpanningLabel
    Item item = new StringItem(null, Locale.get("settings.Button"));
    mShortcutEditScreen.append(item);

    // #style ChoiceGroupPopup
    mShortcutButtonCG = new ChoiceGroup(null, Choice.POPUP);
    for (int i = 0; i < 10; i++) {
      // #style ChoiceItemPopup
      mShortcutButtonCG.append("# " + i, null);
    }

    mShortcutButtonCG.setSelectedIndex(mSelectedShortcut.shortcut.button, true);
    mShortcutEditScreen.append(mShortcutButtonCG);

    // #style SpanningLabel
    item = new StringItem(null, Locale.get("settings.Action"));
    mShortcutEditScreen.append(item);

    // #style ChoiceGroupIndented
    mShortcutActionCG = new ChoiceGroup(null, ChoiceGroup.EXCLUSIVE);
    // #style ChoiceItem
    mShortcutActionCG.append(
        mSelectedShortcut.shortcut.toString(false, Shortcut.ACTION_MOVE_TO_FOLDER), null);
    // #style ChoiceItem
    mShortcutActionCG.append(mSelectedShortcut.shortcut.toString(false, Shortcut.ACTION_TAG), null);
    // #style ChoiceItem
    mShortcutActionCG.append(
        mSelectedShortcut.shortcut.toString(false, Shortcut.ACTION_RUN_SAVED_SEARCH), null);
    mShortcutEditScreen.append(mShortcutActionCG);

    mShortcutActionCG.setSelectedIndex(selectedIndex, true);
    f.removeCommand(SAVE);
    f.removeCommand(DELETE);
    f.addCommand(OK);
    f.addCommand(CANCEL);
    f.deleteAll(SHORTCUTS_TAB);
    f.append(SHORTCUTS_TAB, mShortcutEditScreen);
  }

  static class ShortcutItem extends ChoiceItem {
    Shortcut shortcut;

    ShortcutItem(ShortcutItem copy) {
      super(copy.text, null, 0);
      shortcut = new Shortcut(copy.shortcut);
    }

    ShortcutItem(String text, Image image, int type, Shortcut s) {
      super(text, image, type);
      shortcut = s;
    }

    ShortcutItem(String text, Image image, int type, Shortcut s, Style style) {
      super(text, image, type, style);
      shortcut = s;
    }
  }

  static class PickerListener implements ZmeListener {
    SettingsView v;
    ShortcutItem s;

    PickerListener(SettingsView view, ShortcutItem item) {
      v = view;
      s = item;
    }

    public void action(Object obj, Object data) {
      if (data instanceof MailboxItem) handleMailboxItemPick((MailboxItem) data);
      else if (data instanceof Vector) handleMultiMailboxItemPick((Vector) data);
    }

    public void handleMailboxItemPick(MailboxItem mi) {
      if (mi instanceof Folder) s.shortcut.action = Shortcut.ACTION_MOVE_TO_FOLDER;
      else if (mi instanceof SavedSearch) s.shortcut.action = Shortcut.ACTION_RUN_SAVED_SEARCH;
      s.shortcut.destId = new String[1];
      s.shortcut.destId[0] = mi.mId;
      s.shortcut.dest = new String[1];
      s.shortcut.dest[0] = mi.mName;
      v.createShortcutEditTab(s);
    }

    public void handleMultiMailboxItemPick(Vector mi) {
      int sz = mi.size();
      s.shortcut.dest = new String[sz];
      s.shortcut.destId = new String[sz];
      for (int i = 0; i < sz; i++) {
        s.shortcut.destId[i] = ((MailboxItem) mi.elementAt(i)).mId;
        s.shortcut.dest[i] = ((MailboxItem) mi.elementAt(i)).mName;
      }
      s.shortcut.action = Shortcut.ACTION_TAG;
      v.createShortcutEditTab(s);
    }
  }

  private void setDelWOConfCG(boolean selected) {
    // TODO Hack around J2ME Polish bug that cause the items to not get focus when
    // re-enabled
    mDelWOConfSubCG.deleteAll();

    if (selected) {
      // #style ChoiceItem
      UiAccess.setAccessible(mDWOCConvCI, true);
      // #style ChoiceItem
      UiAccess.setAccessible(mDWOCMsgCI, true);
    } else {
      // #style ChoiceItemDisabled
      UiAccess.setAccessible(mDWOCConvCI, false);
      // #style ChoiceItemDisabled
      UiAccess.setAccessible(mDWOCMsgCI, false);
    }

    // TODO Continue of hack above
    // #if true
    // # mDelWOConfSubCG.append(mDWOCConvCI);
    // # mDelWOConfSubCG.append(mDWOCMsgCI);
    // #endif

    mSettings.setDelWOConf(selected);
  }
}
Exemplo n.º 25
0
public abstract class GuiOsmEntityDisplay extends Form
    implements GpsMidDisplayable,
        CommandListener,
        UploadListener,
        ItemCommandListener,
        SaveButtonListener {

  private static final Logger logger = Logger.getInstance(GuiOsmEntityDisplay.class, Logger.DEBUG);

  protected final Command BACK_CMD =
      new Command(Locale.get("generic.Back") /*Back*/, Command.BACK, 1);
  protected final Command OK_CMD = new Command(Locale.get("generic.OK") /*OK*/, Command.OK, 1);
  protected final Command ADD_CMD =
      new Command(Locale.get("guiosmentitydisplay.AddTag") /*Add tag*/, Command.ITEM, 2);
  protected final Command EDIT_CMD =
      new Command(Locale.get("guiosmentitydisplay.EditTag") /*Edit tag*/, Command.ITEM, 2);
  protected final Command REMOVE_CMD =
      new Command(Locale.get("guiosmentitydisplay.RemoveTag") /*Remove tag*/, Command.ITEM, 3);
  protected final Command UPLOAD_CMD =
      new Command(Locale.get("guiosmentitydisplay.UploadToOSM") /*Upload to OSM*/, Command.OK, 6);
  protected final Command REMOVE_ENTITY_CMD =
      new Command(
          Locale.get("guiosmentitydisplay.RemoveEntity") /*Remove Entity*/, Command.ITEM, 3);
  protected final Command CREATE_CHANGE_CMD =
      new Command(
          Locale.get("guiosmentitydisplay.CreateChangeset") /*Create changeset*/, Command.OK, 6);
  protected final Command CLOSE_CHANGE_CMD =
      new Command(
          Locale.get("guiosmentitydisplay.CloseChangeset") /*Close changeset*/, Command.OK, 6);

  protected static final int LOAD_STATE_NONE = 0;
  protected static final int LOAD_STATE_LOAD = 1;
  protected static final int LOAD_STATE_UPLOAD = 2;
  protected static final int LOAD_STATE_CHANGESET = 3;
  protected static final int LOAD_STATE_DELETE_CHANGESET = 4;
  protected static final int LOAD_STATE_DELETE = 5;

  protected GpsMidDisplayable parent;
  protected static GuiOsmChangeset changesetGui;
  protected int loadState;

  protected OsmDataEntity osmentity;
  protected Image typeImage;

  protected boolean addTag;

  public GuiOsmEntityDisplay(String title, GpsMidDisplayable parent) {
    super(title);
    this.parent = parent;
    addCommand(BACK_CMD);
    addCommand(ADD_CMD);
    addCommand(UPLOAD_CMD);
    addCommand(REMOVE_ENTITY_CMD);
    addCommand(CREATE_CHANGE_CMD);
    addCommand(CLOSE_CHANGE_CMD);
    setCommandListener(this);

    osmentity = null;
  }

  protected void setupScreen() {
    try {
      this.deleteAll();
      addTag = false;
      if (osmentity == null) {
        this.append(
            new StringItem(
                Locale.get("guiosmentitydisplay.NoDataAvailable") /*No Data available*/, "..."));
        return;
      }
      Hashtable tags = osmentity.getTags();
      if (tags == null) return;
      Enumeration keysEn = tags.keys();
      while (keysEn.hasMoreElements()) {
        String key = (String) keysEn.nextElement();
        Item i = new StringItem(key, (String) tags.get(key));
        i.addCommand(EDIT_CMD);
        i.addCommand(REMOVE_CMD);
        i.setItemCommandListener(this);
        // #style formItem
        this.append(i);
      }
      if (osmentity.getVersion() > 0) {
        // #style formItem
        this.append(new StringItem(Locale.get("guiosmentitydisplay.Edited") /*Edited */, null));
        // #style formItem
        this.append(
            new StringItem(
                Locale.get("guiosmentitydisplay.at") /*    at:*/, osmentity.getEditTime()));
        // #style formItem
        this.append(
            new StringItem(
                Locale.get("guiosmentitydisplay.by") /*    by:*/, osmentity.getEditor()));
        // #style formItem
        this.append(
            new StringItem(
                Locale.get("guiosmentitydisplay.ver") /*    ver:*/,
                Integer.toString(osmentity.getVersion())));
      }
      // #if polish.android
      ViewItem createButton =
          new SaveButton(
              Locale.get("guiosmentitydisplay.CreateChangeset") /*Create changeset*/,
              this,
              (Displayable) this,
              CREATE_CHANGE_CMD);
      ViewItem closeButton =
          new SaveButton(
              Locale.get("guiosmentitydisplay.CloseChangeset") /*Close changeset*/,
              this,
              (Displayable) this,
              CLOSE_CHANGE_CMD);
      this.append(createButton);
      this.append(closeButton);
      AndroidDisplay ad = AndroidDisplay.getDisplay(GpsMid.getInstance());
      ad.setOnKeyListener(
          new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
              if (event.getAction() == KeyEvent.ACTION_DOWN) {
                // check if the right key was pressed
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                  backPressed();
                  return true;
                }
              }
              return false;
            }
          });
      // #endif
    } catch (Exception e) {
      logger.exception(
          Locale.get(
              "guiosmentitydisplay.InitialisingEntityTagScreenFailed") /*Initialising entity tag screen failed: */,
          e);
    }
  }

  public void commandAction(Command c, Displayable d) {
    if (c == BACK_CMD) {
      if (d == this) {
        parent.show();
      } else {
        show();
      }
    }
    if (c == ADD_CMD) {
      this.addTag = true;
      TextField tf =
          new TextField(Locale.get("guiosmentitydisplay.key") /*key*/, "", 100, TextField.ANY);
      tf.addCommand(OK_CMD);
      tf.setItemCommandListener(this);
      this.append(tf);
      Display.getDisplay(GpsMid.getInstance()).setCurrentItem(tf);
      tf = new TextField(Locale.get("guiosmentitydisplay.value") /*value*/, "", 100, TextField.ANY);
      tf.addCommand(OK_CMD);
      tf.setItemCommandListener(this);
      this.append(tf);
    }

    if (c == CREATE_CHANGE_CMD) {
      changesetGui = new GuiOsmChangeset(this, this);
      changesetGui.show();
    }

    if (c == CLOSE_CHANGE_CMD) {
      if (changesetGui == null) {
        logger.error(
            Locale.get(
                "guiosmentitydisplay.NoChangesetIsCurrentlyOpen") /*No changeset is currently open*/);
      } else {
        changesetGui.closeChangeset();
        changesetGui = null;
      }
    }
  }

  public void show() {
    GpsMid.getInstance().show(this);
  }

  public void startProgress(String title) {
    // Not supported/used at the moment.
  }

  public void setProgress(String message) {
    // Not supported/used at the moment.

  }

  public void updateProgress(String message) {
    // Not supported/used at the moment.

  }

  public abstract void completedUpload(boolean success, String message);

  public void uploadAborted() {
    // TODO Auto-generated method stub

  }

  public void updateProgressValue(int value) {
    // TODO Auto-generated method stub

  }

  public void commandAction(Command c, Item it) {
    // #debug info
    logger.info("Command " + c + " Item " + it);
    Hashtable tags = osmentity.getTags();
    if (c == REMOVE_CMD) {
      tags.remove(((StringItem) it).getLabel());
      setupScreen();
    }
    if (c == EDIT_CMD) {
      for (int i = 0; i < this.size(); i++) {
        if (this.get(i) == it) {
          StringItem si = (StringItem) it;
          this.delete(i);
          TextField tf = new TextField(it.getLabel(), si.getText(), 100, TextField.ANY);
          tf.addCommand(OK_CMD);
          tf.setItemCommandListener(this);
          this.insert(i, tf);
          Display.getDisplay(GpsMid.getInstance()).setCurrentItem(tf);
        }
      }
    }

    if (c == OK_CMD) {
      if (addTag) {
        tags.put(
            ((TextField) this.get(this.size() - 2)).getString(),
            ((TextField) this.get(this.size() - 1)).getString());
      } else {
        for (int i = 0; i < this.size(); i++) {
          if (this.get(i) == it) {
            TextField tf = (TextField) it;
            tags.put(it.getLabel(), tf.getString());
          }
        }
      }
      addTag = false;
      setupScreen();
    }
  }

  public void refresh() {}

  public void backPressed() {
    parent.show();
  }
}
Exemplo n.º 26
0
  public void run() {
    PaintContext createPC = null;
    final byte MAXCRASHES = 5;
    byte crash = 0;
    do {
      try {

        while (!shutdown) {

          if (!needRedraw || suspended) {
            synchronized (this) {
              try {
                /* FIXME: We still have some situations where redraw is not done automatically immediately,
                 * e.g. on Nokia 5800 after returning from another Displayable
                 * Therefore reduce the timeout for redrawing anyway from 30 seconds to 1 seconds
                 * if the last user interaction happened less than 1.5 secs before

                if (Trace.getDurationSinceLastUserActionTime() > 1500 ) {
                	wait(30000);
                } else {
                	wait(1000);
                }
                */
                wait(30000);
              } catch (InterruptedException e) {
                continue; // Recheck condition of the loop
              }
            }
          }

          needRedraw = false; // moved here and deleted from the bottom of this routine

          // #debug debug
          logger.debug("Redrawing Map");

          iDrawState = 1;

          synchronized (this) {
            while (pc[nextCreate].state != PaintContext.STATE_READY && !shutdown) {
              try {
                // System.out.println("img not ready");
                wait(1000);
              } catch (InterruptedException e) {
              }
            }
            if (suspended || shutdown) {
              continue;
            }
            pc[nextCreate].state = PaintContext.STATE_IN_CREATE;
          }

          iDrawState = 2;

          createPC = pc[nextCreate];

          long startTime = System.currentTimeMillis();

          // create PaintContext
          createPC.xSize = nextSc.xSize;
          createPC.ySize = nextSc.ySize;
          createPC.center = nextSc.center.copy();
          mapCenter = nextSc.center.copy();
          createPC.scale = nextSc.scale;
          createPC.course = nextSc.course;
          //				Projection p = ProjFactory.getInstance(createPC.center,
          //						nextSc.course, nextSc.scale, xSize, ySize);
          createPC.setP(nextSc.getP());
          //				p.inverse(xSize, 0, createPC.screenRU);
          //				p.inverse(0, ySize, createPC.screenLD);
          // pcCollect.trace = nextSc.trace;
          // pcCollect.dataReader = nextSc.dataReader;
          // cleans the screen
          createPC.g = img[nextCreate].getGraphics();
          createPC.g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
          createPC.g.fillRect(0, 0, xSize, ySize);

          //				createPC.g.setColor(0x00FF0000);
          //				createPC.g.drawRect(0, 0, xSize - 1, ySize - 1);
          //				createPC.g.drawRect(20, 20, xSize - 41, ySize - 41);
          createPC.squareDstWithPenToWay = Float.MAX_VALUE;
          createPC.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
          createPC.squareDstWithPenToRoutePath = Float.MAX_VALUE;
          createPC.squareDstToRoutePath = Float.MAX_VALUE;
          createPC.dest = nextSc.dest;
          createPC.waysPainted = 0;

          // System.out.println("create " + pcCollect);

          Way.setupDirectionalPenalty(createPC, tr.speed, tr.gpsRecenter && !tr.gpsRecenterInvalid);

          float boost = Configuration.getMaxDetailBoostMultiplier();

          /*
           * layers containing highlighted path segments
           */
          createPC.hlLayers = 0;

          /*
           * highlighted path is on top if gps recentered, but if not it might still come to top
           * when we determine during painting that the cursor is closer than 25 meters at the route line.
           */
          createPC.highlightedPathOnTop = tr.gpsRecenter;

          /**
           * At the moment we don't really have proper layer support in the data yet, so only split
           * it into Area, Way and Node layers
           */
          byte layersToRender[] = {
            Tile.LAYER_AREA,
            1 | Tile.LAYER_AREA,
            2 | Tile.LAYER_AREA,
            3 | Tile.LAYER_AREA,
            4 | Tile.LAYER_AREA,
            0,
            1,
            2,
            3,
            4,
            Tile.LAYER_NODE,
            0 | Tile.LAYER_HIGHLIGHT,
            1 | Tile.LAYER_HIGHLIGHT,
            2 | Tile.LAYER_HIGHLIGHT,
            3 | Tile.LAYER_HIGHLIGHT
          };

          /**
           * Draw each layer separately to enforce paint ordering:
           *
           * <p>Go through the entire tile tree multiple times to get the drawing order correct.
           *
           * <p>The first 5 layers correspond to drawing areas with the osm layer tag of (< -1, -1,
           * 0, 1, >1), then next 5 layers are drawing streets with osm layer tag (< -1, -1, 0, 1,
           * >1).
           *
           * <p>Then we draw the highlighted streets and finally we draw the POI layer.
           *
           * <p>So e. g. layer 7 corresponds to all streets that have no osm layer tag or layer = 0.
           */
          boolean simplifyMap =
              Configuration.getCfgBitState(Configuration.CFGBIT_SIMPLIFY_MAP_WHEN_BUSY);
          boolean skippableLayer = false;

          if (Configuration.getCfgBitState(Configuration.CFGBIT_TMS_BACKGROUND)) {
            RasterTile.drawRasterMap(createPC, createPC.trace.rootWindow);
          }
          for (byte layer = 0; layer < layersToRender.length; layer++) {
            if (simplifyMap) {
              skippableLayer =
                  ((layer < 5 && layer > 1)
                      // #if polish.api.finland
                      // don't skip node layer where speed camera is if camera alert is on
                      || (layer == 14
                          && !Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDCAMERA_ALERT))
                      // #else
                      || (layer == 14)
                      // #endif
                      // #if polish.android
                      || (Trace.getInstance().mapBrowsing && ((layer < 5) || layer == 14))
                      // #else
                      || (Trace.getInstance().mapBrowsing
                          && ((layer < 5 && layer > 1) || layer == 14))
                  // #endif
                  );
              // skip update if a new one is queued
              if (needRedraw && skippableLayer) {
                continue;
              }
            }

            if (layersToRender[layer] == Tile.LAYER_NODE) {
              tr.resetClickableMarkers();
            }

            // render only highlight layers which actually have highlighted path segments
            if ((layersToRender[layer] & Tile.LAYER_HIGHLIGHT) > 0
                && layersToRender[layer] != Tile.LAYER_NODE) {
              /**
               * as we do two passes for each way layer when gps recentered - one for the ways and
               * one for the route line on top, we can use in the second pass the determined route
               * path connection / idx to highlight the route line in the correct / prior route line
               * color. when not gps recentered, this info will be by one image obsolete however
               */
              if (layersToRender[layer]
                  == Tile
                      .LAYER_HIGHLIGHT /*(0 | Tile.LAYER_HIGHLIGHT) pointless bitwise operation*/) {
                /*
                 *  only take ImageCollector loops into account for dstToRoutePath if ways were painted
                 *  otherwise this would trigger wrong route recalculations
                 */
                if (createPC.waysPainted != 0) {
                  // RouteInstructions.dstToRoutePath =
                  // createPC.getDstFromSquareDst(createPC.squareDstToRoutePath);
                  RouteInstructions.dstToRoutePath = createPC.getDstFromRouteSegment();
                  if (RouteInstructions.dstToRoutePath != RouteInstructions.DISTANCE_UNKNOWN) {
                    RouteInstructions.routePathConnection = createPC.routePathConnection;
                    RouteInstructions.pathIdxInRoutePathConnection =
                        createPC.pathIdxInRoutePathConnection;
                    RouteInstructions.actualRoutePathWay = createPC.actualRoutePathWay;
                    // when we determine during painting that the cursor is closer than 25 meters at
                    // the route line, bring it to the top
                    if (RouteInstructions.dstToRoutePath < 25) {
                      createPC.highlightedPathOnTop = true;
                    }
                  }
                  // System.out.println("waysPainted: " + createPC.waysPainted);
                } else {
                  // FIXME: Sometimes there are ImageCollector loop with no way pained even when
                  // ways would be there and tile data is fully loaded
                  // Update 2011-06-11: Might be fixed with the patch from gojkos at [
                  // sharenav-Bugs-3310178 ] Delayed map draw on LG cookie phone
                  // Update 2012-03-17 (patch from walter9): The image collector has been started
                  // twice. This seems to be fixed now in Trace.java.startImageCollector()
                  System.out.println("No ways painted in this ImageCollector loop");
                }
              }
              byte relLayer = (byte) (((int) layersToRender[layer]) & 0x0000000F);
              if ((createPC.hlLayers & (1 << relLayer)) == 0) {
                continue;
              }
            }
            minTile = Legend.scaleToTile((int) (createPC.scale / (boost * overviewTileScaleBoost)));

            if (t[0] != null) {
              if (needRedraw && skippableLayer) {
                continue;
              }
              t[0].paint(createPC, layersToRender[layer]);
              if (needRedraw && skippableLayer) {
                continue;
              }
            }
            if ((minTile >= 1) && (t[1] != null)) {
              if (needRedraw && skippableLayer) {
                continue;
              }
              t[1].paint(createPC, layersToRender[layer]);
              if (needRedraw && skippableLayer) {
                continue;
              }
              Thread.yield();
            }
            if ((minTile >= 2) && (t[2] != null)) {
              if (needRedraw && skippableLayer) {
                continue;
              }
              t[2].paint(createPC, layersToRender[layer]);
              if (needRedraw && skippableLayer) {
                continue;
              }
              Thread.yield();
            }
            if ((minTile >= 3) && (t[3] != null)) {
              if (needRedraw && skippableLayer) {
                continue;
              }
              t[3].paint(createPC, layersToRender[layer]);
              if (needRedraw && skippableLayer) {
                continue;
              }
              Thread.yield();
            }

            /** Drawing waypoints */
            if (t[DictReader.GPXZOOMLEVEL] != null) {
              t[DictReader.GPXZOOMLEVEL].paint(createPC, layersToRender[layer]);
            }
            if (suspended) {
              // Don't continue rendering if suspended
              createPC.state = PaintContext.STATE_READY;
              break;
            }
          }
          /** Drawing debuginfo for routing */
          if (!suspended
              && t[DictReader.ROUTEZOOMLEVEL] != null
              && (Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_CONNECTIONS)
                  || Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_TURN_RESTRICTIONS))) {
            t[DictReader.ROUTEZOOMLEVEL].paint(createPC, (byte) 0);
          }

          iDrawState = 0;

          icDuration = System.currentTimeMillis() - startTime;
          // #mdebug
          logger.info("Painting map took " + icDuration + " ms");
          // #enddebug
          System.out.println("Painting map took " + icDuration + " ms " + xSize + "/" + ySize);

          createPC.state = PaintContext.STATE_READY;
          lastCreatedSc = createPC.cloneToScreenContext();
          if (!shutdown) {
            newCollected();
          }
          createImageCount++;
          // needRedraw = false;
          tr.cleanup();
          // System.out.println("create ready");
          // System.gc();
        }
      } catch (OutOfMemoryError oome) {
        if (createPC != null) {
          createPC.state = PaintContext.STATE_READY;
        }
        String recoverZoomedIn = "";
        crash++;
        if (tr.scale > 10000 && crash < MAXCRASHES) {
          tr.scale /= 1.5f;
          recoverZoomedIn =
              Locale.get("imagecollector.ZoomingInToRecover") /* Zooming in to recover.*/;
        }
        logger.fatal(
            Locale.get(
                    "imagecollector.ImageCollectorRanOutOfMemory") /*ImageCollector ran out of memory: */
                + oome.getMessage()
                + recoverZoomedIn);
      } catch (Exception e) {
        crash++;
        logger.exception(
            Locale.get(
                "imagecollector.ImageCollectorCrashed") /*ImageCollector thread crashed unexpectedly with error */,
            e);
      }
      if (crash >= MAXCRASHES) {
        logger.fatal(
            Locale.get(
                "imagecollector.ImageCollectorCrashedAborting") /*ImageCollector crashed too often. Aborting.*/);
      }
    } while (!shutdown && crash < MAXCRASHES);
    processorThread = null;
    synchronized (this) {
      notifyAll();
    }
  }
Exemplo n.º 27
0
public class GuiGpxOsmUpload extends Form
    implements GpsMidDisplayable, CommandListener, ExportSession {

  private static final Logger logger = Logger.getInstance(GuiGpxOsmUpload.class, Logger.DEBUG);

  private static final Command BACK_CMD =
      new Command(Locale.get("generic.Cancel") /*Cancel*/, Command.BACK, 2);
  private static final Command OK_CMD =
      new Command(Locale.get("guigpxosmupload.Upload") /*Upload*/, Command.OK, 1);

  private TextField descriptionTF;
  private TextField tagsTF;
  private ChoiceGroup publicCG;

  private String description;
  private String tags;

  private boolean proceed = false;

  private ByteArrayOutputStream gpxOS;

  private String url;
  private String name;
  private boolean publicFlag;

  public GuiGpxOsmUpload() {
    super(Locale.get("guigpxosmupload.GPXToOSM") /*GPX upload to OSM*/);

    descriptionTF =
        new TextField(
            Locale.get("guigpxosmupload.Description") /*Description:*/, "", 255, TextField.ANY);
    tagsTF = new TextField(Locale.get("guigpxosmupload.Tags") /*Tags:*/, "", 255, TextField.ANY);
    String[] items = new String[1];
    items[0] = Locale.get("guigpxosmupload.Public") /*Public*/;
    publicCG = new ChoiceGroup("", Choice.MULTIPLE, items, null);

    this.append(descriptionTF);
    this.append(tagsTF);
    this.append(publicCG);
    this.addCommand(OK_CMD);
    this.addCommand(BACK_CMD);
    this.setCommandListener(this);
  }

  public void upload() throws IOException {
    logger.info(Locale.get("guigpxosmupload.UploadingOSMGPX") /*Uploading OSM GPX*/);
    int respCode;
    String respMessage;
    try {
      HttpConnection connection = (HttpConnection) Connector.open(url);
      System.out.println(Locale.get("guigpxosmupload.Connection") /*Connection: */ + connection);
      connection.setRequestMethod(HttpConnection.POST);
      connection.setRequestProperty("Connection", "close");
      connection.setRequestProperty("User-Agent", "GpsMid");

      connection.setRequestProperty(
          "Authorization",
          "Basic "
              + Base64.encode(Configuration.getOsmUsername() + ":" + Configuration.getOsmPwd()));

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(baos);

      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"file\"; filename=\"" + name + "\"\r\n");
      osw.write("Content-Type: application/octet-stream\r\n\r\n");
      osw.write(new String(gpxOS.toByteArray()));
      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"tags\"\r\n\r\n");
      osw.write(tags + "\r\n");
      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
      osw.write(description + "\r\n");
      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"public\"\r\n\r\n");
      osw.write(publicFlag ? "1" : "0" + "\r\n");
      osw.write("-----------------------------12132519071893744613145780879--\r\n");
      osw.flush();
      connection.setRequestProperty("Content-Length", Integer.toString(baos.toByteArray().length));
      connection.setRequestProperty(
          "Content-Type",
          "multipart/form-data; boundary=---------------------------12132519071893744613145780879");
      OutputStream os = connection.openOutputStream();
      os.write(baos.toByteArray());
      os.flush();

      // HTTP Response
      respCode = connection.getResponseCode();
      respMessage = connection.getResponseMessage();
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(
          Locale.get("guigpxosmupload.FailedUploadingGPX") /*Failed uploading GPX: */
              + e.getMessage());
    }

    if (respCode == HttpConnection.HTTP_OK) {
      logger.info("Successfully uploaded GPX");

    } else {
      throw new IOException(
          Locale.get("guigpxosmupload.GPXTraceNotAccepted") /*GPX trace was not accepted (*/
              + respCode
              + "): "
              + respMessage);
    }
  }

  public void show() {
    GpsMid.getInstance().show(this);
  }

  public synchronized void commandAction(Command c, Displayable d) {
    if (c == OK_CMD) {

      description = descriptionTF.getString();
      tags = tagsTF.getString();
      boolean[] publicFlags = new boolean[1];
      publicCG.getSelectedFlags(publicFlags);
      publicFlag = publicFlags[0];
      proceed = true;
      logger.info("Uploading GPX: desc=" + description + " tags=" + tags + " public=" + publicFlag);
      GpsMid.getInstance().showPreviousDisplayable();
      notifyAll();
    }
    if (c == BACK_CMD) {
      proceed = false;
      GpsMid.getInstance().showPreviousDisplayable();
      notifyAll();
    }
  }

  public void closeSession() throws IOException {
    upload();
  }

  public OutputStream openSession(String url, String name) {
    this.url = url;
    this.name = name;
    show();
    synchronized (this) {
      try {
        wait();
      } catch (InterruptedException e) {
        return null;
      }
    }
    if (!proceed) return null;
    gpxOS = new ByteArrayOutputStream();
    return gpxOS;
  }
}
Exemplo n.º 28
0
  /**
   * copy the last created image to the real screen
   *
   * <p>public void restart() { processorThread = new Thread(this, "ImageCollector"); //#if
   * polish.android processorThread.setPriority(Thread.MAX_PRIORITY); //#else
   * processorThread.setPriority(Thread.MIN_PRIORITY); //#endif //#if not polish.api.paintdirect
   * processorThread.start(); //#endif }
   *
   * <p>/** copy the last created image to the real screen but with the last collected position and
   * direction in the center
   */
  public Node paint(PaintContext screenPc) {

    PaintContext paintPC;
    // System.out.println("paint this: " + screenPc);
    // System.out.println("paint image: " + pc[nextPaint]);
    if (suspended || !collectorReady) {
      return new Node(0, 0);
    }

    // Define the parameters for the next image that will be created
    nextSc.center = screenPc.center.copy();
    nextSc.course = screenPc.course;
    nextSc.scale = screenPc.scale;
    nextSc.dest = screenPc.dest;
    nextSc.xSize = screenPc.xSize;
    nextSc.ySize = screenPc.ySize;
    Projection p =
        ProjFactory.getInstance(nextSc.center, nextSc.course, nextSc.scale, xSize, ySize);
    //		System.out.println("p  =" + p);
    Projection p1 =
        ProjFactory.getInstance(
            nextSc.center, pc[nextPaint].course, pc[nextPaint].scale, xSize, ySize);
    //		System.out.println("p  =" + p1);
    nextSc.setP(p);
    screenPc.setP(p);

    synchronized (this) {
      if (pc[nextPaint].state != PaintContext.STATE_READY) {
        logger.error(
            Locale.get(
                    "imagecollector.ImageCollectorNonReadyPaintContext") /*ImageCollector was trying to draw a non ready PaintContext */
                + pc[nextPaint].state);
        return new Node(0, 0);
      }
      paintPC = pc[nextPaint];
      paintPC.state = PaintContext.STATE_IN_PAINT;
    }
    int screenXCenter = xSize / 2 - xScreenOverscan;
    int screenYCenter = ySize / 2 - yScreenOverscan;
    int newXCenter = screenXCenter;
    int newYCenter = screenYCenter;

    // return center of the map image drawn to the caller
    Node getDrawnCenter = paintPC.center.copy();
    if (p.isOrthogonal()) {
      // maps can painted so that the hotspot is at the predefined point on the screen
      // therfore the offset is useful in that case its not necessary to create a new image
      // if the position has changed less then half of the offset
      if (lastCreatedSc != null) {
        p1.forward(lastCreatedSc.center, oldCenter);
        newXCenter = oldCenter.x - p.getImageCenter().x + screenXCenter;
        newYCenter = oldCenter.y - p.getImageCenter().y + screenYCenter;
        // System.out.println("Paint pos = " + newXCenter + "/" +
        // newYCenter);
        // System.out.println("Paint ysize=" + ySize + " nextSc.xSize="
        // + nextSc.ySize + " hotspot=" + p.getImageCenter());

      }
      screenPc.g.drawImage(
          img[nextPaint], newXCenter, newYCenter, Graphics.VCENTER | Graphics.HCENTER);
      // Test if the new center is around the middle of the screen, in which
      // case we don't need to redraw (recreate a new image), as nothing has changed.
      if (Math.abs(newXCenter - screenXCenter) > 4
          || Math.abs(newYCenter - screenYCenter) > 4
          || paintPC.course != nextSc.course) {
        // The center of the screen has moved or rotated, so need
        // to redraw the map image
        needRedraw = true;
        // System.out.println("wakeup thread because course or position changed");
        // System.out.println("Changed " + newXCenter + "->" +
        // screenXCenter + " and " + newYCenter + "->" + screenYCenter);
      }
    } else {
      screenPc.g.drawImage(
          img[nextPaint], screenXCenter, screenYCenter, Graphics.VCENTER | Graphics.HCENTER);
      p.forward(lastCreatedSc.center, oldCenter);
      newXCenter = oldCenter.x - p.getImageCenter().x + screenXCenter;
      newYCenter = oldCenter.y - p.getImageCenter().y + screenYCenter;
      if (Math.abs(newXCenter - screenXCenter) > 1
          || Math.abs(newYCenter - screenYCenter) > 1
          || paintPC.course != nextSc.course) {
        needRedraw = true;
      }
    }

    // screenPc.g.drawArc(newXCenter-14, newYCenter-14, 28, 28, 0, 360);
    //		if (p instanceof Proj3D){
    //			screenPc.g.setColor(255,50,50);
    //			IntPoint pt0 = new IntPoint();
    //			IntPoint pt1 = new IntPoint();
    //			Proj3D p3=(Proj3D)p;
    //			p.forward(p3.borderLD,pt0);
    //			p.forward(p3.borderLU,pt1);
    //			screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
    //			p.forward(p3.borderRU,pt0);
    //			screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
    //			p.forward(p3.borderRD,pt1);
    //			screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
    //			p.forward(p3.borderLD,pt0);
    //			screenPc.g.drawLine(pt0.x, pt0.y, pt1.x, pt1.y);
    //
    //		}
    String name = null;
    Way wayForName = null;
    /**
     * used to check for pixel distances because checking for meters from converted pixels requires
     * to be exactly on the pixel when zoomed out far
     */
    final int SQUARE_MAXPIXELS = 5 * 5;
    // Tolerance of 15 pixels converted to meters
    float pixDest = 15 / paintPC.ppm;
    if (pixDest < 15) {
      pixDest = 15;
    }
    if (paintPC.trace.gpsRecenter) {
      // Show closest routable way name if map is gpscentered and we are
      // closer
      // than SQUARE_MAXPIXELS or 30 m (including penalty) to it.
      // If the routable way is too far away, we try the closest way.
      if (paintPC.bUsedGpsCenter == false) {
        if (paintPC.squareDstWithPenToActualRoutableWay < SQUARE_MAXPIXELS
            || paintPC.getDstFromSquareDst(paintPC.squareDstWithPenToActualRoutableWay) < 30) {
          wayForName = paintPC.actualRoutableWay;
        } else if (paintPC.squareDstWithPenToWay < SQUARE_MAXPIXELS
            || paintPC.getDstFromSquareDst(paintPC.squareDstWithPenToWay) < 30) {
          wayForName = paintPC.actualWay;
        }
      } else {
        if (paintPC.getDstFromRouteableWay() < 100) {
          wayForName = paintPC.actualRoutableWay;
        } else if (paintPC.getDstFromWay() < 100) {
          wayForName = paintPC.actualWay;
        }
      }
    } else if (paintPC.getDstFromSquareDst(paintPC.squareDstWithPenToWay) <= pixDest) {
      // If not gpscentered show closest way name if it's no more than 15
      // pixels away.
      wayForName = paintPC.actualWay;
    }
    /*
     * As we are double buffering pc, nothing should be writing to paintPC
     * therefore it should be safe to access the volatile variable actualWay
     */
    if (paintPC.actualWay != null) {
      screenPc.actualWay = paintPC.actualWay;
      screenPc.actualSingleTile = paintPC.actualSingleTile;
      tr.actualWay = paintPC.actualWay;
      tr.actualSingleTile = paintPC.actualSingleTile;
    }
    if (wayForName != null) {
      int nummaxspeed;
      String maxspeed = "";
      String winter = "";
      // store for OSM editing
      if (wayForName.getMaxSpeed() != 0) {
        nummaxspeed = wayForName.getMaxSpeed();
        if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
            && (wayForName.getMaxSpeedWinter() > 0)) {
          nummaxspeed = wayForName.getMaxSpeedWinter();
          winter = Locale.get("imagecollector.Winter") /*W */;
        }
        if (nummaxspeed == Legend.MAXSPEED_MARKER_NONE) {
          maxspeed =
              Locale.get("imagecollector.SL") /* SL:*/
                  + winter
                  + Locale.get("imagecollector.MaxSpeedNone") /*none*/;
        } else if (nummaxspeed == Legend.MAXSPEED_MARKER_VARIABLE) {
          maxspeed =
              Locale.get("imagecollector.SL") /* SL:*/
                  + winter
                  + Locale.get("imagecollector.MaxSpeedVariable") /*var*/;
        } else if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
          maxspeed = Locale.get("imagecollector.SL") /* SL:*/ + winter + nummaxspeed;
        } else {
          // Round up at this point, as the the previouse two
          // conversions
          // were rounded down already. (Seems to work better for
          // speed limits of
          // 20mph and 30mph)
          maxspeed =
              Locale.get("imagecollector.SL") /* SL:*/
                  + winter
                  + ((int) (nummaxspeed / 1.609344f + 0.5f));
        }
      }

      if (wayForName.nameIdx != -1) {
        name = screenPc.trace.getName(wayForName.nameIdx);
      } else {
        // #if polish.api.bigstyles
        WayDescription wayDesc = Legend.getWayDescription(wayForName.type);
        // #else
        WayDescription wayDesc = Legend.getWayDescription((short) (wayForName.type & 0xff));
        // #endif
        name = Locale.get("imagecollector.unnamed") /*(unnamed */ + wayDesc.description + ")";
      }
      if (name == null) {
        name = maxspeed;
      } else {
        name = name + maxspeed;
      }
      // If there's an URL associated with way, show a letter next to name
      if (wayForName.urlIdx != -1) {
        name = name + Locale.get("imagecollector.W") /* W*/;
      }
      // Show 'P' for phone number
      if (wayForName.phoneIdx != -1) {
        name = name + Locale.get("imagecollector.P") /* P*/;
      }
    }
    // use the nearest routable way for the the speed limit detection if
    // it's
    // closer than 30 m or SQUARE_MAXPIXELS including penalty
    if (paintPC.squareDstWithPenToActualRoutableWay < SQUARE_MAXPIXELS
        || paintPC.getDstFromSquareDst(paintPC.squareDstWithPenToActualRoutableWay) < 30) {
      tr.actualSpeedLimitWay = paintPC.actualRoutableWay;
    } else {
      tr.actualSpeedLimitWay = null;
    }

    boolean showLatLon = Configuration.getCfgBitState(Configuration.CFGBIT_SHOWLATLON);

    LayoutElement e = Trace.tl.ele[TraceLayout.WAYNAME];
    if (showLatLon) {
      // #if polish.api.finland
      // show Finnish ETRS-TM35FIN coordinates
      // FIXME: add a config option for selection of coordinates
      if (false) {
        PositionMark pmETRS =
            ETRSTM35FINconvert.latlonToEtrs(paintPC.center.radlat, paintPC.center.radlon);
        e.setText(
            Locale.get("imagecollector.lat") /* lat: */
                + Float.toString(pmETRS.lat)
                + " "
                + Locale.get("imagecollector.lon") /* lon: */
                + Float.toString(pmETRS.lon));
      } else {
        // #endif
        e.setText(
            Locale.get("imagecollector.lat") /* lat: */
                + Float.toString(paintPC.center.radlat * MoreMath.FAC_RADTODEC)
                + " "
                + Locale.get("imagecollector.lon") /* lon: */
                + Float.toString(paintPC.center.radlon * MoreMath.FAC_RADTODEC));
        // #if polish.api.finland
      }
      // #endif
    } else {
      if (name != null && name.length() > 0) {
        e.setText(name);
      } else {
        e.setText(" ");
      }
    }

    if (paintPC.scale != screenPc.scale) {
      //			System.out.println("wakeup thread because scale changed");
      needRedraw = true;
    }

    // when the projection has changed we must redraw
    if (!paintPC.getP().getProjectionID().equals(screenPc.getP().getProjectionID())) {
      //			System.out.println("wakeup thread because projection changed");
      needRedraw = true;
    }

    synchronized (this) {
      paintPC.state = PaintContext.STATE_READY;
      if (needRedraw) {
        notify();
      } else {
        //				System.out.println("No need to redraw after painting");
      }
    }
    // currentVisibleSc=lastCreatedSc.cloneToScreenContext();
    return getDrawnCenter;
  }
Exemplo n.º 29
0
  public void upload() throws IOException {
    logger.info(Locale.get("guigpxosmupload.UploadingOSMGPX") /*Uploading OSM GPX*/);
    int respCode;
    String respMessage;
    try {
      HttpConnection connection = (HttpConnection) Connector.open(url);
      System.out.println(Locale.get("guigpxosmupload.Connection") /*Connection: */ + connection);
      connection.setRequestMethod(HttpConnection.POST);
      connection.setRequestProperty("Connection", "close");
      connection.setRequestProperty("User-Agent", "GpsMid");

      connection.setRequestProperty(
          "Authorization",
          "Basic "
              + Base64.encode(Configuration.getOsmUsername() + ":" + Configuration.getOsmPwd()));

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(baos);

      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"file\"; filename=\"" + name + "\"\r\n");
      osw.write("Content-Type: application/octet-stream\r\n\r\n");
      osw.write(new String(gpxOS.toByteArray()));
      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"tags\"\r\n\r\n");
      osw.write(tags + "\r\n");
      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
      osw.write(description + "\r\n");
      osw.write("-----------------------------12132519071893744613145780879\r\n");
      osw.write("Content-Disposition: form-data; name=\"public\"\r\n\r\n");
      osw.write(publicFlag ? "1" : "0" + "\r\n");
      osw.write("-----------------------------12132519071893744613145780879--\r\n");
      osw.flush();
      connection.setRequestProperty("Content-Length", Integer.toString(baos.toByteArray().length));
      connection.setRequestProperty(
          "Content-Type",
          "multipart/form-data; boundary=---------------------------12132519071893744613145780879");
      OutputStream os = connection.openOutputStream();
      os.write(baos.toByteArray());
      os.flush();

      // HTTP Response
      respCode = connection.getResponseCode();
      respMessage = connection.getResponseMessage();
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(
          Locale.get("guigpxosmupload.FailedUploadingGPX") /*Failed uploading GPX: */
              + e.getMessage());
    }

    if (respCode == HttpConnection.HTTP_OK) {
      logger.info("Successfully uploaded GPX");

    } else {
      throw new IOException(
          Locale.get("guigpxosmupload.GPXTraceNotAccepted") /*GPX trace was not accepted (*/
              + respCode
              + "): "
              + respMessage);
    }
  }
Exemplo n.º 30
0
  private void initForm(boolean firstLogin) {
    // #if !polish.blackberry
    this.addCommand(cmdSave);

    if (firstLogin) this.addCommand(cmdCancel);
    else this.addCommand(cmdExit);
    // #endif

    StringItem headLine;
    // #if polish.blackberry
    // #if polish.blackberry.isTouchBuild == false
    // #style .login_headline
    headLine = new StringItem(null, Locale.get("nowplus.client.java.loginform.headline"));
    this.append(headLine);
    // #endif
    // #else
    // #style .login_headline
    headLine = new StringItem(null, Locale.get("nowplus.client.java.loginform.headline"));
    this.append(headLine);

    // #endif

    // #if polish.blackberry && polish.blackberry.isTouchBuild == false
    headLine.setAppearanceMode(Item.PLAIN);
    // #endif

    String usernameString = model.getUserName();
    String passwordString = "";

    // #if username:defined
    // #message Username is set
    // #= usernameString = "${username}";
    // #endif

    // #if password:defined
    // #message Password is set
    // #= passwordString = "${password}";
    // #endif

    if (usernameString == null) usernameString = "";
    if (passwordString == null) passwordString = "";

    // username textfield

    // #if polish.blackberry
    userName =
        UiFactory.createTextField(
            Locale.get("nowplus.client.java.loginform.username.hint"),
            usernameString,
            255,
            TextField.NON_PREDICTIVE,
            this);
    // fix for PBLA-816 Touch device: predictive text while disabling the surepress
    userName.setNoComplexInput(true);
    // #else
    userName = UiFactory.createTextField(null, usernameString, 255, TextField.NON_PREDICTIVE, this);
    // #endif

    UiAccess.setTextfieldHelp(userName, Locale.get("nowplus.client.java.loginform.username.hint"));
    // #if using.native.textfield:defined
    userName.setTitle(Locale.get("nowplus.client.java.loginform.username.hint"));
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(userName);
    // #endif
    // #endif

    if (userName.getText().length() > 0) {
      // Change username textfield into uneditable field once authenticated once to keep users from
      // switching username
      userName.setConstraints(TextField.NON_PREDICTIVE | TextField.UNEDITABLE);

      usernameReadonly = true;

      // #if not polish.blackberry
      // #style .login_textfield_readonly
      // #= userName.setStyle();
      // #endif
    }

    // password textfield

    // #if polish.blackberry
    passWord =
        UiFactory.createTextField(
            Locale.get("nowplus.client.java.loginform.password.hint"),
            passwordString,
            255,
            TextField.NON_PREDICTIVE | TextField.INITIAL_CAPS_NEVER | TextField.PASSWORD,
            this);
    // #else
    passWord =
        UiFactory.createTextField(
            null, passwordString, 255, TextField.INITIAL_CAPS_NEVER | TextField.PASSWORD, this);
    // #endif

    UiAccess.setTextfieldHelp(passWord, Locale.get("nowplus.client.java.loginform.password.hint"));
    // #if using.native.textfield:defined
    passWord.setTitle(Locale.get("nowplus.client.java.loginform.password.hint"));
    // #if (${lowercase(polish.vendor)}==samsung)
    UiFactory.fixSamsungNativeTextField(passWord);
    // #elif polish.device.textField.requires.initialCapsNeverFix:defined
    UiFactory.fixS40NativeTextField(passWord);
    // #endif
    // #endif

    rememberMeItem =
        UiFactory.createChoiceCheckBoxItem(
            Locale.get("nowplus.client.java.loginform.rememberme.label"), Choice.MULTIPLE);
    rememberMeItem.select(model.stayLoggedIn());
    UiFactory.createChoiceGroup(
        null,
        ChoiceGroup.MULTIPLE,
        new ChoiceItem[] {rememberMeItem},
        0,
        rememberMeItem.isSelected,
        null,
        this);

    // #if !polish.blackberry
    if (usernameReadonly) {
      this.focus(passWord);
    }
    // #endif

    // #if polish.blackberry
    // #style ui_factory_button_item
    StringItem loginButton =
        UiFactory.createButtonItem(
            null, cmdSave.getLabel(), (de.enough.polish.ui.Command) cmdSave, null, null);
    append(loginButton);

    if (firstLogin) {
      cmdQuit = cmdCancel;
    } else {
      cmdQuit = cmdExit;
    }
    // #endif
  }