Exemplo n.º 1
0
 public void resetDocument() {
   if (document != null) document.removeUndoableEditListener(view.getUndoListener());
   HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
   document = (HTMLDocument) htmlEditorKit.createDefaultDocument();
   document.addUndoableEditListener(view.getUndoListener());
   view.update();
 }
Exemplo n.º 2
0
 public void dispose() {
   // Dispose of the views
   logger.debug("Disposing of views");
   for (View view : getViews()) {
     view.dispose();
   }
 }
  protected static boolean isTileVisible(
      DrawContext dc, Tile tile, double minDistanceSquared, double maxDistanceSquared) {
    if (!tile.getSector().intersects(dc.getVisibleSector())) return false;

    View view = dc.getView();
    Position eyePos = view.getEyePosition();
    if (eyePos == null) return false;

    Angle lat =
        clampAngle(
            eyePos.getLatitude(),
            tile.getSector().getMinLatitude(),
            tile.getSector().getMaxLatitude());
    Angle lon =
        clampAngle(
            eyePos.getLongitude(),
            tile.getSector().getMinLongitude(),
            tile.getSector().getMaxLongitude());
    Vec4 p = dc.getGlobe().computePointFromPosition(lat, lon, 0d);
    double distSquared = dc.getView().getEyePoint().distanceToSquared3(p);
    //noinspection RedundantIfStatement
    if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) return false;

    return true;
  }
Exemplo n.º 4
0
  public static void testDetermineMergeParticipantsAndMergeCoords4() {
    Address a = Util.createRandomAddress(),
        b = Util.createRandomAddress(),
        c = Util.createRandomAddress(),
        d = Util.createRandomAddress();
    org.jgroups.util.UUID.add(a, "A");
    org.jgroups.util.UUID.add(b, "B");
    org.jgroups.util.UUID.add(c, "C");
    org.jgroups.util.UUID.add(d, "D");

    View v1 = View.create(a, 1, a, b);
    View v2 = View.create(c, 1, c, d);

    Map<Address, View> map = new HashMap<>();
    map.put(a, v1);
    map.put(b, v1);
    map.put(d, v2);

    StringBuilder sb = new StringBuilder("map:\n");
    for (Map.Entry<Address, View> entry : map.entrySet())
      sb.append(entry.getKey() + ": " + entry.getValue() + "\n");
    System.out.println(sb);

    Collection<Address> merge_participants = Util.determineMergeParticipants(map);
    System.out.println("merge_participants = " + merge_participants);
    assert merge_participants.size() == 3;
    assert merge_participants.contains(a)
        && merge_participants.contains(c)
        && merge_participants.contains(d);

    Collection<Address> merge_coords = Util.determineMergeCoords(map);
    System.out.println("merge_coords = " + merge_coords);
    assert merge_coords.size() == 2;
    assert merge_coords.contains(a) && merge_coords.contains(c);
  }
