private void updateVisualEditorFields() {
   mWebView.execJavaScriptFromString(
       "ZSSEditor.getField('zss_field_title').setPlainText('" + Utils.escapeHtml(mTitle) + "');");
   mWebView.execJavaScriptFromString(
       "ZSSEditor.getField('zss_field_content').setHTML('"
           + Utils.escapeHtml(mContentHtml)
           + "');");
 }
  private void onFormattingButtonClicked(ToggleButton toggleButton) {
    String tag = toggleButton.getTag().toString();

    if (mWebView.getVisibility() == View.VISIBLE) {
      mWebView.execJavaScriptFromString("ZSSEditor.set" + StringUtils.capitalize(tag) + "();");
    } else {
      applyFormattingHtmlMode(toggleButton, tag);
    }
  }
  @Override
  public void appendMediaFile(
      final MediaFile mediaFile, final String mediaUrl, ImageLoader imageLoader) {
    if (!mDomHasLoaded) {
      // If the DOM hasn't loaded yet, we won't be able to add media to the ZSSEditor
      // Place them in a queue to be handled when the DOM loaded callback is received
      mWaitingMediaFiles.put(mediaUrl, mediaFile);
      return;
    }

    mWebView.post(
        new Runnable() {
          @Override
          public void run() {
            if (URLUtil.isNetworkUrl(mediaUrl)) {
              String mediaId = mediaFile.getMediaId();
              mWebView.execJavaScriptFromString(
                  "ZSSEditor.insertImage('" + mediaUrl + "', '" + mediaId + "');");
            } else {
              String id = mediaFile.getMediaId();
              // String id = mediaFile.getId();
              // 报错在这里
              // 需要把本地url替换成leanote url
              // http://leanote.com/api/file/getImage?fileId=5503537b38f4111dcb0000d1

              String imageUrl = mediaFile.getFileURL();
              mWebView.execJavaScriptFromString(
                  "ZSSEditor.insertLocalImage(" + id + ", '" + imageUrl + "');");
              // mWebView.execJavaScriptFromString("ZSSEditor.setProgressOnImage(" + id + ", " + 0 +
              // ");");
              // mUploadingMediaIds.add(id);
            }
          }
        });
  }
  public void onDomLoaded() {
    mWebView.post(
        new Runnable() {
          public void run() {
            mDomHasLoaded = true;

            mWebView.execJavaScriptFromString(
                "ZSSEditor.getField('zss_field_content').setMultiline('true');");

            // Set title and content placeholder text
            mWebView.execJavaScriptFromString(
                "ZSSEditor.getField('zss_field_title').setPlaceholderText('"
                    + mTitlePlaceholder
                    + "');");
            mWebView.execJavaScriptFromString(
                "ZSSEditor.getField('zss_field_content').setPlaceholderText('"
                    + mContentPlaceholder
                    + "');");

            // Load title and content into ZSSEditor
            updateVisualEditorFields();

            // If there are images that are still in progress (because the editor exited before they
            // completed),
            // set them to failed, so the user can restart them (otherwise they will stay stuck in
            // 'uploading' mode)
            // mWebView.execJavaScriptFromString("ZSSEditor.markAllUploadingImagesAsFailed();");

            // Update the list of failed media uploads
            // mWebView.execJavaScriptFromString("ZSSEditor.getFailedImages();");

            hideActionBarIfNeeded();

            // Reset all format bar buttons (in case they remained active through activity
            // re-creation)
            ToggleButton htmlButton =
                (ToggleButton) getActivity().findViewById(R.id.format_bar_button_html);
            htmlButton.setChecked(false);
            for (ToggleButton button : mTagToggleButtonMap.values()) {
              button.setChecked(false);
            }

            // Add any media files that were placed in a queue due to the DOM not having loaded yet
            if (mWaitingMediaFiles.size() > 0) {
              // Image insertion will only work if the content field is in focus
              // (for a new post, no field is in focus until user action)
              mWebView.execJavaScriptFromString("ZSSEditor.getField('zss_field_content').focus();");

              for (Map.Entry<String, MediaFile> entry : mWaitingMediaFiles.entrySet()) {
                appendMediaFile(entry.getValue(), entry.getKey(), null);
              }
              mWaitingMediaFiles.clear();
            }
          }
        });
  }
  protected void initJsEditor() {
    if (!isAdded()) {
      return;
    }

    String htmlEditor = Utils.getHtmlFromFile(getActivity(), "android-editor.html");
    // htmlEditor = Utils.getHtmlFromFile(getActivity(), "editor-mobile.min.html");

    mWebView.addJavascriptInterface(new JsCallbackReceiver(this), JS_CALLBACK_HANDLER);

    mWebView.loadDataWithBaseURL("file:///android_asset/", htmlEditor, "text/html", "utf-8", "");

    //        if (isMarddown) {
    //            mWebView.execJavaScriptFromString("LEAMD.init();LEAMD.togglePreview();");
    //        }

    if (mDebugModeEnabled) {
      enableWebDebugging(true);
      // Enable the HTML logging button
      setHasOptionsMenu(true);
    }
  }
 public void onSelectionStyleChanged(final Map<String, Boolean> changeMap) {
   mWebView.post(
       new Runnable() {
         public void run() {
           for (Map.Entry<String, Boolean> entry : changeMap.entrySet()) {
             // Handle toggling format bar style buttons
             ToggleButton button = mTagToggleButtonMap.get(entry.getKey());
             if (button != null) {
               button.setChecked(entry.getValue());
             }
           }
         }
       });
 }
 @Override
 public void onResume() {
   super.onResume();
   // If the editor was previously paused and the current orientation is landscape,
   // hide the actionbar because the keyboard is going to appear (even if it was hidden
   // prior to being paused).
   mWebView.setWebViewClient(new LeaWebViewClient());
   if (mEditorWasPaused
       && (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
       && !getResources().getBoolean(R.bool.is_large_tablet_landscape)) {
     mIsKeyboardOpen = true;
     mHideActionBarOnSoftKeyboardUp = true;
     hideActionBarIfNeeded();
   }
 }
 public void onSelectionChanged(final Map<String, String> selectionArgs) {
   final String focusedFieldId = selectionArgs.get("id"); // The field now in focus
   mWebView.post(
       new Runnable() {
         @Override
         public void run() {
           if (!focusedFieldId.isEmpty()) {
             switch (focusedFieldId) {
               case "zss_field_title":
                 updateFormatBarEnabledState(false);
                 break;
               case "zss_field_content":
                 updateFormatBarEnabledState(true);
                 break;
             }
           }
         }
       });
 }
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   if (item.getItemId() == BUTTON_ID_LOG_HTML) {
     if (mDebugModeEnabled) {
       // Log the raw html
       mWebView.post(
           new Runnable() {
             @Override
             public void run() {
               mWebView.execJavaScriptFromString("console.log(document.body.innerHTML);");
             }
           });
     } else {
       AppLog.d(AppLog.T.EDITOR, "Could not execute JavaScript - debug mode not enabled");
     }
     return true;
   } else {
     return super.onOptionsItemSelected(item);
   }
 }