Exemplo n.º 5
0
  /** Execute when new member join or leave Group */
  public void viewAccepted(View v) {
    memberSize = v.size();
    if (mainFrame != null) setTitle();
    members.clear();
    members.addAll(v.getMembers());

    if (v instanceof MergeView) {
      System.out.println("** " + v);

      // This is a simple merge function, which fetches the state from the coordinator
      // on a merge and overwrites all of its own state
      if (useState && !members.isEmpty()) {
        Address coord = members.get(0);
        Address local_addr = channel.getAddress();
        if (local_addr != null && !local_addr.equals(coord)) {
          try {

            // make a copy of our state first
            Map<Point, Color> copy = null;
            if (send_own_state_on_merge) {
              synchronized (drawPanel.state) {
                copy = new LinkedHashMap<Point, Color>(drawPanel.state);
              }
            }
            System.out.println("fetching state from " + coord);
            channel.getState(coord, 5000);
            if (copy != null)
              sendOwnState(copy); // multicast my own state so everybody else has it too
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    } else System.out.println("** View=" + v);
  }
Exemplo n.º 6
0
  /** @param view */
  public static void showSoftKeyboard(final View view) {
    if (view == null) {
      return;
    }

    final Runnable action =
        new Runnable() {
          @Override
          public void run() {
            final InputMethodManager imm =
                (InputMethodManager)
                    view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
          }
        };

    final View.OnFocusChangeListener restoreOnFocusChangeListener = view.getOnFocusChangeListener();

    final View.OnFocusChangeListener temporaryOnFocusChangeListener =
        new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(final View v, final boolean hasFocus) {
            view.setOnFocusChangeListener(restoreOnFocusChangeListener);
            view.postDelayed(action, 25);
          }
        };

    view.setOnFocusChangeListener(temporaryOnFocusChangeListener);
    view.requestFocus();
  }
Exemplo n.º 7
0
 public static void main(String[] args) {
   View viewMain = new View();
   Controller controller = new Controller(viewMain);
   viewMain.setController(controller);
   viewMain.init();
   controller.init();
 }
Exemplo n.º 8
0
 public void createNewDocument() {
   view.selectHtmlTab();
   resetDocument();
   view.setTitle("HTML редактор");
   view.resetUndo();
   currentFile = null;
 }
Exemplo n.º 9
0
  private void showUserHashDialog() {
    String userHash = NavigineApp.Settings.getString("user_hash", "");

    LayoutInflater inflater = getLayoutInflater();
    View view = inflater.inflate(R.layout.user_hash_dialog, null);
    _userEdit = (EditText) view.findViewById(R.id.user_hash_edit);
    _userEdit.setText(userHash);
    _userEdit.setTypeface(Typeface.MONOSPACE);
    // _userEdit.addTextChangedListener(new TextWatcher()
    //  {
    //    public void afterTextChanged(Editable s) { }
    //    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
    //    public void onTextChanged(CharSequence s, int start, int before, int count)
    //    {
    //      String text = _userEdit.getText().toString();
    //      int length  = _userEdit.getText().length();
    //
    //      if (text.endsWith("-"))
    //        return;
    //
    //      if (count <= before)
    //        return;
    //
    //      if (length == 4 || length == 9 || length == 14)
    //      {
    //        _userEdit.setText((text + "-"));
    //        _userEdit.setSelection(length + 1);
    //      }
    //    }
    //  });

    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mContext);
    alertBuilder.setView(view);
    alertBuilder.setTitle("Enter user ID");
    alertBuilder.setNegativeButton(
        getString(R.string.cancel_button),
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dlg, int id) {}
        });

    alertBuilder.setPositiveButton(
        getString(R.string.ok_button),
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dlg, int id) {
            String userHash = _userEdit.getText().toString();
            SharedPreferences.Editor editor = NavigineApp.Settings.edit();
            editor.putString("user_hash", userHash);
            editor.commit();
            NavigineApp.applySettings();
            refreshMapList();
          }
        });

    AlertDialog dialog = alertBuilder.create();
    dialog.setCanceledOnTouchOutside(false);
    dialog.show();
  }