示例#10
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if ((requestCode == LinkDialogFragment.LINK_DIALOG_REQUEST_CODE_ADD
        || requestCode == LinkDialogFragment.LINK_DIALOG_REQUEST_CODE_UPDATE)) {

      if (resultCode == LinkDialogFragment.LINK_DIALOG_REQUEST_CODE_DELETE) {
        mWebView.execJavaScriptFromString("ZSSEditor.unlink();");
        return;
      }

      if (data == null) {
        return;
      }

      Bundle extras = data.getExtras();
      if (extras == null) {
        return;
      }

      String linkUrl = extras.getString("linkURL");
      String linkText = extras.getString("linkText");

      if (linkText == null || linkText.equals("")) {
        linkText = linkUrl;
      }

      if (mSourceView.getVisibility() == View.VISIBLE) {
        Editable content = mSourceViewContent.getText();
        if (content == null) {
          return;
        }

        if (mSelectionStart < mSelectionEnd) {
          content.delete(mSelectionStart, mSelectionEnd);
        }

        String urlHtml = "<a href=\"" + linkUrl + "\">" + linkText + "</a>";

        content.insert(mSelectionStart, urlHtml);
        mSourceViewContent.setSelection(mSelectionStart + urlHtml.length());
      } else {
        String jsMethod;
        if (requestCode == LinkDialogFragment.LINK_DIALOG_REQUEST_CODE_ADD) {
          jsMethod = "ZSSEditor.insertLink";
        } else {
          jsMethod = "ZSSEditor.updateLink";
        }
        mWebView.execJavaScriptFromString(
            jsMethod
                + "('"
                + Utils.escapeHtml(linkUrl)
                + "', '"
                + Utils.escapeHtml(linkText)
                + "');");
      }
    } else if (requestCode == ImageSettingsDialogFragment.IMAGE_SETTINGS_DIALOG_REQUEST_CODE) {
      if (data == null) {
        return;
      }

      Bundle extras = data.getExtras();
      if (extras == null) {
        return;
      }

      final String imageMeta = extras.getString("imageMeta");
      final int imageRemoteId = extras.getInt("imageRemoteId");
      final boolean isFeaturedImage = extras.getBoolean("isFeatured");

      mWebView.post(
          new Runnable() {
            @Override
            public void run() {
              mWebView.execJavaScriptFromString(
                  "ZSSEditor.updateCurrentImageMeta('" + imageMeta + "');");
            }
          });

      if (imageRemoteId != 0) {
        if (isFeaturedImage) {
          mFeaturedImageId = imageRemoteId;
          mEditorFragmentListener.onFeaturedImageChanged(mFeaturedImageId);
        } else {
          // If this image was unset as featured, clear the featured image id
          if (mFeaturedImageId == imageRemoteId) {
            mFeaturedImageId = 0;
            mEditorFragmentListener.onFeaturedImageChanged(mFeaturedImageId);
          }
        }
      }
    }
  }
示例#11
0
  @Override
  public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.format_bar_button_html) {
      // Don't switch to HTML mode if currently uploading media
      //            if (!mUploadingMediaIds.isEmpty()) {
      //                ((ToggleButton) v).setChecked(false);
      //
      //                if (isAdded()) {
      //                    ToastUtils.showToast(getActivity(),
      // R.string.alert_html_toggle_uploading, ToastUtils.Duration.LONG);
      //                }
      //                return;
      //            }

      clearFormatBarButtons();
      updateFormatBarEnabledState(true);

      if (((ToggleButton) v).isChecked()) {
        mSourceViewTitle.setText(getTitle());

        SpannableString spannableContent = new SpannableString(getContent());
        HtmlStyleUtils.styleHtmlForDisplay(spannableContent);
        mSourceViewContent.setText(spannableContent);

        mWebView.setVisibility(View.GONE);
        mSourceView.setVisibility(View.VISIBLE);

        mSourceViewContent.requestFocus();
        mSourceViewContent.setSelection(0);

        InputMethodManager imm =
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE));
        imm.showSoftInput(mSourceViewContent, InputMethodManager.SHOW_IMPLICIT);
      } else {
        mWebView.setVisibility(View.VISIBLE);
        mSourceView.setVisibility(View.GONE);

        mTitle = mSourceViewTitle.getText().toString();
        mContentHtml = mSourceViewContent.getText().toString();
        updateVisualEditorFields();

        mWebView.execJavaScriptFromString("ZSSEditor.getField('zss_field_content').focus();");
      }
    } else if (id == R.id.format_bar_button_media) {
      ((ToggleButton) v).setChecked(false);

      if (mSourceView.getVisibility() == View.VISIBLE) {
        ToastUtils.showToast(
            getActivity(), R.string.alert_insert_image_html_mode, ToastUtils.Duration.LONG);
      } else {
        mEditorFragmentListener.onAddMediaClicked();
        if (isAdded()) {
          getActivity().openContextMenu(mTagToggleButtonMap.get(TAG_FORMAT_BAR_BUTTON_MEDIA));
        }
      }
    } else if (id == R.id.format_bar_button_link) {
      if (!((ToggleButton) v).isChecked()) {
        // The link button was checked when it was pressed; remove the current link
        mWebView.execJavaScriptFromString("ZSSEditor.unlink();");
        return;
      }

      ((ToggleButton) v).setChecked(false);

      LinkDialogFragment linkDialogFragment = new LinkDialogFragment();
      linkDialogFragment.setTargetFragment(this, LinkDialogFragment.LINK_DIALOG_REQUEST_CODE_ADD);

      Bundle dialogBundle = new Bundle();

      // Pass selected text to dialog
      if (mSourceView.getVisibility() == View.VISIBLE) {
        // HTML mode
        mSelectionStart = mSourceViewContent.getSelectionStart();
        mSelectionEnd = mSourceViewContent.getSelectionEnd();

        String selectedText =
            mSourceViewContent.getText().toString().substring(mSelectionStart, mSelectionEnd);
        dialogBundle.putString("linkText", selectedText);
      } else {
        // Visual mode
        mGetSelectedTextCountDownLatch = new CountDownLatch(1);
        mWebView.execJavaScriptFromString("ZSSEditor.execFunctionForResult('getSelectedText');");
        try {
          if (mGetSelectedTextCountDownLatch.await(1, TimeUnit.SECONDS)) {
            dialogBundle.putString("linkText", mJavaScriptResult);
          }
        } catch (InterruptedException e) {
          AppLog.d(AppLog.T.EDITOR, "Failed to obtain selected text from JS editor.");
        }
      }

      linkDialogFragment.setArguments(dialogBundle);
      linkDialogFragment.show(getFragmentManager(), "LinkDialogFragment");
    } else {
      if (v instanceof ToggleButton) {
        onFormattingButtonClicked((ToggleButton) v);
      }
    }
  }