Exemplo n.º 10
0
 public boolean containsView(String id) {
   for (View view : getViews()) {
     if (id.equals(view.getId())) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 11
0
 private void addView(
     Map<String, DesignDocument.View> views, View input, Class<?> repositoryClass) {
   if (input.file().length() > 0) {
     views.put(input.name(), loadViewFromFile(views, input, repositoryClass));
   } else {
     views.put(input.name(), DesignDocument.View.of(input));
   }
 }
Exemplo n.º 12
0
 public void bringViewToFront(String id) {
   for (View view : getViews()) {
     if (view.getId() != null && view.getId().equals(id)) {
       Util.bringToFront(view);
       // Carry on until all views with the specified
       // view id are in front
     }
   }
 }
 private void initPagerItems() {
   for (int i = 0; i < bitmapList.size(); i++) {
     View v = LayoutInflater.from(this).inflate(R.layout.call_activity_itempage, null);
     ImageView imageView = (ImageView) v.findViewById(R.id.contactIv);
     TextView textView = (TextView) v.findViewById(R.id.contactTv);
     imageView.setImageBitmap(bitmapList.get(i));
     textView.setText(nameList.get(i));
     viewArrayList.add(v);
   }
 }
Exemplo n.º 14
0
  public static void testAllEqual() {
    Address[] mbrs = Util.createRandomAddresses(5);
    View[] views = {
      View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs)
    };

    boolean same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert same;

    views =
        new View[] {
          View.create(mbrs[0], 1, mbrs),
          View.create(mbrs[0], 2, mbrs),
          View.create(mbrs[0], 1, mbrs)
        };
    same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert !same;

    views =
        new View[] {
          View.create(mbrs[1], 1, mbrs),
          View.create(mbrs[0], 1, mbrs),
          View.create(mbrs[0], 1, mbrs)
        };
    same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert !same;
  }
Exemplo n.º 15
0
 private DesignDocument.View loadViewFromFile(
     Map<String, DesignDocument.View> views, View input, Class<?> repositoryClass) {
   try {
     InputStream in = repositoryClass.getResourceAsStream(input.file());
     if (in == null) {
       throw new FileNotFoundException("Could not load view file with path: " + input.file());
     }
     String json = IOUtils.toString(in, "UTF-8");
     return mapper().readValue(json.replaceAll("\n", ""), DesignDocument.View.class);
   } catch (Exception e) {
     throw Exceptions.propagate(e);
   }
 }
Exemplo n.º 16
0
  /**
   * Compute the lat/lon position of the view center
   *
   * @param dc the current DrawContext
   * @param view the current View
   * @return the ground position of the view center or null
   */
  protected Position computeGroundPosition(DrawContext dc, View view) {
    if (view == null) return null;

    Position groundPos =
        view.computePositionFromScreenPoint(
            view.getViewport().getWidth() / 2, view.getViewport().getHeight() / 2);
    if (groundPos == null) return null;

    double elevation =
        dc.getGlobe().getElevation(groundPos.getLatitude(), groundPos.getLongitude());
    return new Position(
        groundPos.getLatitude(),
        groundPos.getLongitude(),
        elevation * dc.getVerticalExaggeration());
  }
Exemplo n.º 17
0
 /**
  * Establishes the parent view for this view. Seize this moment to cache the AWT Container I'm in.
  */
 public void setParent(View parent) {
   super.setParent(parent);
   fContainer = parent != null ? getContainer() : null;
   if (parent == null && fComponent != null) {
     fComponent.getParent().remove(fComponent);
     fComponent = null;
   }
 }
Exemplo n.º 18
0
  private synchronized void handleViewChange(View view, boolean makeServer) {
    if (makeServer) initializeNewSymmetricKey(view instanceof MergeView);

    // if view is a bit broken set me as keyserver
    List<Address> members = view.getMembers();
    if (members == null || members.isEmpty() || members.get(0) == null) {
      becomeKeyServer(local_addr, false);
      return;
    }
    // otherwise get keyserver from view controller
    Address tmpKeyServer = view.getMembers().get(0);

    // I am  keyserver - either first member of group or old key server is no more and
    // I have been voted new controller
    if (makeServer || (tmpKeyServer.equals(local_addr))) becomeKeyServer(tmpKeyServer, makeServer);
    else handleNewKeyServer(tmpKeyServer, view instanceof MergeView);
  }
Exemplo n.º 19
0
 public void startFlush(List<Address> flushParticipants, boolean automatic_resume)
     throws Exception {
   if (!flushSupported())
     throw new IllegalStateException(
         "Flush is not supported, add pbcast.FLUSH protocol to your configuration");
   View v = getView();
   boolean validParticipants = v != null && v.getMembers().containsAll(flushParticipants);
   if (!validParticipants)
     throw new IllegalArgumentException(
         "Current view " + v + " does not contain all flush participants " + flushParticipants);
   try {
     down(new Event(Event.SUSPEND, flushParticipants));
   } catch (Exception e) {
     throw new Exception("Flush failed", e.getCause());
   } finally {
     if (automatic_resume) stopFlush(flushParticipants);
   }
 }
Exemplo n.º 20
0
 public void saveDocumentAs() {
   try {
     view.selectHtmlTab();
     JFileChooser jFileChooser = new JFileChooser();
     jFileChooser.setFileFilter(new HTMLFileFilter());
     jFileChooser.setDialogTitle("Save File");
     int n = jFileChooser.showSaveDialog(view);
     if (n == JFileChooser.APPROVE_OPTION) {
       currentFile = jFileChooser.getSelectedFile();
       view.setTitle(currentFile.getName());
       try (FileWriter writer = new FileWriter(currentFile)) {
         new HTMLEditorKit().write(writer, document, 0, document.getLength());
       }
     }
   } catch (Exception e) {
     ExceptionHandler.log(e);
   }
 }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      View row = convertView;
      PhotoGridHolder holder = null;

      if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new PhotoGridHolder();
        holder.itemImageView = (ImageView) row.findViewById(R.id.galleryGridImage);
        row.setTag(holder);
      } else {
        holder = (PhotoGridHolder) row.getTag();
      }
      String filename = getItem(position);
      String path = context.getFilesDir().getAbsolutePath() + "/images/" + filename;

      holder.itemImageView.setImageURI(Uri.parse(path));
      return row;
    }
Exemplo n.º 22
0
 public void saveDocument() {
   try {
     view.selectHtmlTab();
     if (currentFile != null) {
       try (FileWriter writer = new FileWriter(currentFile)) {
         new HTMLEditorKit().write(writer, document, 0, document.getLength());
       }
     } else saveDocumentAs();
   } catch (Exception e) {
     ExceptionHandler.log(e);
   }
 }
Exemplo n.º 23
0
  protected boolean _startFlush(
      final View new_view, int maxAttempts, long randomFloor, long randomCeiling) {
    if (!flushProtocolInStack) return true;
    if (flushInvokerClass != null) {
      try {
        Callable<Boolean> invoker =
            flushInvokerClass.getDeclaredConstructor(View.class).newInstance(new_view);
        return invoker.call();
      } catch (Throwable e) {
        return false;
      }
    }

    try {
      boolean successfulFlush = false;
      boolean validView = new_view != null && new_view.size() > 0;
      if (validView && flushProtocolInStack) {
        int attemptCount = 0;
        while (attemptCount < maxAttempts) {
          try {
            up_prot.up(new Event(Event.SUSPEND, new ArrayList<Address>(new_view.getMembers())));
            successfulFlush = true;
            break;
          } catch (Exception e) {
            Util.sleepRandom(randomFloor, randomCeiling);
            attemptCount++;
          }
        }

        if (successfulFlush) {
          if (log.isTraceEnabled()) log.trace(local_addr + ": successful GMS flush by coordinator");
        } else {
          if (log.isWarnEnabled()) log.warn(local_addr + ": GMS flush by coordinator failed");
        }
      }
      return successfulFlush;
    } catch (Exception e) {
      return false;
    }
  }
  private boolean needToSplit(DrawContext dc, Sector sector) {
    Vec4[] corners = sector.computeCornerPoints(dc.getGlobe(), dc.getVerticalExaggeration());
    Vec4 centerPoint = sector.computeCenterPoint(dc.getGlobe(), dc.getVerticalExaggeration());

    View view = dc.getView();
    double d1 = view.getEyePoint().distanceTo3(corners[0]);
    double d2 = view.getEyePoint().distanceTo3(corners[1]);
    double d3 = view.getEyePoint().distanceTo3(corners[2]);
    double d4 = view.getEyePoint().distanceTo3(corners[3]);
    double d5 = view.getEyePoint().distanceTo3(centerPoint);

    double minDistance = d1;
    if (d2 < minDistance) minDistance = d2;
    if (d3 < minDistance) minDistance = d3;
    if (d4 < minDistance) minDistance = d4;
    if (d5 < minDistance) minDistance = d5;

    double cellSize =
        (Math.PI * sector.getDeltaLatRadians() * dc.getGlobe().getRadius()) / 20; // TODO

    return !(Math.log10(cellSize) <= (Math.log10(minDistance) - this.splitScale));
  }
  /** Force a packet to be sent. */
  public void sendPacket() {
    // Also save stuff to a player's local hard-drive.

    if (activationEvent) {
      View MyView = MyHacker.getView();
      Object[] send =
          new Object[] {new Integer(activationID), new Integer(activationType), MyHacker.getIP()};
      MyView.addFunctionCall(
          new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER, "hacktendoActivate", send));
    } else if (targetEvent) {
      View MyView = MyHacker.getView();
      Object[] send = null;
      if (playerSprite != null)
        send =
            new Object[] {
              new Integer(targetX),
              new Integer(targetY),
              MyHacker.getIP(),
              new Integer(playerSprite.getX()),
              new Integer(playerSprite.getY())
            };
      else
        send =
            new Object[] {
              new Integer(targetX),
              new Integer(targetY),
              MyHacker.getIP(),
              new Integer(targetX),
              new Integer(targetY)
            };

      MyView.addFunctionCall(
          new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER, "hacktendoTarget", send));
    }

    activationEvent = false;
    targetEvent = false;
  }