示例#12
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_editor, container, false);

    Log.i("enter...", "new editor");
    // Setup hiding the action bar when the soft keyboard is displayed for narrow viewports
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
        && !getResources().getBoolean(R.bool.is_large_tablet_landscape)) {
      mHideActionBarOnSoftKeyboardUp = true;
    }

    mWaitingMediaFiles = new ConcurrentHashMap<>();
    // mUploadingMediaIds = new HashSet<>();
    mFailedMediaIds = new HashSet<>();

    // -- WebView configuration

    mWebView = (EditorWebViewAbstract) view.findViewById(R.id.webview);

    mWebView.setOnTouchListener(this);
    mWebView.setOnImeBackListener(this);

    LeaWebViewClient webViewClient = new LeaWebViewClient();
    webViewClient.setImageLoadListener(this);
    // mWebView.setWebViewClient(webViewClient);

    // Ensure that the content field is always filling the remaining screen space
    mWebView.addOnLayoutChangeListener(
        new View.OnLayoutChangeListener() {
          @Override
          public void onLayoutChange(
              View v,
              int left,
              int top,
              int right,
              int bottom,
              int oldLeft,
              int oldTop,
              int oldRight,
              int oldBottom) {
            mWebView.post(
                new Runnable() {
                  @Override
                  public void run() {
                    // mWebView.execJavaScriptFromString("ZSSEditor.init()");
                    mWebView.execJavaScriptFromString("ZSSEditor.refreshVisibleViewportSize();");
                  }
                });
          }
        });

    mEditorFragmentListener.onEditorFragmentInitialized();

    initJsEditor();

    if (savedInstanceState != null) {
      setTitle(savedInstanceState.getCharSequence(KEY_TITLE));
      setContent(savedInstanceState.getCharSequence(KEY_CONTENT));
    }

    // -- HTML mode configuration

    mSourceView = view.findViewById(R.id.sourceview);
    mSourceViewTitle = (SourceViewEditText) view.findViewById(R.id.sourceview_title);
    mSourceViewContent = (SourceViewEditText) view.findViewById(R.id.sourceview_content);

    // Toggle format bar on/off as user changes focus between title and content in HTML mode
    mSourceViewTitle.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View v, boolean hasFocus) {
            updateFormatBarEnabledState(!hasFocus);
          }
        });

    mSourceViewTitle.setOnTouchListener(this);
    mSourceViewContent.setOnTouchListener(this);

    mSourceViewTitle.setOnImeBackListener(this);
    mSourceViewContent.setOnImeBackListener(this);

    mSourceViewContent.addTextChangedListener(new HtmlStyleTextWatcher());

    mSourceViewTitle.setHint(mTitlePlaceholder);
    mSourceViewContent.setHint("<p>" + mContentPlaceholder + "</p>");

    // -- Format bar configuration

    setupFormatBarButtonMap(view);

    return view;
  }
示例#13
0
 @Override
 public void onImageLoaded(String localFileId) {
   AppLog.i("download, reload webview...");
   mWebView.reload();
 }