Exemplo n.º 26
0
  public void openDocument() {
    view.selectHtmlTab();
    JFileChooser fileopen = new JFileChooser();
    fileopen.setFileFilter(new HTMLFileFilter());
    int ret = fileopen.showOpenDialog(view);
    if (ret == JFileChooser.APPROVE_OPTION) {
      currentFile = fileopen.getSelectedFile();
      resetDocument();
      view.setTitle(currentFile.getName());
      try (FileReader reader = new FileReader(currentFile)) {
        new HTMLEditorKit()
            .read(
                reader, document,
                0); // Вызови метод read() из класса HTMLEditorKit, который вычитает данные из
                    // реадера в документ document.

      } catch (Exception e) {
        ExceptionHandler.log(
            e); // Проследи, чтобы метод не кидал исключения. Их необходимо просто логировать.
      }
      view.resetUndo();
    }
  }
Exemplo n.º 27
0
    protected boolean isNavSectorVisible(
        DrawContext dc, double minDistanceSquared, double maxDistanceSquared) {
      if (!navSector.intersects(dc.getVisibleSector())) return false;

      View view = dc.getView();
      Position eyePos = view.getEyePosition();
      if (eyePos == null) return false;

      // check for eyePos over globe
      if (Double.isNaN(eyePos.getLatitude().getDegrees())
          || Double.isNaN(eyePos.getLongitude().getDegrees())) return false;

      Angle lat =
          clampAngle(eyePos.getLatitude(), navSector.getMinLatitude(), navSector.getMaxLatitude());
      Angle lon =
          clampAngle(
              eyePos.getLongitude(), navSector.getMinLongitude(), navSector.getMaxLongitude());
      Vec4 p = dc.getGlobe().computePointFromPosition(lat, lon, 0d);
      double distSquared = dc.getView().getEyePoint().distanceToSquared3(p);
      //noinspection RedundantIfStatement
      if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) return false;

      return true;
    }
Exemplo n.º 28
0
  protected void handleView(View view) {
    this.view = view;
    if (log.isDebugEnabled()) log.debug("view=" + view);
    List<Address> members = view.getMembers();

    _consumerLock.lock();
    try {
      // This removes the consumers that were registered that are now gone
      Iterator<Owner> iterator = _consumersAvailable.iterator();
      while (iterator.hasNext()) {
        Owner owner = iterator.next();
        if (!members.contains(owner.getAddress())) {
          iterator.remove();
          sendRemoveConsumerRequest(owner);
        }
      }

      // This removes the tasks that those requestors are gone
      iterator = _runRequests.iterator();
      while (iterator.hasNext()) {
        Owner owner = iterator.next();
        if (!members.contains(owner.getAddress())) {
          iterator.remove();
          sendRemoveRunRequest(owner);
        }
      }

      synchronized (_awaitingReturn) {
        for (Entry<Owner, Runnable> entry : _awaitingReturn.entrySet()) {
          // The person currently servicing our request has gone down
          // without completing so we have to keep our request alive by
          // sending ours back to the coordinator
          Owner owner = entry.getKey();
          if (!members.contains(owner.getAddress())) {
            Runnable runnable = entry.getValue();
            // We need to register the request id before sending the request back to the coordinator
            // in case if our task gets picked up since another was removed
            _requestId.put(runnable, owner.getRequestId());
            _awaitingConsumer.add(runnable);
            sendToCoordinator(RUN_REQUEST, owner.getRequestId(), local_addr);
          }
        }
      }
    } finally {
      _consumerLock.unlock();
    }
  }
Exemplo n.º 29
0
  /**
   * Computes the next view. Returns a copy that has <code>old_mbrs</code> and <code>suspected_mbrs
   * </code> removed and <code>new_mbrs</code> added.
   */
  public View getNextView(
      Collection<Address> new_mbrs,
      Collection<Address> old_mbrs,
      Collection<Address> suspected_mbrs) {
    synchronized (members) {
      ViewId view_id = view != null ? view.getViewId() : null;
      if (view_id == null) {
        log.error("view_id is null");
        return null; // this should *never* happen !
      }
      long vid = Math.max(view_id.getId(), ltime) + 1;
      ltime = vid;
      Membership tmp_mbrs = tmp_members.copy(); // always operate on the temporary membership
      tmp_mbrs.remove(suspected_mbrs);
      tmp_mbrs.remove(old_mbrs);
      tmp_mbrs.add(new_mbrs);
      List<Address> mbrs = tmp_mbrs.getMembers();
      Address new_coord = local_addr;
      if (!mbrs.isEmpty()) new_coord = mbrs.get(0);
      View v = new View(new_coord, vid, mbrs);

      // Update membership (see DESIGN for explanation):
      tmp_members.set(mbrs);

      // Update joining list (see DESIGN for explanation)
      if (new_mbrs != null) {
        for (Address tmp_mbr : new_mbrs) {
          if (!joining.contains(tmp_mbr)) joining.add(tmp_mbr);
        }
      }

      // Update leaving list (see DESIGN for explanations)
      if (old_mbrs != null) {
        for (Address addr : old_mbrs) {
          if (!leaving.contains(addr)) leaving.add(addr);
        }
      }
      if (suspected_mbrs != null) {
        for (Address addr : suspected_mbrs) {
          if (!leaving.contains(addr)) leaving.add(addr);
        }
      }
      return v;
    }
  }
Exemplo n.º 30
0
  /** My attributes may have changed. */
  public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
    if (DEBUG) System.out.println("ImageView: changedUpdate begin...");
    super.changedUpdate(e, a, f);
    float align = getVerticalAlignment();

    int height = fHeight;
    int width = fWidth;

    initialize(getElement());

    boolean hChanged = fHeight != height;
    boolean wChanged = fWidth != width;
    if (hChanged || wChanged || getVerticalAlignment() != align) {
      if (DEBUG) System.out.println("ImageView: calling preferenceChanged");
      getParent().preferenceChanged(this, hChanged, wChanged);
    }
    if (DEBUG) System.out.println("ImageView: changedUpdate end; valign=" + getVerticalAlignment());
  }